Scan with limiting result set
[idzebra-moved-to-github.git] / index / zebraapi.c
1 /* $Id: zebraapi.c,v 1.91 2003-03-06 11:58:08 adam Exp $
2    Copyright (C) 1995,1996,1997,1998,1999,2000,2001,2002,2003
3    Index Data Aps
4
5 This file is part of the Zebra server.
6
7 Zebra is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
10 version.
11
12 Zebra is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Zebra; see the file LICENSE.zebra.  If not, write to the
19 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20 02111-1307, USA.
21 */
22
23
24
25 #include <assert.h>
26 #include <stdio.h>
27 #ifdef WIN32
28 #include <io.h>
29 #include <process.h>
30 #include <direct.h>
31 #else
32 #include <unistd.h>
33 #endif
34
35 #include <yaz/diagbib1.h>
36 #include <yaz/pquery.h>
37 #include <yaz/sortspec.h>
38 #include "index.h"
39 #include <charmap.h>
40 #include "zebraapi.h"
41
42 /* simple asserts to validate the most essential input args */
43 #define ASSERTZH assert(zh && zh->service)
44 #define ASSERTZHRES assert(zh && zh->service && zh->res)
45 #define ASSERTZS assert(zs)
46
47 static Res zebra_open_res (ZebraHandle zh);
48 static void zebra_close_res (ZebraHandle zh);
49
50
51 static void zebra_chdir (ZebraService zs)
52 {
53     const char *dir ;
54     ASSERTZS;
55     dir = res_get (zs->global_res, "chdir");
56     if (!dir)
57         return;
58     logf (LOG_DEBUG, "chdir %s", dir);
59 #ifdef WIN32
60     _chdir(dir);
61 #else
62     chdir (dir);
63 #endif
64 }
65
66 static void zebra_flush_reg (ZebraHandle zh)
67 {
68     ASSERTZH;
69     zh->errCode=0;
70     zebraExplain_flush (zh->reg->zei, zh);
71     
72     extract_flushWriteKeys (zh);
73     zebra_index_merge (zh);
74 }
75
76 static struct zebra_register *zebra_register_open (ZebraService zs, 
77                                                    const char *name,
78                                                    int rw, int useshadow,
79                                                    Res res,
80                                                    const char *reg_path);
81 static void zebra_register_close (ZebraService zs, struct zebra_register *reg);
82
83 ZebraHandle zebra_open (ZebraService zs)
84 {
85     ZebraHandle zh;
86     const char *default_encoding;
87     ASSERTZS;
88
89     if (!zs)
90         return 0;
91
92     zh = (ZebraHandle) xmalloc (sizeof(*zh));
93     yaz_log (LOG_DEBUG, "zebra_open zs=%p returns %p", zs, zh);
94
95     zh->service = zs;
96     zh->reg = 0;          /* no register attached yet */
97     zh->sets = 0;
98     zh->destroyed = 0;
99     zh->errCode = 0;
100     zh->errString = 0;
101     zh->res = 0; 
102
103     zh->reg_name = xstrdup ("");
104     zh->path_reg = 0;
105     zh->num_basenames = 0;
106     zh->basenames = 0;
107
108     zh->trans_no = 0;
109     zh->trans_w_no = 0;
110
111     zh->lock_normal = 0;
112     zh->lock_shadow = 0;
113
114     zh->admin_databaseName = 0;
115
116     zh->shadow_enable = 1;
117
118     default_encoding = res_get_def(zs->global_res, "encoding", "ISO-8859-1");
119     zh->record_encoding = xstrdup (default_encoding);
120
121     zh->iconv_to_utf8 =
122         yaz_iconv_open ("UTF-8", default_encoding);
123     if (zh->iconv_to_utf8 == 0)
124         yaz_log (LOG_WARN, "iconv: %s to UTF-8 unsupported",
125            default_encoding);
126     zh->iconv_from_utf8 =
127         yaz_iconv_open (default_encoding, "UTF-8");
128     if (zh->iconv_to_utf8 == 0)
129         yaz_log (LOG_WARN, "iconv: UTF-8 to %s unsupported",
130            default_encoding);
131
132     zebra_mutex_cond_lock (&zs->session_lock);
133
134     zh->next = zs->sessions;
135     zs->sessions = zh;
136
137     zebra_mutex_cond_unlock (&zs->session_lock);
138
139     return zh;
140 }
141
142 ZebraService zebra_start (const char *configName)
143 {
144     Res res;
145
146     yaz_log (LOG_LOG, "zebra_start %s", configName);
147
148     if ((res = res_open (configName, 0)))
149     {
150         ZebraService zh = xmalloc (sizeof(*zh));
151
152         yaz_log (LOG_DEBUG, "Read resources `%s'", configName);
153         
154         zh->global_res = res;
155         zh->configName = xstrdup(configName);
156         zh->sessions = 0;
157         
158         zebra_chdir (zh);
159         
160         zebra_mutex_cond_init (&zh->session_lock);
161         if (!res_get (zh->global_res, "passwd"))
162             zh->passwd_db = NULL;
163         else
164         {
165             zh->passwd_db = passwd_db_open ();
166             if (!zh->passwd_db)
167                 logf (LOG_WARN|LOG_ERRNO, "passwd_db_open failed");
168             else
169                 passwd_db_file (zh->passwd_db,
170                                 res_get (zh->global_res, "passwd"));
171         }
172         zh->path_root = res_get (zh->global_res, "root");
173         return zh;
174     }
175     return 0;
176 }
177
178 static
179 struct zebra_register *zebra_register_open (ZebraService zs, const char *name,
180                                             int rw, int useshadow, Res res,
181                                             const char *reg_path)
182 {
183     struct zebra_register *reg;
184     int record_compression = REC_COMPRESS_NONE;
185     char *recordCompression = 0;
186
187     ASSERTZS;
188     
189     reg = xmalloc (sizeof(*reg));
190
191     assert (name);
192     reg->name = xstrdup (name);
193
194     reg->seqno = 0;
195     reg->last_val = 0;
196
197     assert (res);
198
199     yaz_log (LOG_DEBUG, "zebra_register_open rw = %d useshadow=%d p=%p",
200              rw, useshadow, reg);
201
202     reg->dh = data1_createx (DATA1_FLAG_XML);
203     if (!reg->dh)
204         return 0;
205     reg->bfs = bfs_create (res_get (res, "register"), reg_path);
206     if (!reg->bfs)
207     {
208         data1_destroy(reg->dh);
209         return 0;
210     }
211     if (useshadow)
212         bf_cache (reg->bfs, res_get (res, "shadow"));
213     data1_set_tabpath (reg->dh, res_get_def(res, "profilePath",
214                                             DEFAULT_PROFILE_PATH));
215     data1_set_tabroot (reg->dh, reg_path);
216     reg->recTypes = recTypes_init (reg->dh);
217     recTypes_default_handlers (reg->recTypes);
218
219     reg->zebra_maps = zebra_maps_open (res, reg_path);
220     reg->rank_classes = NULL;
221
222     reg->key_buf = 0;
223
224     reg->keys.buf_max = 0;
225     reg->keys.buf = 0;
226     reg->sortKeys.buf = 0;
227     reg->sortKeys.buf_max = 0;
228
229     reg->records = 0;
230     reg->dict = 0;
231     reg->sortIdx = 0;
232     reg->isams = 0;
233     reg->matchDict = 0;
234     reg->isam = 0;
235     reg->isamc = 0;
236     reg->isamd = 0;
237     reg->isamb = 0;
238     reg->zei = 0;
239     reg->matchDict = 0;
240     reg->key_file_no = 0;
241     
242     zebraRankInstall (reg, rank1_class);
243     zebraRankInstall (reg, rankzv_class);
244
245     recordCompression = res_get_def (res, "recordCompression", "none");
246     if (!strcmp (recordCompression, "none"))
247         record_compression = REC_COMPRESS_NONE;
248     if (!strcmp (recordCompression, "bzip2"))
249         record_compression = REC_COMPRESS_BZIP2;
250
251     if (!(reg->records = rec_open (reg->bfs, rw, record_compression)))
252     {
253         logf (LOG_WARN, "rec_open");
254         return 0;
255     }
256     if (rw)
257     {
258         reg->matchDict = dict_open (reg->bfs, GMATCH_DICT, 20, 1, 0);
259     }
260     if (!(reg->dict = dict_open (reg->bfs, FNAME_DICT, 40, rw, 0)))
261     {
262         logf (LOG_WARN, "dict_open");
263         return 0;
264     }
265     if (!(reg->sortIdx = sortIdx_open (reg->bfs, rw)))
266     {
267         logf (LOG_WARN, "sortIdx_open");
268         return 0;
269     }
270     if (res_get_match (res, "isam", "s", ISAM_DEFAULT))
271     {
272         struct ISAMS_M_s isams_m;
273         if (!(reg->isams = isams_open (reg->bfs, FNAME_ISAMS, rw,
274                                       key_isams_m(res, &isams_m))))
275         {
276             logf (LOG_WARN, "isams_open");
277             return 0;
278         }
279     }
280     if (res_get_match (res, "isam", "i", ISAM_DEFAULT))
281     {
282         if (!(reg->isam = is_open (reg->bfs, FNAME_ISAM, key_compare, rw,
283                                   sizeof (struct it_key), res)))
284         {
285             logf (LOG_WARN, "is_open");
286             return 0;
287         }
288     }
289     if (res_get_match (res, "isam", "c", ISAM_DEFAULT))
290     {
291         struct ISAMC_M_s isamc_m;
292         if (!(reg->isamc = isc_open (reg->bfs, FNAME_ISAMC,
293                                     rw, key_isamc_m(res, &isamc_m))))
294         {
295             logf (LOG_WARN, "isc_open");
296             return 0;
297         }
298     }
299     if (res_get_match (res, "isam", "d", ISAM_DEFAULT))
300     {
301         struct ISAMD_M_s isamd_m;
302         
303         if (!(reg->isamd = isamd_open (reg->bfs, FNAME_ISAMD,
304                                       rw, key_isamd_m(res, &isamd_m))))
305         {
306             logf (LOG_WARN, "isamd_open");
307             return 0;
308         }
309     }
310     if (res_get_match (res, "isam", "b", ISAM_DEFAULT))
311     {
312         struct ISAMC_M_s isamc_m;
313         
314         if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
315                                        rw, key_isamc_m(res, &isamc_m), 0)))
316         {
317             logf (LOG_WARN, "isamb_open");
318             return 0;
319         }
320     }
321     if (res_get_match (res, "isam", "bc", ISAM_DEFAULT))
322     {
323         struct ISAMC_M_s isamc_m;
324         
325         if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
326                                        rw, key_isamc_m(res, &isamc_m), 1)))
327         {
328             logf (LOG_WARN, "isamb_open");
329             return 0;
330         }
331     }
332     if (res_get_match (res, "isam", "null", ISAM_DEFAULT))
333     {
334         struct ISAMC_M_s isamc_m;
335         
336         if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
337                                        rw, key_isamc_m(res, &isamc_m), -1)))
338         {
339             logf (LOG_WARN, "isamb_open");
340             return 0;
341         }
342     }
343     reg->zei = zebraExplain_open (reg->records, reg->dh,
344                                   res, rw, reg,
345                                   explain_extract);
346     if (!reg->zei)
347     {
348         logf (LOG_WARN, "Cannot obtain EXPLAIN information");
349         return 0;
350     }
351     reg->active = 2;
352     yaz_log (LOG_DEBUG, "zebra_register_open ok p=%p", reg);
353     return reg;
354 }
355
356 void zebra_admin_shutdown (ZebraHandle zh)
357 {
358     ASSERTZH;
359     zh->errCode=0;
360
361     zebra_mutex_cond_lock (&zh->service->session_lock);
362     zh->service->stop_flag = 1;
363     zebra_mutex_cond_unlock (&zh->service->session_lock);
364 }
365
366 void zebra_admin_start (ZebraHandle zh)
367 {
368     ZebraService zs;
369     ASSERTZH;
370     zh->errCode=0;
371     zs = zh->service;
372     zebra_mutex_cond_lock (&zs->session_lock);
373     zebra_mutex_cond_unlock (&zs->session_lock);
374 }
375
376 static void zebra_register_close (ZebraService zs, struct zebra_register *reg)
377 {
378     ASSERTZS;
379     yaz_log(LOG_DEBUG, "zebra_register_close p=%p", reg);
380     reg->stop_flag = 0;
381     zebra_chdir (zs);
382     if (reg->records)
383     {
384         zebraExplain_close (reg->zei);
385         dict_close (reg->dict);
386         if (reg->matchDict)
387             dict_close (reg->matchDict);
388         sortIdx_close (reg->sortIdx);
389         if (reg->isams)
390             isams_close (reg->isams);
391         if (reg->isam)
392             is_close (reg->isam);
393         if (reg->isamc)
394             isc_close (reg->isamc);
395         if (reg->isamd)
396             isamd_close (reg->isamd);
397         if (reg->isamb)
398             isamb_close (reg->isamb);
399         rec_close (&reg->records);
400     }
401
402     recTypes_destroy (reg->recTypes);
403     zebra_maps_close (reg->zebra_maps);
404     zebraRankDestroy (reg);
405     bfs_destroy (reg->bfs);
406     data1_destroy (reg->dh);
407
408     xfree (reg->sortKeys.buf);
409     xfree (reg->keys.buf);
410
411     xfree (reg->key_buf);
412     xfree (reg->name);
413     xfree (reg);
414 }
415
416 void zebra_stop(ZebraService zs)
417 {
418     if (!zs)
419         return ;
420     yaz_log (LOG_LOG, "zebra_stop");
421
422     while (zs->sessions)
423     {
424         zebra_close (zs->sessions);
425     }
426         
427     zebra_mutex_cond_destroy (&zs->session_lock);
428
429     if (zs->passwd_db)
430         passwd_db_close (zs->passwd_db);
431
432     res_close (zs->global_res);
433     xfree (zs->configName);
434     xfree (zs->path_root);
435     xfree (zs);
436 }
437
438 void zebra_close (ZebraHandle zh)
439 {
440     ZebraService zs;
441     struct zebra_session **sp;
442     int i;
443
444     if (!zh)
445         return;
446     ASSERTZH;
447     zh->errCode=0;
448     
449     zs = zh->service;
450     yaz_log (LOG_DEBUG, "zebra_close zh=%p", zh);
451     if (!zh)
452         return ;
453     resultSetDestroy (zh, -1, 0, 0);
454
455     if (zh->reg)
456         zebra_register_close (zh->service, zh->reg);
457     zebra_close_res (zh);
458
459     xfree (zh->record_encoding);
460
461     for (i = 0; i < zh->num_basenames; i++)
462         xfree (zh->basenames[i]);
463     xfree (zh->basenames);
464
465     if (zh->iconv_to_utf8 != 0)
466         yaz_iconv_close (zh->iconv_to_utf8);
467     if (zh->iconv_from_utf8 != 0)
468         yaz_iconv_close (zh->iconv_from_utf8);
469
470     xfree (zh->admin_databaseName);
471     zebra_mutex_cond_lock (&zs->session_lock);
472     zebra_lock_destroy (zh->lock_normal);
473     zebra_lock_destroy (zh->lock_shadow);
474     sp = &zs->sessions;
475     while (1)
476     {
477         assert (*sp);
478         if (*sp == zh)
479         {
480             *sp = (*sp)->next;
481             break;
482         }
483         sp = &(*sp)->next;
484     }
485     zebra_mutex_cond_unlock (&zs->session_lock);
486     xfree (zh->reg_name);
487     zh->service=0; /* more likely to trigger an assert */
488     xfree (zh);
489 }
490
491 struct map_baseinfo {
492     ZebraHandle zh;
493     NMEM mem;
494     int num_bases;
495     char **basenames;
496     int new_num_bases;
497     char **new_basenames;
498     int new_num_max;
499 };
500
501 static Res zebra_open_res (ZebraHandle zh)
502 {
503     Res res = 0;
504     char fname[512];
505     ASSERTZH;
506     zh->errCode=0;
507
508     if (zh->path_reg)
509     {
510         sprintf (fname, "%.200s/zebra.cfg", zh->path_reg);
511         res = res_open (fname, zh->service->global_res);
512         if (!res)
513             res = zh->service->global_res;
514     }
515     else if (*zh->reg_name == 0)
516     {
517         res = zh->service->global_res;
518     }
519     else
520     {
521         yaz_log (LOG_WARN, "no register root specified");
522         return 0;  /* no path for register - fail! */
523     }
524     return res;
525 }
526
527 static void zebra_close_res (ZebraHandle zh)
528 {
529     ASSERTZH;
530     zh->errCode=0;
531     if (zh->res != zh->service->global_res)
532         res_close (zh->res);
533     zh->res = 0;
534 }
535
536 static int zebra_select_register (ZebraHandle zh, const char *new_reg)
537 {
538     ASSERTZH;
539     zh->errCode=0;
540     if (zh->res && strcmp (zh->reg_name, new_reg) == 0)
541         return 0;
542     if (!zh->res)
543     {
544         assert (zh->reg == 0);
545         assert (*zh->reg_name == 0);
546     }
547     else
548     {
549         if (zh->reg)
550         {
551             resultSetInvalidate (zh);
552             zebra_register_close (zh->service, zh->reg);
553             zh->reg = 0;
554         }
555         zebra_close_res(zh);
556     }
557     xfree (zh->reg_name);
558     zh->reg_name = xstrdup (new_reg);
559
560     xfree (zh->path_reg);
561     zh->path_reg = 0;
562     if (zh->service->path_root)
563     {
564         zh->path_reg = xmalloc (strlen(zh->service->path_root) + 
565                                 strlen(zh->reg_name) + 3);
566         strcpy (zh->path_reg, zh->service->path_root);
567         if (*zh->reg_name)
568         {
569             strcat (zh->path_reg, "/");
570             strcat (zh->path_reg, zh->reg_name);
571         }
572     }
573     zh->res = zebra_open_res (zh);
574     
575     if (zh->lock_normal)
576         zebra_lock_destroy (zh->lock_normal);
577     zh->lock_normal = 0;
578
579     if (zh->lock_shadow)
580         zebra_lock_destroy (zh->lock_shadow);
581     zh->lock_shadow = 0;
582
583     if (zh->res)
584     {
585         char fname[512];
586         const char *lock_area  =res_get (zh->res, "lockDir");
587         
588         if (!lock_area && zh->path_reg)
589             res_put (zh->res, "lockDir", zh->path_reg);
590         sprintf (fname, "norm.%s.LCK", zh->reg_name);
591         zh->lock_normal =
592             zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
593         
594         sprintf (fname, "shadow.%s.LCK", zh->reg_name);
595         zh->lock_shadow =
596             zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
597
598     }
599     return 1;
600 }
601
602 void map_basenames_func (void *vp, const char *name, const char *value)
603 {
604     struct map_baseinfo *p = (struct map_baseinfo *) vp;
605     int i, no;
606     char fromdb[128], todb[8][128];
607     
608     no =
609         sscanf (value, "%127s %127s %127s %127s %127s %127s %127s %127s %127s",
610                 fromdb, todb[0], todb[1], todb[2], todb[3], todb[4],
611                 todb[5], todb[6], todb[7]);
612     if (no < 2)
613         return ;
614     no--;
615     for (i = 0; i<p->num_bases; i++)
616         if (p->basenames[i] && !STRCASECMP (p->basenames[i], fromdb))
617         {
618             p->basenames[i] = 0;
619             for (i = 0; i < no; i++)
620             {
621                 if (p->new_num_bases == p->new_num_max)
622                     return;
623                 p->new_basenames[(p->new_num_bases)++] = 
624                     nmem_strdup (p->mem, todb[i]);
625             }
626             return;
627         }
628 }
629
630 void map_basenames (ZebraHandle zh, ODR stream,
631                     int *num_bases, char ***basenames)
632 {
633     struct map_baseinfo info;
634     struct map_baseinfo *p = &info;
635     int i;
636     ASSERTZH;
637     zh->errCode=0;
638
639     info.zh = zh;
640     info.num_bases = *num_bases;
641     info.basenames = *basenames;
642     info.new_num_max = 128;
643     info.new_num_bases = 0;
644     info.new_basenames = (char **)
645         odr_malloc (stream, sizeof(*info.new_basenames) * info.new_num_max);
646     info.mem = stream->mem;
647
648     res_trav (zh->service->global_res, "mapdb", &info, map_basenames_func);
649     
650     for (i = 0; i<p->num_bases; i++)
651         if (p->basenames[i] && p->new_num_bases < p->new_num_max)
652         {
653             p->new_basenames[(p->new_num_bases)++] = 
654                 nmem_strdup (p->mem, p->basenames[i]);
655         }
656     *num_bases = info.new_num_bases;
657     *basenames = info.new_basenames;
658     for (i = 0; i<*num_bases; i++)
659         logf (LOG_LOG, "base %s", (*basenames)[i]);
660 }
661
662 int zebra_select_database (ZebraHandle zh, const char *basename)
663 {
664     ASSERTZH;
665     zh->errCode=0;
666     return zebra_select_databases (zh, 1, &basename);
667 }
668
669 int zebra_select_databases (ZebraHandle zh, int num_bases,
670                             const char **basenames)
671 {
672     int i;
673     const char *cp;
674     int len = 0;
675     char *new_reg = 0;
676     ASSERTZH;
677     zh->errCode=0;
678     
679     if (num_bases < 1)
680     {
681         zh->errCode = 23;
682         return -1;
683     }
684     for (i = 0; i < zh->num_basenames; i++)
685         xfree (zh->basenames[i]);
686     xfree (zh->basenames);
687     
688     zh->num_basenames = num_bases;
689     zh->basenames = xmalloc (zh->num_basenames * sizeof(*zh->basenames));
690     for (i = 0; i < zh->num_basenames; i++)
691         zh->basenames[i] = xstrdup (basenames[i]);
692
693     cp = strrchr(basenames[0], '/');
694     if (cp)
695     {
696         len = cp - basenames[0];
697         new_reg = xmalloc (len + 1);
698         memcpy (new_reg, basenames[0], len);
699         new_reg[len] = '\0';
700     }
701     else
702         new_reg = xstrdup ("");
703     for (i = 1; i<num_bases; i++)
704     {
705         const char *cp1;
706
707         cp1 = strrchr (basenames[i], '/');
708         if (cp)
709         {
710             if (!cp1)
711             {
712                 zh->errCode = 23;
713                 return -1;
714             }
715             if (len != cp1 - basenames[i] ||
716                 memcmp (basenames[i], new_reg, len))
717             {
718                 zh->errCode = 23;
719                 return -1;
720             }
721         }
722         else
723         {
724             if (cp1)
725             {
726                 zh->errCode = 23;
727                 return -1;
728             }
729         }
730     }
731     zebra_select_register (zh, new_reg);
732     xfree (new_reg);
733     if (!zh->res)
734     {
735         zh->errCode = 109;
736         return -1;
737     }
738     if (!zh->lock_normal || !zh->lock_shadow)
739     {
740         zh->errCode = 2;
741         return -1;
742     }
743     return 0;
744 }
745
746 void zebra_search_rpn (ZebraHandle zh, ODR decode, ODR stream,
747                        Z_RPNQuery *query, const char *setname, int *hits)
748 {
749     ASSERTZH;
750     zh->errCode=0;
751     zh->hits = 0;
752     *hits = 0;
753
754     if (zebra_begin_read (zh))
755         return;
756     resultSetAddRPN (zh, decode, stream, query, 
757                      zh->num_basenames, zh->basenames, setname);
758
759     zebra_end_read (zh);
760
761     *hits = zh->hits;
762 }
763
764 void zebra_records_retrieve (ZebraHandle zh, ODR stream,
765                              const char *setname, Z_RecordComposition *comp,
766                              oid_value input_format, int num_recs,
767                              ZebraRetrievalRecord *recs)
768 {
769     ZebraPosSet poset;
770     int i, *pos_array;
771     ASSERTZH;
772     zh->errCode=0;
773
774     if (!zh->res)
775     {
776         zh->errCode = 30;
777         zh->errString = odr_strdup (stream, setname);
778         return;
779     }
780     
781     zh->errCode = 0;
782
783     if (zebra_begin_read (zh))
784         return;
785
786     pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
787     for (i = 0; i<num_recs; i++)
788         pos_array[i] = recs[i].position;
789     poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
790     if (!poset)
791     {
792         logf (LOG_DEBUG, "zebraPosSetCreate error");
793         zh->errCode = 30;
794         zh->errString = nmem_strdup (stream->mem, setname);
795     }
796     else
797     {
798         for (i = 0; i<num_recs; i++)
799         {
800             if (poset[i].term)
801             {
802                 recs[i].errCode = 0;
803                 recs[i].format = VAL_SUTRS;
804                 recs[i].len = strlen(poset[i].term);
805                 recs[i].buf = poset[i].term;
806                 recs[i].base = poset[i].db;
807             }
808             else if (poset[i].sysno)
809             {
810                 recs[i].errCode =
811                     zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
812                                         stream, input_format, comp,
813                                         &recs[i].format, &recs[i].buf,
814                                         &recs[i].len,
815                                         &recs[i].base);
816                 recs[i].errString = NULL;
817             }
818             else
819             {
820                 char num_str[20];
821
822                 sprintf (num_str, "%d", pos_array[i]);  
823                 zh->errCode = 13;
824                 zh->errString = odr_strdup (stream, num_str);
825                 break;
826             }
827         }
828         zebraPosSetDestroy (zh, poset, num_recs);
829     }
830     zebra_end_read (zh);
831     xfree (pos_array);
832 }
833
834 void zebra_scan (ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
835                  oid_value attributeset,
836                  int *position, int *num_entries, ZebraScanEntry **entries,
837                  int *is_partial)
838 {
839     ASSERTZH;
840     zh->errCode=0;
841     if (zebra_begin_read (zh))
842     {
843         *entries = 0;
844         *num_entries = 0;
845         return;
846     }
847     rpn_scan (zh, stream, zapt, attributeset,
848               zh->num_basenames, zh->basenames, position,
849               num_entries, entries, is_partial, 0, 0);
850     zebra_end_read (zh);
851 }
852
853 void zebra_sort (ZebraHandle zh, ODR stream,
854                  int num_input_setnames, const char **input_setnames,
855                  const char *output_setname, Z_SortKeySpecList *sort_sequence,
856                  int *sort_status)
857 {
858     ASSERTZH;
859     zh->errCode=0;
860     if (zebra_begin_read (zh))
861         return;
862     resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
863                    output_setname, sort_sequence, sort_status);
864     zebra_end_read(zh);
865 }
866
867 int zebra_deleleResultSet(ZebraHandle zh, int function,
868                           int num_setnames, char **setnames,
869                           int *statuses)
870 {
871     int i, status;
872     ASSERTZH;
873     zh->errCode=0;
874     if (zebra_begin_read(zh))
875         return Z_DeleteStatus_systemProblemAtTarget;
876     switch (function)
877     {
878     case Z_DeleteRequest_list:
879         resultSetDestroy (zh, num_setnames, setnames, statuses);
880         break;
881     case Z_DeleteRequest_all:
882         resultSetDestroy (zh, -1, 0, statuses);
883         break;
884     }
885     zebra_end_read (zh);
886     status = Z_DeleteStatus_success;
887     for (i = 0; i<num_setnames; i++)
888         if (statuses[i] == Z_DeleteStatus_resultSetDidNotExist)
889             status = statuses[i];
890     return status;
891 }
892
893 int zebra_errCode (ZebraHandle zh)
894 {
895     if (zh)
896         return zh->errCode;
897     return 0; 
898 }
899
900 const char *zebra_errString (ZebraHandle zh)
901 {
902     if (zh)
903         return diagbib1_str (zh->errCode);
904     return "";
905 }
906
907 char *zebra_errAdd (ZebraHandle zh)
908 {
909     if (zh)
910         return zh->errString;
911     return "";
912 }
913
914 int zebra_auth (ZebraHandle zh, const char *user, const char *pass)
915 {
916     ZebraService zs;
917     ASSERTZH;
918     zh->errCode=0;
919     zs= zh->service;
920     if (!zs->passwd_db || !passwd_db_auth (zs->passwd_db, user, pass))
921     {
922         logf(LOG_APP,"AUTHOK:%s", user?user:"ANONYMOUS");
923         return 0;
924     }
925
926     logf(LOG_APP,"AUTHFAIL:%s", user?user:"ANONYMOUS");
927     return 1;
928 }
929
930 void zebra_admin_import_begin (ZebraHandle zh, const char *database,
931                                const char *record_type)
932 {
933     ASSERTZH;
934     zh->errCode=0;
935     if (zebra_select_database(zh, database))
936         return;
937     zebra_begin_trans (zh, 1);
938     xfree (zh->admin_databaseName);
939     zh->admin_databaseName = xstrdup(database);
940 }
941
942 void zebra_admin_import_end (ZebraHandle zh)
943 {
944     ASSERTZH;
945     zh->errCode=0;
946     zebra_end_trans (zh);
947 }
948
949 void zebra_admin_import_segment (ZebraHandle zh, Z_Segment *segment)
950 {
951     int sysno;
952     int i;
953     ASSERTZH;
954     zh->errCode=0;
955     for (i = 0; i<segment->num_segmentRecords; i++)
956     {
957         Z_NamePlusRecord *npr = segment->segmentRecords[i];
958         const char *databaseName = npr->databaseName;
959
960         if (!databaseName)
961             databaseName = zh->admin_databaseName;
962         printf ("--------------%d--------------------\n", i);
963         if (npr->which == Z_NamePlusRecord_intermediateFragment)
964         {
965             Z_FragmentSyntax *fragment = npr->u.intermediateFragment;
966             if (fragment->which == Z_FragmentSyntax_notExternallyTagged)
967             {
968                 Odr_oct *oct = fragment->u.notExternallyTagged;
969                 printf ("%.*s", (oct->len > 100 ? 100 : oct->len) ,
970                         oct->buf);
971                 
972                 sysno = 0;
973                 extract_rec_in_mem (zh, "grs.sgml",
974                                     oct->buf, oct->len,
975                                     databaseName,
976                                     0 /* delete_flag */,
977                                     0 /* test_mode */,
978                                     &sysno /* sysno */,
979                                     1 /* store_keys */,
980                                     1 /* store_data */,
981                                     0 /* match criteria */);
982             }
983         }
984     }
985 }
986
987 int zebra_admin_exchange_record (ZebraHandle zh,
988                                  const char *database,
989                                  const char *rec_buf,
990                                  size_t rec_len,
991                                  const char *recid_buf, size_t recid_len,
992                                  int action)
993 {
994     int sysno = 0;
995     char *rinfo = 0;
996     char recid_z[256];
997     ASSERTZH;
998     zh->errCode=0;
999
1000     if (!recid_buf || recid_len <= 0 || recid_len >= sizeof(recid_z))
1001         return -1;
1002     memcpy (recid_z, recid_buf, recid_len);
1003     recid_z[recid_len] = 0;
1004
1005     rinfo = dict_lookup (zh->reg->matchDict, recid_z);
1006     if (rinfo)
1007     {
1008         if (action == 1)  /* fail if insert */
1009             return -1;
1010         memcpy (&sysno, rinfo+1, sizeof(sysno));
1011     }
1012     else
1013     {
1014         if (action == 2 || action == 3) /* fail if delete or update */
1015             return -1;
1016     }
1017     extract_rec_in_mem (zh, "grs.sgml", rec_buf, rec_len, database,
1018                         action == 3 ? 1 : 0 /* delete flag */,
1019                         0, &sysno, 1, 1, 0);
1020     if (action == 1)
1021     {
1022         dict_insert (zh->reg->matchDict, recid_z, sizeof(sysno), &sysno);
1023     }
1024     else if (action == 3)
1025     {
1026         dict_delete (zh->reg->matchDict, recid_z);
1027     }
1028     return 0;
1029 }
1030
1031 void zebra_admin_create (ZebraHandle zh, const char *database)
1032 {
1033     ZebraService zs;
1034     ASSERTZH;
1035     zh->errCode=0;
1036
1037     if (zebra_select_database (zh, database))
1038         return;
1039     zebra_begin_trans (zh, 1);
1040
1041     zs = zh->service;
1042     /* announce database */
1043     if (zebraExplain_newDatabase (zh->reg->zei, database, 0 
1044                                   /* explainDatabase */))
1045     {
1046         zh->errCode = 224;
1047         zh->errString = "database already exist";
1048     }
1049     zebra_end_trans (zh);
1050 }
1051
1052 int zebra_string_norm (ZebraHandle zh, unsigned reg_id,
1053                        const char *input_str, int input_len,
1054                        char *output_str, int output_len)
1055 {
1056     WRBUF wrbuf;
1057     ASSERTZH;
1058     zh->errCode=0;
1059     if (!zh->reg->zebra_maps)
1060         return -1;
1061     wrbuf = zebra_replace(zh->reg->zebra_maps, reg_id, "",
1062                           input_str, input_len);
1063     if (!wrbuf)
1064         return -2;
1065     if (wrbuf_len(wrbuf) >= output_len)
1066         return -3;
1067     if (wrbuf_len(wrbuf))
1068         memcpy (output_str, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
1069     output_str[wrbuf_len(wrbuf)] = '\0';
1070     return wrbuf_len(wrbuf);
1071 }
1072
1073
1074 void zebra_set_state (ZebraHandle zh, int val, int seqno)
1075 {
1076     char state_fname[256];
1077     char *fname;
1078     long p = getpid();
1079     FILE *f;
1080     ASSERTZH;
1081     zh->errCode=0;
1082
1083     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1084     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1085     f = fopen (fname, "w");
1086
1087     yaz_log (LOG_DEBUG, "%c %d %ld", val, seqno, p);
1088     fprintf (f, "%c %d %ld\n", val, seqno, p);
1089     fclose (f);
1090     xfree (fname);
1091 }
1092
1093 void zebra_get_state (ZebraHandle zh, char *val, int *seqno)
1094 {
1095     char state_fname[256];
1096     char *fname;
1097     FILE *f;
1098
1099     ASSERTZH;
1100     zh->errCode=0;
1101     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1102     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1103     f = fopen (fname, "r");
1104     *val = 'o';
1105     *seqno = 0;
1106
1107     if (f)
1108     {
1109         fscanf (f, "%c %d", val, seqno);
1110         fclose (f);
1111     }
1112     xfree (fname);
1113 }
1114
1115 int zebra_begin_read (ZebraHandle zh)
1116 {
1117     return zebra_begin_trans(zh, 0);
1118 }
1119
1120 void zebra_end_read (ZebraHandle zh)
1121 {
1122     zebra_end_trans(zh);
1123 }
1124
1125 int zebra_begin_trans (ZebraHandle zh, int rw)
1126 {
1127     ASSERTZHRES;
1128     assert (zh->res);
1129     if (rw)
1130     {
1131         int pass;
1132         int seqno = 0;
1133         char val = '?';
1134         const char *rval = 0;
1135         
1136         (zh->trans_no++);
1137         if (zh->trans_w_no)
1138             return 0;
1139         if (zh->trans_no != 1)
1140         {
1141             zh->errCode = 2;
1142             zh->errString = "write trans not allowed within read trans";
1143             return -1;
1144         }
1145         zh->trans_w_no = zh->trans_no;
1146
1147         zh->errCode=0;
1148         
1149         yaz_log (LOG_LOG, "zebra_begin_trans");
1150         
1151         zh->records_inserted = 0;
1152         zh->records_updated = 0;
1153         zh->records_deleted = 0;
1154         zh->records_processed = 0;
1155         
1156 #if HAVE_SYS_TIMES_H
1157         times (&zh->tms1);
1158 #endif
1159         /* lock */
1160         if (zh->shadow_enable)
1161             rval = res_get (zh->res, "shadow");
1162         
1163         for (pass = 0; pass < 2; pass++)
1164         {
1165             if (rval)
1166             {
1167                 zebra_lock_r (zh->lock_normal);
1168                 zebra_lock_w (zh->lock_shadow);
1169             }
1170             else
1171             {
1172                 zebra_lock_w (zh->lock_normal);
1173                 zebra_lock_w (zh->lock_shadow);
1174             }
1175             
1176             zebra_get_state (zh, &val, &seqno);
1177             if (val == 'c')
1178             {
1179                 yaz_log (LOG_LOG, "previous transaction didn't finish commit");
1180                 zebra_unlock (zh->lock_shadow);
1181                 zebra_unlock (zh->lock_normal);
1182                 zebra_commit (zh);
1183                 continue;
1184             }
1185             else if (val == 'd')
1186             {
1187                 if (rval)
1188                 {
1189                     BFiles bfs = bfs_create (res_get (zh->res, "shadow"),
1190                                              zh->path_reg);
1191                     yaz_log (LOG_LOG, "previous transaction didn't reach commit");
1192                     bf_commitClean (bfs, rval);
1193                     bfs_destroy (bfs);
1194             }
1195                 else
1196                 {
1197                     yaz_log (LOG_WARN, "your previous transaction didn't finish");
1198                 }
1199             }
1200             break;
1201         }
1202         if (pass == 2)
1203         {
1204             yaz_log (LOG_FATAL, "zebra_begin_trans couldn't finish commit");
1205             abort();
1206             return -1;
1207         }
1208         zebra_set_state (zh, 'd', seqno);
1209         
1210         zh->reg = zebra_register_open (zh->service, zh->reg_name,
1211                                        1, rval ? 1 : 0, zh->res,
1212                                        zh->path_reg);
1213         
1214         zh->reg->seqno = seqno;
1215     }
1216     else
1217     {
1218         int dirty = 0;
1219         char val;
1220         int seqno;
1221         
1222         (zh->trans_no)++;
1223         
1224         if (zh->trans_no != 1)
1225         {
1226             zebra_flush_reg (zh);
1227             return 0;
1228         }
1229         zh->errCode=0;
1230 #if HAVE_SYS_TIMES_H
1231         times (&zh->tms1);
1232 #endif
1233         if (!zh->res)
1234         {
1235             (zh->trans_no)--;
1236             zh->errCode = 109;
1237             return -1;
1238         }
1239         if (!zh->lock_normal || !zh->lock_shadow)
1240         {
1241             (zh->trans_no)--;
1242             zh->errCode = 2;
1243             return -1;
1244         }
1245         zebra_get_state (zh, &val, &seqno);
1246         if (val == 'd')
1247             val = 'o';
1248         
1249         if (!zh->reg)
1250             dirty = 1;
1251         else if (seqno != zh->reg->seqno)
1252         {
1253             yaz_log (LOG_LOG, "reopen seqno cur/old %d/%d",
1254                      seqno, zh->reg->seqno);
1255             dirty = 1;
1256         }
1257         else if (zh->reg->last_val != val)
1258         {
1259             yaz_log (LOG_LOG, "reopen last cur/old %d/%d",
1260                      val, zh->reg->last_val);
1261             dirty = 1;
1262         }
1263         if (!dirty)
1264             return 0;
1265         
1266         if (val == 'c')
1267             zebra_lock_r (zh->lock_shadow);
1268         else
1269             zebra_lock_r (zh->lock_normal);
1270         
1271         if (zh->reg)
1272             zebra_register_close (zh->service, zh->reg);
1273         zh->reg = zebra_register_open (zh->service, zh->reg_name,
1274                                        0, val == 'c' ? 1 : 0,
1275                                        zh->res, zh->path_reg);
1276         if (!zh->reg)
1277         {
1278             zh->errCode = 109;
1279             return -1;
1280         }
1281         zh->reg->last_val = val;
1282         zh->reg->seqno = seqno;
1283     }
1284     return 0;
1285 }
1286
1287 void zebra_end_trans (ZebraHandle zh) {
1288   ZebraTransactionStatus dummy;
1289   zebra_end_transaction(zh, &dummy);
1290 }
1291
1292 void zebra_end_transaction (ZebraHandle zh, ZebraTransactionStatus *status)
1293 {
1294     char val;
1295     int seqno;
1296     const char *rval;
1297
1298     ASSERTZH;
1299
1300     status->processed = 0;
1301     status->inserted  = 0;
1302     status->updated   = 0;
1303     status->deleted   = 0;
1304     status->utime     = 0;
1305     status->stime     = 0;
1306
1307     if (zh->trans_no != zh->trans_w_no)
1308     {
1309         zh->trans_no--;
1310         if (zh->trans_no != 0)
1311             return;
1312
1313         /* release read lock */
1314
1315         zebra_unlock (zh->lock_normal);
1316         zebra_unlock (zh->lock_shadow);
1317     }
1318     else
1319     {   /* release write lock */
1320         zh->trans_no--;
1321         zh->trans_w_no = 0;
1322         
1323         yaz_log (LOG_LOG, "zebra_end_trans");
1324         rval = res_get (zh->res, "shadow");
1325         
1326         zebraExplain_runNumberIncrement (zh->reg->zei, 1);
1327         
1328         zebra_flush_reg (zh);
1329         
1330         zebra_register_close (zh->service, zh->reg);
1331         zh->reg = 0;
1332         
1333         yaz_log (LOG_LOG, "Records: %7d i/u/d %d/%d/%d", 
1334                  zh->records_processed, zh->records_inserted,
1335                  zh->records_updated, zh->records_deleted);
1336         
1337         status->processed = zh->records_processed;
1338         status->inserted = zh->records_inserted;
1339         status->updated = zh->records_updated;
1340         status->deleted = zh->records_deleted;
1341         
1342         zebra_get_state (zh, &val, &seqno);
1343         if (val != 'd')
1344         {
1345             BFiles bfs = bfs_create (rval, zh->path_reg);
1346             yaz_log (LOG_LOG, "deleting shadow stuff val=%c", val);
1347             bf_commitClean (bfs, rval);
1348             bfs_destroy (bfs);
1349         }
1350         if (!rval)
1351             seqno++;
1352         zebra_set_state (zh, 'o', seqno);
1353         
1354         zebra_unlock (zh->lock_shadow);
1355         zebra_unlock (zh->lock_normal);
1356         
1357     }
1358 #if HAVE_SYS_TIMES_H
1359     times (&zh->tms2);
1360     logf (LOG_LOG, "user/system: %ld/%ld",
1361           (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1362           (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1363     
1364     status->utime = (long) (zh->tms2.tms_utime - zh->tms1.tms_utime);
1365     status->stime = (long) (zh->tms2.tms_stime - zh->tms1.tms_stime);
1366 #endif
1367 }
1368
1369 void zebra_repository_update (ZebraHandle zh)
1370 {
1371     ASSERTZH;
1372     zh->errCode=0;
1373     logf (LOG_LOG, "updating %s", zh->rGroup.path);
1374     repositoryUpdate (zh);    
1375 }
1376
1377 void zebra_repository_delete (ZebraHandle zh)
1378 {
1379     ASSERTZH;
1380     zh->errCode=0;
1381     logf (LOG_LOG, "deleting %s", zh->rGroup.path);
1382     repositoryDelete (zh);
1383 }
1384
1385 void zebra_repository_show (ZebraHandle zh)
1386 {
1387     ASSERTZH;
1388     zh->errCode=0;
1389     repositoryShow (zh);
1390 }
1391
1392 int zebra_commit (ZebraHandle zh)
1393 {
1394     int seqno;
1395     char val;
1396     const char *rval;
1397     BFiles bfs;
1398     ASSERTZH;
1399     zh->errCode=0;
1400
1401     if (!zh->res)
1402     {
1403         zh->errCode = 109;
1404         return -1;
1405     }
1406     rval = res_get (zh->res, "shadow");    
1407     if (!rval)
1408     {
1409         logf (LOG_WARN, "Cannot perform commit");
1410         logf (LOG_WARN, "No shadow area defined");
1411         return 0;
1412     }
1413
1414     zebra_lock_w (zh->lock_normal);
1415     zebra_lock_r (zh->lock_shadow);
1416
1417     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1418
1419     zebra_get_state (zh, &val, &seqno);
1420
1421     if (rval && *rval)
1422         bf_cache (bfs, rval);
1423     if (bf_commitExists (bfs))
1424     {
1425         zebra_set_state (zh, 'c', seqno);
1426
1427         logf (LOG_LOG, "commit start");
1428         bf_commitExec (bfs);
1429 #ifndef WIN32
1430         sync ();
1431 #endif
1432         logf (LOG_LOG, "commit clean");
1433         bf_commitClean (bfs, rval);
1434         seqno++;
1435         zebra_set_state (zh, 'o', seqno);
1436     }
1437     else
1438     {
1439         logf (LOG_LOG, "nothing to commit");
1440     }
1441     bfs_destroy (bfs);
1442
1443     zebra_unlock (zh->lock_shadow);
1444     zebra_unlock (zh->lock_normal);
1445     return 0;
1446 }
1447
1448 int zebra_init (ZebraHandle zh)
1449 {
1450     const char *rval;
1451     BFiles bfs = 0;
1452     ASSERTZH;
1453     zh->errCode=0;
1454
1455     if (!zh->res)
1456     {
1457         zh->errCode = 109;
1458         return -1;
1459     }
1460     rval = res_get (zh->res, "shadow");
1461
1462     bfs = bfs_create (res_get (zh->service->global_res, "register"),
1463                       zh->path_reg);
1464     if (rval && *rval)
1465         bf_cache (bfs, rval);
1466     
1467     bf_reset (bfs);
1468     bfs_destroy (bfs);
1469     zebra_set_state (zh, 'o', 0);
1470     return 0;
1471 }
1472
1473 int zebra_compact (ZebraHandle zh)
1474 {
1475     BFiles bfs;
1476     ASSERTZH;
1477     zh->errCode=0;
1478     if (!zh->res)
1479     {
1480         zh->errCode = 109;
1481         return -1;
1482     }
1483     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1484     inv_compact (bfs);
1485     bfs_destroy (bfs);
1486     return 0;
1487 }
1488
1489 int zebra_record_insert (ZebraHandle zh, const char *buf, int len)
1490 {
1491     int sysno = 0;
1492     int olderr;
1493     ASSERTZH;
1494     zh->errCode=0;
1495     zebra_begin_trans (zh, 1);
1496     if (zh->errCode)
1497       return 0; /* bad sysno */
1498     extract_rec_in_mem (zh, "grs.sgml",
1499                         buf, len,
1500                         "Default",  /* database */
1501                         0 /* delete_flag */,
1502                         0 /* test_mode */,
1503                         &sysno /* sysno */,
1504                         1 /* store_keys */,
1505                         1 /* store_data */,
1506                         0 /* match criteria */);
1507     olderr=zh->errCode;
1508     zebra_end_trans (zh);
1509     if (olderr)
1510       zh->errCode=olderr; 
1511     return sysno;
1512 }
1513
1514 void zebra_set_group (ZebraHandle zh, struct recordGroup *rg)
1515 {
1516     ASSERTZH;
1517     zh->errCode=0;
1518     memcpy (&zh->rGroup, rg, sizeof(*rg));
1519 }
1520
1521 void zebra_result (ZebraHandle zh, int *code, char **addinfo)
1522 {
1523     ASSERTZH;
1524     *code = zh->errCode;
1525     *addinfo = zh->errString;
1526 }
1527
1528 void zebra_shadow_enable (ZebraHandle zh, int value)
1529 {
1530     ASSERTZH;
1531     zh->errCode=0;
1532     zh->shadow_enable = value;
1533 }
1534
1535 int zebra_record_encoding (ZebraHandle zh, const char *encoding)
1536 {
1537     ASSERTZH;
1538     zh->errCode=0;
1539     xfree (zh->record_encoding);
1540
1541     /*
1542      * Fixme!
1543      */
1544
1545     if (zh->iconv_to_utf8 != 0)
1546         yaz_iconv_close(zh->iconv_to_utf8);
1547     if (zh->iconv_from_utf8 != 0)
1548         yaz_iconv_close(zh->iconv_from_utf8);
1549     
1550     zh->record_encoding = xstrdup (encoding);
1551     
1552     logf(LOG_DEBUG, "Reset record encoding: %s", encoding);
1553     
1554     zh->iconv_to_utf8 =
1555         yaz_iconv_open ("UTF-8", encoding);
1556     if (zh->iconv_to_utf8 == 0)
1557         yaz_log (LOG_WARN, "iconv: %s to UTF-8 unsupported", encoding);
1558     zh->iconv_from_utf8 =
1559         yaz_iconv_open (encoding, "UTF-8");
1560     if (zh->iconv_to_utf8 == 0)
1561         yaz_log (LOG_WARN, "iconv: UTF-8 to %s unsupported", encoding);
1562
1563     return 0;
1564 }
1565
1566 void zebra_set_resource(ZebraHandle zh, const char *name, const char *value)
1567 {
1568     ASSERTZH;
1569     zh->errCode=0;
1570     res_put(zh->res, name, value);
1571 }
1572
1573 const char *zebra_get_resource(ZebraHandle zh,
1574                                 const char *name, const char *defaultvalue)
1575 {
1576     ASSERTZH;
1577     zh->errCode=0;
1578     return res_get_def( zh->res, name, (char *)defaultvalue);
1579 }
1580
1581 /* moved from zebra_api_ext.c by pop */
1582
1583 int zebra_trans_no (ZebraHandle zh) {
1584   return (zh->trans_no);
1585 }
1586
1587
1588
1589 int zebra_get_shadow_enable (ZebraHandle zh) {
1590   return (zh->shadow_enable);
1591 }
1592
1593 void zebra_set_shadow_enable (ZebraHandle zh, int value) {
1594   zh->shadow_enable = value;
1595 }
1596
1597 void init_recordGroup (struct recordGroup *rg) {
1598     rg->groupName = NULL;
1599     rg->databaseName = NULL;
1600     rg->path = NULL;
1601     rg->recordId = NULL;
1602     rg->recordType = NULL;
1603     rg->flagStoreData = -1;
1604     rg->flagStoreKeys = -1; 
1605     rg->flagRw = 1;
1606     rg->databaseNamePath = 0;
1607     rg->explainDatabase = 0; 
1608     rg->fileVerboseLimit = 100000; 
1609     rg->followLinks = -1;
1610
1611
1612
1613 /* This is from extract.c... it seems useful, when extract_rec_in mem is 
1614    called... and in general... Should be moved to somewhere else */
1615 void res_get_recordGroup (ZebraHandle zh,
1616                           struct recordGroup *rGroup,
1617                           const char *ext) {
1618   char gprefix[128];
1619   char ext_res[128]; 
1620     
1621   if (!rGroup->groupName || !*rGroup->groupName)
1622     *gprefix = '\0';
1623   else 
1624     sprintf (gprefix, "%s.", rGroup->groupName);
1625   
1626   /* determine file type - depending on extension */
1627   if (!rGroup->recordType) {
1628     sprintf (ext_res, "%srecordType.%s", gprefix, ext);
1629     if (!(rGroup->recordType = res_get (zh->res, ext_res))) {
1630       sprintf (ext_res, "%srecordType", gprefix);
1631       rGroup->recordType = res_get (zh->res, ext_res);
1632     }
1633   }
1634   /* determine match criteria */
1635   if (!rGroup->recordId) { 
1636     sprintf (ext_res, "%srecordId.%s", gprefix, ext);
1637     if (!(rGroup->recordId = res_get (zh->res, ext_res))) {
1638       sprintf (ext_res, "%srecordId", gprefix);
1639       rGroup->recordId = res_get (zh->res, ext_res);
1640     }
1641   } 
1642   
1643   /* determine database name */
1644   if (!rGroup->databaseName) {
1645     sprintf (ext_res, "%sdatabase.%s", gprefix, ext);
1646     if (!(rGroup->databaseName = res_get (zh->res, ext_res))) { 
1647       sprintf (ext_res, "%sdatabase", gprefix);
1648       rGroup->databaseName = res_get (zh->res, ext_res);
1649     }
1650   }
1651   if (!rGroup->databaseName)
1652     rGroup->databaseName = "Default";
1653
1654   /* determine if explain database */
1655   sprintf (ext_res, "%sexplainDatabase", gprefix);
1656   rGroup->explainDatabase =
1657     atoi (res_get_def (zh->res, ext_res, "0"));
1658
1659   /* storeData */
1660   if (rGroup->flagStoreData == -1) {
1661     const char *sval;
1662     sprintf (ext_res, "%sstoreData.%s", gprefix, ext);
1663     if (!(sval = res_get (zh->res, ext_res))) {
1664       sprintf (ext_res, "%sstoreData", gprefix);
1665       sval = res_get (zh->res, ext_res);
1666     }
1667     if (sval)
1668       rGroup->flagStoreData = atoi (sval);
1669   }
1670   if (rGroup->flagStoreData == -1)  rGroup->flagStoreData = 0;
1671
1672   /* storeKeys */
1673   if (rGroup->flagStoreKeys == -1)  {
1674     const char *sval;
1675     
1676     sprintf (ext_res, "%sstoreKeys.%s", gprefix, ext);
1677     sval = res_get (zh->res, ext_res);
1678     if (!sval) {
1679       sprintf (ext_res, "%sstoreKeys", gprefix);
1680       sval = res_get (zh->res, ext_res);
1681     }
1682     if (!sval)  sval = res_get (zh->res, "storeKeys");
1683     if (sval) rGroup->flagStoreKeys = atoi (sval);
1684   }
1685   if (rGroup->flagStoreKeys == -1) rGroup->flagStoreKeys = 0;
1686   
1687
1688
1689
1690 /* almost the same as zebra_records_retrieve ... but how did it work? 
1691    I mean for multiple records ??? CHECK ??? */
1692 void api_records_retrieve (ZebraHandle zh, ODR stream,
1693                            const char *setname, Z_RecordComposition *comp,
1694                            oid_value input_format, int num_recs,
1695                            ZebraRetrievalRecord *recs)
1696 {
1697     ZebraPosSet poset;
1698     int i, *pos_array;
1699
1700     if (!zh->res)
1701     {
1702         zh->errCode = 30;
1703         zh->errString = odr_strdup (stream, setname);
1704         return;
1705     }
1706     
1707     zh->errCode = 0; 
1708
1709     if (zebra_begin_read (zh))
1710         return;
1711
1712     pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
1713     for (i = 0; i<num_recs; i++)
1714         pos_array[i] = recs[i].position;
1715     poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
1716     if (!poset)
1717     {
1718         logf (LOG_DEBUG, "zebraPosSetCreate error");
1719         zh->errCode = 30;
1720         zh->errString = nmem_strdup (stream->mem, setname);
1721     }
1722     else
1723     {
1724         for (i = 0; i<num_recs; i++)
1725         {
1726             if (poset[i].term)
1727             {
1728                 recs[i].errCode = 0;
1729                 recs[i].format = VAL_SUTRS;
1730                 recs[i].len = strlen(poset[i].term);
1731                 recs[i].buf = poset[i].term;
1732                 recs[i].base = poset[i].db;
1733                 recs[i].sysno = 0;
1734             
1735             }
1736             else if (poset[i].sysno)
1737             {
1738               /* changed here ??? CHECK ??? */
1739               char *b;
1740                 recs[i].errCode =
1741                     zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
1742                                         stream, input_format, comp,
1743                                         &recs[i].format, 
1744                                         &b,
1745                                         &recs[i].len,
1746                                         &recs[i].base);
1747                 recs[i].buf = (char *) odr_malloc(stream,recs[i].len);
1748                 memcpy(recs[i].buf, b, recs[i].len);
1749                 recs[i].errString = 0; /* Hmmm !!! we should get this */ 
1750                 recs[i].sysno = poset[i].sysno;
1751                 recs[i].score = poset[i].score;
1752             }
1753             else
1754             {
1755                 char num_str[20];
1756
1757                 sprintf (num_str, "%d", pos_array[i]);  
1758                 zh->errCode = 13;
1759                 zh->errString = odr_strdup (stream, num_str);
1760                 break;
1761             }
1762
1763         }
1764         zebraPosSetDestroy (zh, poset, num_recs);
1765     }
1766     zebra_end_read (zh);
1767     xfree (pos_array);
1768 }
1769
1770
1771 /* ---------------------------------------------------------------------------
1772   Record insert(=update), delete 
1773
1774   If sysno is provided, then it's used to identify the reocord.
1775   If not, and match_criteria is provided, then sysno is guessed
1776   If not, and a record is provided, then sysno is got from there
1777 */
1778
1779 int zebra_update_record (ZebraHandle zh, 
1780                          struct recordGroup *rGroup,
1781                          const char *recordType,
1782                          int sysno, const char *match, const char *fname,
1783                          const char *buf, int buf_size)
1784
1785 {
1786     int res;
1787
1788     if (buf_size < 1) buf_size = strlen(buf);
1789
1790     zebra_begin_trans(zh, 1);
1791     res=bufferExtractRecord (zh, buf, buf_size, rGroup, 
1792                              0, // delete_flag 
1793                              0, // test_mode,
1794                              recordType,
1795                              &sysno,   
1796                              match, fname);     
1797     zebra_end_trans(zh); 
1798     return sysno; 
1799 }
1800
1801 int zebra_delete_record (ZebraHandle zh, 
1802                          struct recordGroup *rGroup, 
1803                          const char *recordType,
1804                          int sysno, const char *match, const char *fname,
1805                          const char *buf, int buf_size)
1806 {
1807     int res;
1808
1809     if (buf_size < 1) buf_size = strlen(buf);
1810
1811     zebra_begin_trans(zh, 1);
1812     res=bufferExtractRecord (zh, buf, buf_size, rGroup, 
1813                              1, // delete_flag
1814                              0, // test_mode, 
1815                              recordType,
1816                              &sysno,
1817                              match,fname);    
1818     zebra_end_trans(zh);
1819     return sysno;   
1820 }
1821
1822 /* ---------------------------------------------------------------------------
1823   Searching 
1824
1825   zebra_search_RPN is the same as zebra_search_rpn, except that read locking
1826   is not mandatory. (it's repeatable now, also in zebraapi.c)
1827 */
1828
1829 void zebra_search_RPN (ZebraHandle zh, ODR decode, ODR stream,
1830                        Z_RPNQuery *query, const char *setname, int *hits)
1831 {
1832     zh->hits = 0;
1833     *hits = 0;
1834
1835     if (zebra_begin_read (zh))
1836         return;
1837     resultSetAddRPN (zh, decode, stream, query, 
1838                      zh->num_basenames, zh->basenames, setname);
1839
1840     zebra_end_read (zh);
1841
1842     *hits = zh->hits;
1843 }
1844
1845 int zebra_search_PQF (ZebraHandle zh, 
1846                       ODR odr_input, ODR odr_output, 
1847                       const char *pqf_query,
1848                       const char *setname)
1849     
1850 {
1851     int hits;
1852     Z_RPNQuery *query;
1853     query = p_query_rpn (odr_input, PROTO_Z3950, pqf_query);
1854     
1855     if (!query) {
1856         logf (LOG_WARN, "bad query %s\n", pqf_query);
1857         odr_reset (odr_input);
1858         return(0);
1859     }
1860     zebra_search_RPN (zh, odr_input, odr_output, query, setname, &hits);
1861     
1862     odr_reset (odr_input);
1863     odr_reset (odr_output);
1864     
1865     return(hits);
1866 }
1867
1868 /* ---------------------------------------------------------------------------
1869   Sort - a simplified interface, with optional read locks.
1870 */
1871 int sort (ZebraHandle zh, 
1872           ODR stream,
1873           const char *sort_spec,
1874           const char *output_setname,
1875           const char **input_setnames
1876     ) 
1877 {
1878     int num_input_setnames = 0;
1879     int sort_status = 0;
1880     Z_SortKeySpecList *sort_sequence = yaz_sort_spec (stream, sort_spec);
1881     if (!sort_sequence) {
1882         logf(LOG_WARN,"invalid sort specs '%s'", sort_spec);
1883         zh->errCode = 207;
1884     return (-1);
1885     }
1886     
1887     /* we can do this, since the perl typemap code for char** will 
1888        put a NULL at the end of list */
1889     while (input_setnames[num_input_setnames]) num_input_setnames++;
1890
1891     if (zebra_begin_read (zh))
1892         return -1;
1893     
1894     resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
1895                    output_setname, sort_sequence, &sort_status);
1896     
1897     zebra_end_read(zh);
1898     return (sort_status);
1899 }