Added zebra_scan_PQF.
[idzebra-moved-to-github.git] / index / zebraapi.c
1 /* $Id: zebraapi.c,v 1.157 2005-04-13 08:52:27 adam Exp $
2    Copyright (C) 1995-2005
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 #include <assert.h>
24 #include <stdio.h>
25 #include <limits.h>
26 #ifdef WIN32
27 #include <io.h>
28 #include <process.h>
29 #include <direct.h>
30 #else
31 #include <unistd.h>
32 #endif
33
34 #include <yaz/diagbib1.h>
35 #include <yaz/pquery.h>
36 #include <yaz/sortspec.h>
37 #include "index.h"
38 #include <charmap.h>
39 #include <idzebra/api.h>
40
41 /* simple asserts to validate the most essential input args */
42 #define ASSERTZH assert(zh && zh->service)
43 #define ASSERTZHRES assert(zh && zh->service && zh->res)
44 #define ASSERTZS assert(zs)
45
46 static int log_level = 0;
47 static int log_level_initialized = 0;
48
49 static Res zebra_open_res (ZebraHandle zh);
50 static void zebra_close_res (ZebraHandle zh);
51
52 static void zebra_chdir (ZebraService zs)
53 {
54     const char *dir ;
55     ASSERTZS;
56     yaz_log(log_level, "zebra_chdir");
57     dir = res_get (zs->global_res, "chdir");
58     if (!dir)
59         return;
60     yaz_log (YLOG_DEBUG, "chdir %s", dir);
61 #ifdef WIN32
62     _chdir(dir);
63 #else
64     chdir (dir);
65 #endif
66 }
67
68 static void zebra_flush_reg (ZebraHandle zh)
69 {
70     ASSERTZH;
71     yaz_log(log_level, "zebra_flush_reg");
72     zh->errCode = 0;
73     zebraExplain_flush (zh->reg->zei, zh);
74     
75     extract_flushWriteKeys (zh, 1 /* final */);
76     zebra_index_merge (zh );
77 }
78
79 static struct zebra_register *zebra_register_open (ZebraService zs, 
80                                                    const char *name,
81                                                    int rw, int useshadow,
82                                                    Res res,
83                                                    const char *reg_path);
84 static void zebra_register_close (ZebraService zs, struct zebra_register *reg);
85
86 ZebraHandle zebra_open (ZebraService zs)
87 {
88     ZebraHandle zh;
89     const char *default_encoding;
90     if (!log_level_initialized)
91     {
92         log_level = yaz_log_module_level("zebraapi");
93         log_level_initialized = 1;
94     }
95
96     yaz_log(log_level, "zebra_open");
97
98     if (!zs)
99         return 0;
100
101     zh = (ZebraHandle) xmalloc(sizeof(*zh));
102     yaz_log (YLOG_DEBUG, "zebra_open zs=%p returns %p", zs, zh);
103
104     zh->service = zs;
105     zh->reg = 0;          /* no register attached yet */
106     zh->sets = 0;
107     zh->destroyed = 0;
108     zh->errCode = 0;
109     zh->errString = 0;
110     zh->res = 0; 
111     zh->user_perm = 0;
112
113     zh->reg_name = xstrdup ("");
114     zh->path_reg = 0;
115     zh->num_basenames = 0;
116     zh->basenames = 0;
117
118     zh->trans_no = 0;
119     zh->trans_w_no = 0;
120
121     zh->lock_normal = 0;
122     zh->lock_shadow = 0;
123
124     zh->shadow_enable = 1;
125
126     default_encoding = res_get_def(zs->global_res, "encoding", "ISO-8859-1");
127
128     zh->iconv_to_utf8 =
129         yaz_iconv_open ("UTF-8", default_encoding);
130     if (zh->iconv_to_utf8 == 0)
131         yaz_log (YLOG_WARN, "iconv: %s to UTF-8 unsupported",
132            default_encoding);
133     zh->iconv_from_utf8 =
134         yaz_iconv_open (default_encoding, "UTF-8");
135     if (zh->iconv_to_utf8 == 0)
136         yaz_log (YLOG_WARN, "iconv: UTF-8 to %s unsupported",
137            default_encoding);
138
139     zh->record_encoding = 0;
140
141     zebra_mutex_cond_lock (&zs->session_lock);
142
143     zh->next = zs->sessions;
144     zs->sessions = zh;
145
146     zebra_mutex_cond_unlock (&zs->session_lock);
147
148     return zh;
149 }
150
151 ZebraService zebra_start (const char *configName)
152 {
153     return zebra_start_res(configName, 0, 0);
154 }
155
156 ZebraService zebra_start_res (const char *configName, Res def_res, Res over_res)
157 {
158     Res res;
159
160     if (!log_level_initialized)
161     {
162         log_level = yaz_log_module_level("zebraapi");
163         log_level_initialized = 1;
164     }
165
166     yaz_log(log_level, "zebra_start %s",configName);
167     assert(configName);
168
169     if ((res = res_open (configName, def_res, over_res)))
170     {
171         ZebraService zh = xmalloc(sizeof(*zh));
172
173         yaz_log (YLOG_DEBUG, "Read resources `%s'", configName);
174         
175         zh->global_res = res;
176         zh->configName = xstrdup(configName);
177         zh->sessions = 0;
178         
179         zebra_chdir (zh);
180         
181         zebra_mutex_cond_init (&zh->session_lock);
182         if (!res_get (zh->global_res, "passwd"))
183             zh->passwd_db = NULL;
184         else
185         {
186             zh->passwd_db = passwd_db_open ();
187             if (!zh->passwd_db)
188                 yaz_log (YLOG_WARN|YLOG_ERRNO, "passwd_db_open failed");
189             else
190                 passwd_db_file (zh->passwd_db,
191                                 res_get (zh->global_res, "passwd"));
192         }
193         zh->path_root = res_get (zh->global_res, "root");
194         zh->nmem = nmem_create();
195         zh->record_classes = recTypeClass_create (zh->global_res, zh->nmem);
196         return zh;
197     }
198     return 0;
199 }
200
201 void zebra_filter_info(ZebraService zs, void *cd,
202                         void (*cb)(void *cd, const char *name))
203 {
204     ASSERTZS;
205     assert(cb);
206     recTypeClass_info(zs->record_classes, cd, cb);
207 }
208
209 void zebra_pidfname(ZebraService zs, char *path)
210 {
211     ASSERTZS;
212     zebra_lock_prefix (zs->global_res, path);
213     strcat(path, "zebrasrv.pid");
214 }
215
216 Dict dict_open_res (BFiles bfs, const char *name, int cache, int rw,
217                     int compact_flag, Res res)
218 {
219     int page_size = 4096;
220     char resource_str[200];
221     const char *v;
222     sprintf (resource_str, "dict.%.100s.pagesize", name);
223     assert(bfs);
224     assert(name);
225
226     v = res_get(res, resource_str);
227     if (v)
228     {
229         page_size = atoi(v);
230         yaz_log(YLOG_LOG, "Using custom dictionary page size %d for %s",
231                 page_size, name);
232     }
233     return dict_open(bfs, name, cache, rw, compact_flag, page_size);
234 }
235
236
237 static
238 struct zebra_register *zebra_register_open (ZebraService zs, const char *name,
239                                             int rw, int useshadow, Res res,
240                                             const char *reg_path)
241 {
242     struct zebra_register *reg;
243     int record_compression = REC_COMPRESS_NONE;
244     const char *recordCompression = 0;
245     const char *profilePath;
246     char cwd[1024];
247
248     ASSERTZS;
249     
250     reg = xmalloc(sizeof(*reg));
251
252     assert (name);
253     reg->name = xstrdup (name);
254
255     reg->seqno = 0;
256     reg->last_val = 0;
257
258     assert (res);
259
260     yaz_log (YLOG_DEBUG, "zebra_register_open rw=%d useshadow=%d p=%p n=%s rp=%s",
261              rw, useshadow, reg, name, reg_path ? reg_path : "(none)");
262     
263     reg->dh = data1_createx (DATA1_FLAG_XML);
264     if (!reg->dh)
265         return 0;
266     reg->bfs = bfs_create (res_get (res, "register"), reg_path);
267     if (!reg->bfs)
268     {
269         data1_destroy(reg->dh);
270         return 0;
271     }
272     if (useshadow)
273         bf_cache (reg->bfs, res_get (res, "shadow"));
274
275     getcwd(cwd, sizeof(cwd)-1);
276     profilePath = res_get_def(res, "profilePath", DEFAULT_PROFILE_PATH);
277     yaz_log(YLOG_DEBUG, "profilePath=%s cwd=%s", profilePath, cwd);
278
279     data1_set_tabpath (reg->dh, profilePath);
280     data1_set_tabroot (reg->dh, reg_path);
281     reg->recTypes = recTypes_init (zs->record_classes, reg->dh);
282
283     reg->zebra_maps = zebra_maps_open (res, reg_path);
284     reg->rank_classes = NULL;
285
286     reg->key_buf = 0;
287
288     reg->keys.buf_max = 0;
289     reg->keys.buf = 0;
290     reg->keys.codec_handle = iscz1_start();
291
292     reg->sortKeys.buf = 0;
293     reg->sortKeys.buf_max = 0;
294
295     reg->records = 0;
296     reg->dict = 0;
297     reg->sortIdx = 0;
298     reg->isams = 0;
299     reg->matchDict = 0;
300     reg->isamc = 0;
301     reg->isamb = 0;
302     reg->zei = 0;
303     reg->matchDict = 0;
304     reg->key_file_no = 0;
305     reg->ptr_i = 0;
306     
307     zebraRankInstall (reg, rank1_class);
308     zebraRankInstall (reg, rankzv_class);
309
310     recordCompression = res_get_def (res, "recordCompression", "none");
311     if (!strcmp (recordCompression, "none"))
312         record_compression = REC_COMPRESS_NONE;
313     if (!strcmp (recordCompression, "bzip2"))
314         record_compression = REC_COMPRESS_BZIP2;
315
316     if (!(reg->records = rec_open (reg->bfs, rw, record_compression)))
317     {
318         yaz_log (YLOG_WARN, "rec_open failed");
319         return 0;
320     }
321     if (rw)
322     {
323         reg->matchDict = dict_open_res (reg->bfs, GMATCH_DICT, 20, 1, 0, res);
324     }
325     if (!(reg->dict = dict_open_res (reg->bfs, FNAME_DICT, 40, rw, 0, res)))
326     {
327         yaz_log (YLOG_WARN, "dict_open failed");
328         return 0;
329     }
330     if (!(reg->sortIdx = sortIdx_open (reg->bfs, rw)))
331     {
332         yaz_log (YLOG_WARN, "sortIdx_open failed");
333         return 0;
334     }
335     if (res_get_match (res, "isam", "s", ISAM_DEFAULT))
336     {
337         struct ISAMS_M_s isams_m;
338         if (!(reg->isams = isams_open (reg->bfs, FNAME_ISAMS, rw,
339                                       key_isams_m(res, &isams_m))))
340         {
341             yaz_log (YLOG_WARN, "isams_open failed");
342             return 0;
343         }
344     }
345     if (res_get_match (res, "isam", "c", ISAM_DEFAULT))
346     {
347         struct ISAMC_M_s isamc_m;
348         if (!(reg->isamc = isc_open (reg->bfs, FNAME_ISAMC,
349                                     rw, key_isamc_m(res, &isamc_m))))
350         {
351             yaz_log (YLOG_WARN, "isc_open failed");
352             return 0;
353         }
354     }
355     if (res_get_match (res, "isam", "b", ISAM_DEFAULT))
356     {
357         struct ISAMC_M_s isamc_m;
358         
359         if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
360                                        rw, key_isamc_m(res, &isamc_m), 0)))
361         {
362             yaz_log (YLOG_WARN, "isamb_open failed");
363             return 0;
364         }
365     }
366     if (res_get_match (res, "isam", "bc", ISAM_DEFAULT))
367     {
368         struct ISAMC_M_s isamc_m;
369         
370         if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
371                                        rw, key_isamc_m(res, &isamc_m), 1)))
372         {
373             yaz_log (YLOG_WARN, "isamb_open failed");
374             return 0;
375         }
376     }
377     if (res_get_match (res, "isam", "null", ISAM_DEFAULT))
378     {
379         struct ISAMC_M_s isamc_m;
380         
381         if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
382                                        rw, key_isamc_m(res, &isamc_m), -1)))
383         {
384             yaz_log (YLOG_WARN, "isamb_open failed");
385             return 0;
386         }
387     }
388     reg->zei = zebraExplain_open (reg->records, reg->dh,
389                                   res, rw, reg,
390                                   explain_extract);
391     if (!reg->zei)
392     {
393         yaz_log (YLOG_WARN, "Cannot obtain EXPLAIN information");
394         return 0;
395     }
396     reg->active = 2;
397     yaz_log (YLOG_DEBUG, "zebra_register_open ok p=%p", reg);
398     return reg;
399 }
400
401 int zebra_admin_shutdown (ZebraHandle zh)
402 {
403     ASSERTZH;
404     yaz_log(log_level, "zebra_admin_shutdown");
405     zh->errCode = 0;
406
407     zebra_mutex_cond_lock (&zh->service->session_lock);
408     zh->service->stop_flag = 1;
409     zebra_mutex_cond_unlock (&zh->service->session_lock);
410     return 0;
411 }
412
413 int zebra_admin_start (ZebraHandle zh)
414 {
415     ZebraService zs;
416     ASSERTZH;
417     yaz_log(log_level, "zebra_admin_start");
418     zh->errCode = 0;
419     zs = zh->service;
420     zebra_mutex_cond_lock (&zs->session_lock);
421     zebra_mutex_cond_unlock (&zs->session_lock);
422     return 0;
423 }
424
425 static void zebra_register_close (ZebraService zs, struct zebra_register *reg)
426 {
427     ASSERTZS;
428     assert(reg);
429     yaz_log(YLOG_DEBUG, "zebra_register_close p=%p", reg);
430     reg->stop_flag = 0;
431     zebra_chdir (zs);
432     if (reg->records)
433     {
434         zebraExplain_close (reg->zei);
435         dict_close (reg->dict);
436         if (reg->matchDict)
437             dict_close (reg->matchDict);
438         sortIdx_close (reg->sortIdx);
439         if (reg->isams)
440             isams_close (reg->isams);
441         if (reg->isamc)
442             isc_close (reg->isamc);
443         if (reg->isamb)
444             isamb_close (reg->isamb);
445         rec_close (&reg->records);
446     }
447
448     recTypes_destroy (reg->recTypes);
449     zebra_maps_close (reg->zebra_maps);
450     zebraRankDestroy (reg);
451     bfs_destroy (reg->bfs);
452     data1_destroy (reg->dh);
453
454     xfree(reg->sortKeys.buf);
455     xfree(reg->keys.buf);
456     if (reg->keys.codec_handle)
457         iscz1_stop(reg->keys.codec_handle);
458     xfree(reg->key_buf);
459     xfree(reg->name);
460     xfree(reg);
461 }
462
463 int zebra_stop(ZebraService zs)
464 {
465     if (!zs)
466         return 0;
467     yaz_log (log_level, "zebra_stop");
468
469     while (zs->sessions)
470     {
471         zebra_close (zs->sessions);
472     }
473         
474     zebra_mutex_cond_destroy (&zs->session_lock);
475
476     if (zs->passwd_db)
477         passwd_db_close (zs->passwd_db);
478
479     recTypeClass_destroy(zs->record_classes);
480     nmem_destroy(zs->nmem);
481     res_close (zs->global_res);
482     xfree(zs->configName);
483     xfree(zs);
484     return 0;
485 }
486
487 int zebra_close (ZebraHandle zh)
488 {
489     ZebraService zs;
490     struct zebra_session **sp;
491     int i;
492
493     yaz_log(log_level, "zebra_close");
494     if (!zh)
495         return 0;
496     ASSERTZH;
497     zh->errCode = 0;
498     
499     zs = zh->service;
500     yaz_log (YLOG_DEBUG, "zebra_close zh=%p", zh);
501     resultSetDestroy (zh, -1, 0, 0);
502
503     if (zh->reg)
504         zebra_register_close (zh->service, zh->reg);
505     zebra_close_res (zh);
506
507     xfree(zh->record_encoding);
508
509     for (i = 0; i < zh->num_basenames; i++)
510         xfree(zh->basenames[i]);
511     xfree(zh->basenames);
512
513     if (zh->iconv_to_utf8 != 0)
514         yaz_iconv_close (zh->iconv_to_utf8);
515     if (zh->iconv_from_utf8 != 0)
516         yaz_iconv_close (zh->iconv_from_utf8);
517
518     zebra_mutex_cond_lock (&zs->session_lock);
519     zebra_lock_destroy (zh->lock_normal);
520     zebra_lock_destroy (zh->lock_shadow);
521     sp = &zs->sessions;
522     while (1)
523     {
524         assert (*sp);
525         if (*sp == zh)
526         {
527             *sp = (*sp)->next;
528             break;
529         }
530         sp = &(*sp)->next;
531     }
532     zebra_mutex_cond_unlock (&zs->session_lock);
533     xfree(zh->reg_name);
534     xfree(zh->user_perm);
535     zh->service = 0; /* more likely to trigger an assert */
536     xfree(zh->path_reg);
537     xfree(zh);
538     return 0;
539 }
540
541 struct map_baseinfo {
542     ZebraHandle zh;
543     NMEM mem;
544     int num_bases;
545     char **basenames;
546     int new_num_bases;
547     char **new_basenames;
548     int new_num_max;
549 };
550
551 static Res zebra_open_res (ZebraHandle zh)
552 {
553     Res res = 0;
554     char fname[512];
555     ASSERTZH;
556     zh->errCode = 0;
557
558     if (zh->path_reg)
559     {
560         sprintf (fname, "%.200s/zebra.cfg", zh->path_reg);
561         res = res_open (fname, zh->service->global_res, 0);
562         if (!res)
563             res = zh->service->global_res;
564     }
565     else if (*zh->reg_name == 0)
566     {
567         res = zh->service->global_res;
568     }
569     else
570     {
571         yaz_log (YLOG_WARN, "no register root specified");
572         return 0;  /* no path for register - fail! */
573     }
574     return res;
575 }
576
577 static void zebra_close_res (ZebraHandle zh)
578 {
579     ASSERTZH;
580     zh->errCode = 0;
581     if (zh->res != zh->service->global_res)
582         res_close (zh->res);
583     zh->res = 0;
584 }
585
586 static int zebra_select_register (ZebraHandle zh, const char *new_reg)
587 {
588     ASSERTZH;
589     zh->errCode = 0;
590     if (zh->res && strcmp (zh->reg_name, new_reg) == 0)
591         return 0;
592     if (!zh->res)
593     {
594         assert (zh->reg == 0);
595         assert (*zh->reg_name == 0);
596     }
597     else
598     {
599         if (zh->reg)
600         {
601             resultSetInvalidate (zh);
602             zebra_register_close (zh->service, zh->reg);
603             zh->reg = 0;
604         }
605         zebra_close_res(zh);
606     }
607     xfree(zh->reg_name);
608     zh->reg_name = xstrdup (new_reg);
609
610     xfree(zh->path_reg);
611     zh->path_reg = 0;
612     if (zh->service->path_root)
613     {
614         zh->path_reg = xmalloc(strlen(zh->service->path_root) + 
615                                 strlen(zh->reg_name) + 3);
616         strcpy (zh->path_reg, zh->service->path_root);
617         if (*zh->reg_name)
618         {
619             strcat (zh->path_reg, "/");
620             strcat (zh->path_reg, zh->reg_name);
621         }
622     }
623     zh->res = zebra_open_res (zh);
624     
625     if (zh->lock_normal)
626         zebra_lock_destroy (zh->lock_normal);
627     zh->lock_normal = 0;
628
629     if (zh->lock_shadow)
630         zebra_lock_destroy (zh->lock_shadow);
631     zh->lock_shadow = 0;
632
633     if (zh->res)
634     {
635         char fname[512];
636         const char *lock_area  =res_get (zh->res, "lockDir");
637         
638         if (!lock_area && zh->path_reg)
639             res_set (zh->res, "lockDir", zh->path_reg);
640         sprintf (fname, "norm.%s.LCK", zh->reg_name);
641         zh->lock_normal =
642             zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
643         
644         sprintf (fname, "shadow.%s.LCK", zh->reg_name);
645         zh->lock_shadow =
646             zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
647
648     }
649     return 1;
650 }
651
652 void map_basenames_func (void *vp, const char *name, const char *value)
653 {
654     struct map_baseinfo *p = (struct map_baseinfo *) vp;
655     int i, no;
656     char fromdb[128], todb[8][128];
657
658     assert(value);
659     assert(name);
660     assert(vp);
661     
662     no =
663         sscanf (value, "%127s %127s %127s %127s %127s %127s %127s %127s %127s",
664                 fromdb, todb[0], todb[1], todb[2], todb[3], todb[4],
665                 todb[5], todb[6], todb[7]);
666     if (no < 2)
667         return ;
668     no--;
669     for (i = 0; i<p->num_bases; i++)
670         if (p->basenames[i] && !STRCASECMP (p->basenames[i], fromdb))
671         {
672             p->basenames[i] = 0;
673             for (i = 0; i < no; i++)
674             {
675                 if (p->new_num_bases == p->new_num_max)
676                     return;
677                 p->new_basenames[(p->new_num_bases)++] = 
678                     nmem_strdup (p->mem, todb[i]);
679             }
680             return;
681         }
682 }
683
684 int zebra_select_default_database(ZebraHandle zh)
685 {
686     if (!zh->res)
687     {
688         /* no database has been selected - so we select based on
689            resource setting (including group)
690         */
691         const char *group = res_get(zh->service->global_res, "group");
692         const char *v = res_get_prefix(zh->service->global_res,
693                                        "database", group, "Default");
694         zebra_select_database(zh, v);
695     }
696     return 0;
697 }
698
699 void map_basenames (ZebraHandle zh, ODR stream,
700                     int *num_bases, char ***basenames)
701 {
702     struct map_baseinfo info;
703     struct map_baseinfo *p = &info;
704     int i;
705     ASSERTZH;
706     yaz_log(log_level, "map_basenames ");
707     assert(stream);
708
709     zh->errCode = 0;
710
711     info.zh = zh;
712
713     info.num_bases = *num_bases;
714     info.basenames = *basenames;
715     info.new_num_max = 128;
716     info.new_num_bases = 0;
717     info.new_basenames = (char **)
718         odr_malloc (stream, sizeof(*info.new_basenames) * info.new_num_max);
719     info.mem = stream->mem;
720
721     res_trav (zh->service->global_res, "mapdb", &info, map_basenames_func);
722     
723     for (i = 0; i<p->num_bases; i++)
724         if (p->basenames[i] && p->new_num_bases < p->new_num_max)
725         {
726             p->new_basenames[(p->new_num_bases)++] = 
727                 nmem_strdup (p->mem, p->basenames[i]);
728         }
729     *num_bases = info.new_num_bases;
730     *basenames = info.new_basenames;
731     for (i = 0; i<*num_bases; i++)
732         yaz_log (YLOG_DEBUG, "base %s", (*basenames)[i]);
733 }
734
735 int zebra_select_database (ZebraHandle zh, const char *basename)
736 {
737     ASSERTZH;
738     yaz_log(log_level, "zebra_select_database %s",basename);
739     assert(basename);
740     zh->errCode = 0;
741     return zebra_select_databases (zh, 1, &basename);
742 }
743
744 int zebra_select_databases (ZebraHandle zh, int num_bases,
745                             const char **basenames)
746 {
747     int i;
748     const char *cp;
749     int len = 0;
750     char *new_reg = 0;
751     ASSERTZH;
752     assert(basenames);
753
754     yaz_log(log_level, "zebra_select_databases n=%d [0]=%s",
755                     num_bases,basenames[0]);
756     zh->errCode = 0;
757     
758     if (num_bases < 1)
759     {
760         zh->errCode = 23;
761         return -1;
762     }
763     for (i = 0; i < zh->num_basenames; i++)
764         xfree(zh->basenames[i]);
765     xfree(zh->basenames);
766     
767     zh->num_basenames = num_bases;
768     zh->basenames = xmalloc(zh->num_basenames * sizeof(*zh->basenames));
769     for (i = 0; i < zh->num_basenames; i++)
770         zh->basenames[i] = xstrdup (basenames[i]);
771
772     cp = strrchr(basenames[0], '/');
773     if (cp)
774     {
775         len = cp - basenames[0];
776         new_reg = xmalloc(len + 1);
777         memcpy (new_reg, basenames[0], len);
778         new_reg[len] = '\0';
779     }
780     else
781         new_reg = xstrdup ("");
782     for (i = 1; i<num_bases; i++)
783     {
784         const char *cp1;
785
786         cp1 = strrchr (basenames[i], '/');
787         if (cp)
788         {
789             if (!cp1)
790             {
791                 zh->errCode = 23;
792                 return -1;
793             }
794             if (len != cp1 - basenames[i] ||
795                 memcmp (basenames[i], new_reg, len))
796             {
797                 zh->errCode = 23;
798                 return -1;
799             }
800         }
801         else
802         {
803             if (cp1)
804             {
805                 zh->errCode = 23;
806                 return -1;
807             }
808         }
809     }
810     zebra_select_register (zh, new_reg);
811     xfree(new_reg);
812     if (!zh->res)
813     {
814         zh->errCode = 109;
815         return -1;
816     }
817     if (!zh->lock_normal || !zh->lock_shadow)
818     {
819         zh->errCode = 2;
820         return -1;
821     }
822     return 0;
823 }
824
825 int zebra_search_RPN (ZebraHandle zh, ODR o,
826                        Z_RPNQuery *query, const char *setname, zint *hits)
827 {
828     const char *max;
829     zint maxhits;
830     ASSERTZH;
831     assert(o);
832     assert(query);
833     assert(hits);
834     assert(setname);
835     yaz_log(log_level, "zebra_search_rpn");
836     zh->errCode = 0;
837     zh->hits = 0;
838     *hits = 0;
839
840     if (zebra_begin_read (zh))
841         return 1;
842
843     resultSetAddRPN (zh, odr_extract_mem(o), query, 
844                      zh->num_basenames, zh->basenames, setname);
845
846     zebra_end_read (zh);
847     max = res_get (zh->res, "maxhits");
848     if (max)
849         maxhits = atoi(max);
850     else {
851         int i = 0; 
852         maxhits = INT_MAX;  /* properly rounded, to make it look like a limit*/
853         while (maxhits>100) { maxhits/=10; i++;}
854         while (i--) maxhits *= 10;
855     }
856     if (zh->hits > maxhits) { /* too large for yaz to handle */
857         yaz_log(YLOG_DEBUG, "limiting hits to "ZINT_FORMAT, maxhits);
858         *hits = maxhits;  
859     }
860     else
861         *hits = zh->hits;
862     return 0;
863 }
864
865 int zebra_records_retrieve (ZebraHandle zh, ODR stream,
866                             const char *setname, Z_RecordComposition *comp,
867                             oid_value input_format, int num_recs,
868                             ZebraRetrievalRecord *recs)
869 {
870     ZebraMetaRecord *poset;
871     int i, ret = 0;
872     zint *pos_array;
873     ASSERTZH;
874     assert(stream);
875     assert(setname);
876     assert(recs);
877     assert(num_recs>0);
878
879     yaz_log(log_level, "zebra_records_retrieve n=%d",num_recs);
880     zh->errCode = 0;
881
882     if (!zh->res)
883     {
884         zh->errCode = 30;
885         zh->errString = odr_strdup(stream, setname);
886         return -1;
887     }
888     
889     zh->errCode = 0;
890
891     if (zebra_begin_read (zh))
892         return -1;
893
894     pos_array = (zint *) xmalloc(num_recs * sizeof(*pos_array));
895     for (i = 0; i<num_recs; i++)
896         pos_array[i] = recs[i].position;
897     poset = zebra_meta_records_create(zh, setname, num_recs, pos_array);
898     if (!poset)
899     {
900         yaz_log (YLOG_DEBUG, "zebraPosSetCreate error");
901         zh->errCode = 30;
902         zh->errString = nmem_strdup (stream->mem, setname);
903         ret = -1;
904     }
905     else
906     {
907         for (i = 0; i<num_recs; i++)
908         {
909             if (poset[i].term)
910             {
911                 recs[i].errCode = 0;
912                 recs[i].format = VAL_SUTRS;
913                 recs[i].len = strlen(poset[i].term);
914                 recs[i].buf = poset[i].term;
915                 recs[i].base = poset[i].db;
916             }
917             else if (poset[i].sysno)
918             {
919                 char *buf;
920                 int len;
921                 recs[i].errCode =
922                     zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
923                                         stream, input_format, comp,
924                                         &recs[i].format, &buf, &len,
925                                         &recs[i].base, &recs[i].errString);
926                 recs[i].len = len;
927                 if (len > 0)
928                 {
929                     recs[i].buf = (char*) odr_malloc(stream, len);
930                     memcpy(recs[i].buf, buf, len);
931                 }
932                 else
933                     recs[i].buf = buf;
934                 recs[i].score = poset[i].score;
935                 recs[i].sysno = poset[i].sysno;
936             }
937             else
938             {
939                 char num_str[20];
940
941                 sprintf (num_str, ZINT_FORMAT, pos_array[i]);   
942                 zh->errCode = 13;
943                 zh->errString = odr_strdup (stream, num_str);
944                 ret = -1;
945                 break;
946             }
947         }
948         zebra_meta_records_destroy(zh, poset, num_recs);
949     }
950     zebra_end_read (zh);
951     xfree(pos_array);
952     return ret;
953 }
954
955 int zebra_scan_PQF(ZebraHandle zh, ODR stream, const char *query,
956                    int *position, int *num_entries, ZebraScanEntry **entries,
957                    int *is_partial)
958 {
959     YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
960     Z_AttributesPlusTerm *zapt;
961     int *attributeSet;
962     
963     if (!(zapt = yaz_pqf_scan(pqf_parser, stream, &attributeSet, query)))
964     {
965         yaz_pqf_destroy (pqf_parser);
966         return -1;
967     }
968     yaz_pqf_destroy (pqf_parser);
969     return zebra_scan(zh, stream, zapt, VAL_BIB1,
970                       position, num_entries, entries, is_partial);
971 }
972
973 int zebra_scan (ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
974                 oid_value attributeset,
975                 int *position, int *num_entries, ZebraScanEntry **entries,
976                 int *is_partial)
977 {
978     ASSERTZH;
979     assert(stream);
980     assert(zapt);
981     assert(position);
982     assert(num_entries);
983     assert(is_partial);
984     assert(entries);
985     yaz_log(log_level, "zebra_scan");
986     zh->errCode = 0;
987     if (zebra_begin_read (zh))
988     {
989         *entries = 0;
990         *num_entries = 0;
991         return 1;
992     }
993     rpn_scan (zh, stream, zapt, attributeset,
994               zh->num_basenames, zh->basenames, position,
995               num_entries, entries, is_partial, 0, 0);
996     zebra_end_read (zh);
997     return 0;
998 }
999
1000 int zebra_sort (ZebraHandle zh, ODR stream,
1001                  int num_input_setnames, const char **input_setnames,
1002                  const char *output_setname, Z_SortKeySpecList *sort_sequence,
1003                  int *sort_status)
1004 {
1005     ASSERTZH;
1006     assert(stream);
1007     assert(num_input_setnames>0);
1008     assert(input_setnames);
1009     assert(sort_sequence);
1010     assert(sort_status);
1011     yaz_log(log_level, "zebra_sort");
1012     zh->errCode = 0;
1013     if (zebra_begin_read (zh))
1014         return 1;
1015     resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
1016                    output_setname, sort_sequence, sort_status);
1017     zebra_end_read(zh);
1018     return 0;
1019 }
1020
1021 int zebra_deleteResultSet(ZebraHandle zh, int function,
1022                           int num_setnames, char **setnames,
1023                           int *statuses)
1024 {
1025     int i, status;
1026     ASSERTZH;
1027     assert(statuses);
1028     yaz_log(log_level, "zebra_deleteResultSet n=%d",num_setnames);
1029     zh->errCode = 0;
1030     if (zebra_begin_read(zh))
1031         return Z_DeleteStatus_systemProblemAtTarget;
1032     switch (function)
1033     {
1034     case Z_DeleteResultSetRequest_list:
1035         assert(num_setnames>0);
1036         assert(setnames);
1037         resultSetDestroy (zh, num_setnames, setnames, statuses);
1038         break;
1039     case Z_DeleteResultSetRequest_all:
1040         resultSetDestroy (zh, -1, 0, statuses);
1041         break;
1042     }
1043     zebra_end_read (zh);
1044     status = Z_DeleteStatus_success;
1045     for (i = 0; i<num_setnames; i++)
1046         if (statuses[i] == Z_DeleteStatus_resultSetDidNotExist)
1047             status = statuses[i];
1048     return status;
1049 }
1050
1051 int zebra_errCode (ZebraHandle zh)
1052 {
1053     if (zh)
1054     {
1055         yaz_log(log_level, "zebra_errCode: %d",zh->errCode);
1056         return zh->errCode;
1057     }
1058     yaz_log(log_level, "zebra_errCode: o");
1059     return 0; 
1060 }
1061
1062 const char *zebra_errString (ZebraHandle zh)
1063 {
1064     const char *e="";
1065     if (zh)
1066         e= diagbib1_str (zh->errCode);
1067     yaz_log(log_level, "zebra_errString: %s",e);
1068     return e;
1069 }
1070
1071 char *zebra_errAdd (ZebraHandle zh)
1072 {
1073     char *a="";
1074     if (zh)
1075         a= zh->errString;
1076     yaz_log(log_level, "zebra_errAdd: %s",a);
1077     return a;
1078 }
1079
1080 void zebra_clearError(ZebraHandle zh)
1081 {
1082     if (zh)
1083     {
1084         zh->errCode = 0;
1085         zh->errString="";
1086     }
1087 }
1088
1089 int zebra_auth (ZebraHandle zh, const char *user, const char *pass)
1090 {
1091     const char *p;
1092     char u[40];
1093     ZebraService zs;
1094
1095     ASSERTZH;
1096     zh->errCode = 0;
1097     zs= zh->service;
1098     
1099     sprintf(u, "perm.%.30s", user ? user : "anonymous");
1100     p = res_get(zs->global_res, u);
1101     xfree(zh->user_perm);
1102     zh->user_perm = xstrdup(p ? p : "r");
1103
1104     /* users that don't require a password .. */
1105     if (zh->user_perm && strchr(zh->user_perm, 'a'))
1106         return 0;
1107     
1108     if (!zs->passwd_db || !passwd_db_auth (zs->passwd_db, user, pass))
1109         return 0;
1110     return 1;
1111 }
1112
1113 int zebra_admin_import_begin (ZebraHandle zh, const char *database,
1114                                const char *record_type)
1115 {
1116     ASSERTZH;
1117     yaz_log(log_level, "zebra_admin_import_begin db=%s rt=%s", 
1118                      database, record_type);
1119     zh->errCode = 0;
1120     if (zebra_select_database(zh, database))
1121         return 1;
1122     if (zebra_begin_trans (zh, 1))
1123         return 1;
1124     return 0;
1125 }
1126
1127 int zebra_admin_import_end (ZebraHandle zh)
1128 {
1129     ASSERTZH;
1130     yaz_log(log_level, "zebra_admin_import_end");
1131     zh->errCode = 0;
1132     zebra_end_trans (zh);
1133     return 0;
1134 }
1135
1136 int zebra_admin_import_segment (ZebraHandle zh, Z_Segment *segment)
1137 {
1138     SYSNO sysno;
1139     int i;
1140     ASSERTZH;
1141     yaz_log(log_level, "zebra_admin_import_segment");
1142     zh->errCode = 0;
1143     for (i = 0; i<segment->num_segmentRecords; i++)
1144     {
1145         Z_NamePlusRecord *npr = segment->segmentRecords[i];
1146
1147         printf ("--------------%d--------------------\n", i);
1148         /* FIXME - What! printing on stdout ??? */
1149         if (npr->which == Z_NamePlusRecord_intermediateFragment)
1150         {
1151             Z_FragmentSyntax *fragment = npr->u.intermediateFragment;
1152             if (fragment->which == Z_FragmentSyntax_notExternallyTagged)
1153             {
1154                 Odr_oct *oct = fragment->u.notExternallyTagged;
1155                 printf ("%.*s", (oct->len > 100 ? 100 : oct->len) ,
1156                         oct->buf);
1157                 
1158                 sysno = 0;
1159                 
1160                 zebra_update_record(zh, 
1161                                     0, /* record Type */
1162                                     &sysno,
1163                                     0, /* match */
1164                                     0, /* fname */
1165                                     oct->buf, oct->len,
1166                                     0);
1167             }
1168         }
1169     }
1170     return 0;
1171 }
1172
1173 int zebra_admin_exchange_record (ZebraHandle zh,
1174                                  const char *rec_buf,
1175                                  size_t rec_len,
1176                                  const char *recid_buf, size_t recid_len,
1177                                  int action)
1178     /* 1 = insert. Fail it already exists */
1179     /* 2 = replace. Fail it does not exist */
1180     /* 3 = delete. Fail if does not exist */
1181     /* 4 = update. Insert/replace */
1182 {
1183     SYSNO sysno = 0;
1184     char *rinfo = 0;
1185     char recid_z[256];
1186     ASSERTZH;
1187     assert(action>0 && action <=4);
1188     assert(rec_buf);
1189
1190     yaz_log(log_level, "zebra_admin_exchange_record ac=%d", action);
1191     zh->errCode = 0;
1192
1193     if (!recid_buf || recid_len <= 0 || recid_len >= sizeof(recid_z))
1194         return -1;
1195     memcpy (recid_z, recid_buf, recid_len);
1196     recid_z[recid_len] = 0;
1197
1198     if (zebra_begin_trans(zh, 1))
1199         return -1;
1200
1201     rinfo = dict_lookup (zh->reg->matchDict, recid_z);
1202     if (rinfo)
1203     {
1204         if (action == 1)  /* fail if insert */
1205         {
1206              zebra_end_trans(zh);
1207              return -1;
1208         }
1209
1210         memcpy (&sysno, rinfo+1, sizeof(sysno));
1211     }
1212     else
1213     {
1214         if (action == 2 || action == 3) /* fail if delete or update */
1215         {
1216             zebra_end_trans(zh);
1217             return -1;
1218         }
1219         action = 1;  /* make it an insert (if it's an update).. */
1220     }
1221     buffer_extract_record (zh, rec_buf, rec_len,
1222                            action == 3 ? 1 : 0 /* delete flag */,
1223                            0, /* test mode */
1224                            0, /* recordType */
1225                            &sysno, 
1226                            0, /* match */
1227                            0, /* fname */
1228                            0, /* force update */
1229                            1  /* allow update */
1230         );
1231     if (action == 1)
1232     {
1233         dict_insert (zh->reg->matchDict, recid_z, sizeof(sysno), &sysno);
1234     }
1235     else if (action == 3)
1236     {
1237         dict_delete (zh->reg->matchDict, recid_z);
1238     }
1239     zebra_end_trans(zh);
1240     return 0;
1241 }
1242
1243 int delete_w_handle(const char *info, void *handle)
1244 {
1245     ZebraHandle zh = (ZebraHandle) handle;
1246     ISAMC_P pos;
1247     ASSERTZH;
1248
1249     if (*info == sizeof(pos))
1250     {
1251         memcpy (&pos, info+1, sizeof(pos));
1252         isamb_unlink(zh->reg->isamb, pos);
1253     }
1254     return 0;
1255 }
1256
1257 static int delete_SU_handle(void *handle, int ord)
1258 {
1259     ZebraHandle zh = (ZebraHandle) handle;
1260     char ord_buf[20];
1261     int ord_len;
1262
1263     ord_len = key_SU_encode (ord, ord_buf);
1264     ord_buf[ord_len] = '\0';
1265
1266     assert (zh->reg->isamb);
1267     dict_delete_subtree(zh->reg->dict, ord_buf,
1268                         zh, delete_w_handle);
1269     return 0;
1270 }
1271
1272 int zebra_drop_database  (ZebraHandle zh, const char *database)
1273 {
1274     int ret = 0;
1275     ASSERTZH;
1276     yaz_log(log_level, "zebra_drop_database");
1277     zh->errCode = 0;
1278
1279     if (zebra_select_database (zh, database))
1280         return -1;
1281     if (zebra_begin_trans (zh, 1))
1282         return -1;
1283     if (zh->reg->isamb)
1284     {
1285         zebraExplain_curDatabase (zh->reg->zei, database);
1286         
1287         zebraExplain_trav_ord(zh->reg->zei, zh, delete_SU_handle);
1288         zebraExplain_removeDatabase(zh->reg->zei, zh);
1289     }
1290     else
1291     {
1292         yaz_log(YLOG_WARN, "drop database only supported for isam:b");
1293         ret = -1;
1294     }
1295     zebra_end_trans (zh);
1296     return ret;
1297 }
1298
1299 int zebra_create_database (ZebraHandle zh, const char *database)
1300 {
1301     ASSERTZH;
1302     yaz_log(log_level, "zebra_create_database %s",database);
1303     assert(database);
1304     zh->errCode = 0;
1305
1306     if (zebra_select_database (zh, database))
1307         return -1;
1308     if (zebra_begin_trans (zh, 1))
1309         return -1;
1310
1311     /* announce database */
1312     if (zebraExplain_newDatabase (zh->reg->zei, database, 0 
1313                                   /* explainDatabase */))
1314     {
1315         zebra_end_trans (zh);
1316         zh->errCode = 224;
1317         zh->errString = "database already exist";
1318         return -1;
1319     }
1320     zebra_end_trans (zh);
1321     return 0;
1322 }
1323
1324 int zebra_string_norm (ZebraHandle zh, unsigned reg_id,
1325                        const char *input_str, int input_len,
1326                        char *output_str, int output_len)
1327 {
1328     WRBUF wrbuf;
1329     ASSERTZH;
1330     assert(input_str);
1331     assert(output_str);
1332     yaz_log(log_level, "zebra_string_norm ");
1333     zh->errCode = 0;
1334     if (!zh->reg->zebra_maps)
1335         return -1;
1336     wrbuf = zebra_replace(zh->reg->zebra_maps, reg_id, "",
1337                           input_str, input_len);
1338     if (!wrbuf)
1339         return -2;
1340     if (wrbuf_len(wrbuf) >= output_len)
1341         return -3;
1342     if (wrbuf_len(wrbuf))
1343         memcpy (output_str, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
1344     output_str[wrbuf_len(wrbuf)] = '\0';
1345     return wrbuf_len(wrbuf);
1346 }
1347
1348
1349 int zebra_set_state (ZebraHandle zh, int val, int seqno)
1350     /* FIXME - zint seqno ?? */
1351 {
1352     char state_fname[256];
1353     char *fname;
1354     long p = getpid();
1355     FILE *f;
1356     ASSERTZH;
1357     yaz_log(log_level, "zebra_set_state v=%d seq=%d", val, seqno);
1358     zh->errCode = 0;
1359
1360     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1361     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1362     f = fopen (fname, "w");
1363
1364     yaz_log (YLOG_DEBUG, "zebra_set_state: %c %d %ld", val, seqno, p);
1365     fprintf (f, "%c %d %ld\n", val, seqno, p);
1366     fclose (f);
1367     xfree(fname);
1368     return 0;
1369 }
1370
1371 int zebra_get_state (ZebraHandle zh, char *val, int *seqno)
1372 {
1373     char state_fname[256];
1374     char *fname;
1375     FILE *f;
1376
1377     ASSERTZH;
1378     yaz_log(log_level, "zebra_get_state ");
1379     zh->errCode = 0;
1380     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1381     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1382     f = fopen (fname, "r");
1383     *val = 'o';
1384     *seqno = 0;
1385
1386     if (f)
1387     {
1388         fscanf (f, "%c %d", val, seqno);
1389         fclose (f);
1390     }
1391     xfree(fname);
1392     return 0;
1393 }
1394
1395 int zebra_begin_read (ZebraHandle zh)
1396 {
1397     return zebra_begin_trans(zh, 0);
1398 }
1399
1400 int zebra_end_read (ZebraHandle zh)
1401 {
1402     return zebra_end_trans(zh);
1403 }
1404
1405 static void read_res_for_transaction(ZebraHandle zh)
1406 {
1407     const char *group = res_get(zh->res, "group");
1408     const char *v;
1409     /* FIXME - do we still use groups ?? */
1410     
1411     zh->m_group = group;
1412     v = res_get_prefix(zh->res, "followLinks", group, "1");
1413     zh->m_follow_links = atoi(v);
1414
1415     zh->m_record_id = res_get_prefix(zh->res, "recordId", group, 0);
1416     zh->m_record_type = res_get_prefix(zh->res, "recordType", group, 0);
1417
1418     v = res_get_prefix(zh->res, "storeKeys", group, "1");
1419     zh->m_store_keys = atoi(v);
1420
1421     v = res_get_prefix(zh->res, "storeData", group, "1");
1422     zh->m_store_data = atoi(v);
1423
1424     v = res_get_prefix(zh->res, "explainDatabase", group, "0");
1425     zh->m_explain_database = atoi(v);
1426
1427     v = res_get_prefix(zh->res, "openRW", group, "1");
1428     zh->m_flag_rw = atoi(v);
1429
1430     v = res_get_prefix(zh->res, "fileVerboseLimit", group, "100000");
1431     zh->m_file_verbose_limit = atoi(v);
1432 }
1433
1434 int zebra_begin_trans (ZebraHandle zh, int rw)
1435 {
1436     ASSERTZH;
1437     zebra_select_default_database(zh);
1438     if (!zh->res)
1439     {
1440         zh->errCode = 2;
1441         zh->errString = "zebra_begin_trans: no database selected";
1442         return -1;
1443     }
1444     ASSERTZHRES;
1445     yaz_log(log_level, "zebra_begin_trans rw=%d",rw);
1446
1447     if (zh->user_perm)
1448     {
1449         if (rw && !strchr(zh->user_perm, 'w'))
1450         {
1451             zh->errCode = 223;
1452             zh->errString = 0;
1453             return -1;
1454         }
1455     }
1456
1457     assert (zh->res);
1458     if (rw)
1459     {
1460         int pass;
1461         int seqno = 0;
1462         char val = '?';
1463         const char *rval = 0;
1464         
1465         (zh->trans_no++);
1466         if (zh->trans_w_no)
1467         {
1468             read_res_for_transaction(zh);
1469             return 0;
1470         }
1471         if (zh->trans_no != 1)
1472         {
1473             zh->errCode = 2;
1474             zh->errString = "zebra_begin_trans: write trans not allowed within read trans";
1475             return -1;
1476         }
1477         if (zh->reg)
1478         {
1479             resultSetInvalidate (zh);
1480             zebra_register_close (zh->service, zh->reg);
1481         }
1482         zh->trans_w_no = zh->trans_no;
1483
1484         zh->errCode = 0;
1485         
1486         zh->records_inserted = 0;
1487         zh->records_updated = 0;
1488         zh->records_deleted = 0;
1489         zh->records_processed = 0;
1490         
1491 #if HAVE_SYS_TIMES_H
1492         times (&zh->tms1);
1493 #endif
1494         /* lock */
1495         if (zh->shadow_enable)
1496             rval = res_get (zh->res, "shadow");
1497         
1498         for (pass = 0; pass < 2; pass++)
1499         {
1500             if (rval)
1501             {
1502                 zebra_lock_r (zh->lock_normal);
1503                 zebra_lock_w (zh->lock_shadow);
1504             }
1505             else
1506             {
1507                 zebra_lock_w (zh->lock_normal);
1508                 zebra_lock_w (zh->lock_shadow);
1509             }
1510             
1511             zebra_get_state (zh, &val, &seqno);
1512             if (val == 'c')
1513             {
1514                 yaz_log (YLOG_WARN, "previous transaction didn't finish commit");
1515                 zebra_unlock (zh->lock_shadow);
1516                 zebra_unlock (zh->lock_normal);
1517                 zebra_commit (zh);
1518                 continue;
1519             }
1520             else if (val == 'd')
1521             {
1522                 if (rval)
1523                 {
1524                     BFiles bfs = bfs_create (res_get (zh->res, "shadow"),
1525                                              zh->path_reg);
1526                     yaz_log (YLOG_WARN, "previous transaction didn't reach commit");
1527                     bf_commitClean (bfs, rval);
1528                     bfs_destroy (bfs);
1529             }
1530                 else
1531                 {
1532                     yaz_log (YLOG_WARN, "your previous transaction didn't finish");
1533                 }
1534             }
1535             break;
1536         }
1537         if (pass == 2)
1538         {
1539             yaz_log (YLOG_FATAL, "zebra_begin_trans couldn't finish commit");
1540             abort();
1541             return -1;
1542         }
1543         zebra_set_state (zh, 'd', seqno);
1544         
1545         zh->reg = zebra_register_open (zh->service, zh->reg_name,
1546                                        1, rval ? 1 : 0, zh->res,
1547                                        zh->path_reg);
1548         if (zh->reg)
1549             zh->reg->seqno = seqno;
1550         else
1551         {
1552             zebra_set_state (zh, 'o', seqno);
1553             
1554             zebra_unlock (zh->lock_shadow);
1555             zebra_unlock (zh->lock_normal);
1556
1557             zh->trans_no--;
1558             zh->trans_w_no = 0;
1559
1560             zh->errCode = 2;
1561             zh->errString = "zebra_begin_trans: cannot open register";
1562             yaz_log(YLOG_FATAL, zh->errString);
1563             return -1;
1564         }
1565     }
1566     else
1567     {
1568         int dirty = 0;
1569         char val;
1570         int seqno;
1571         
1572         (zh->trans_no)++;
1573         
1574         if (zh->trans_no != 1)
1575         {
1576             zebra_flush_reg (zh);
1577             return 0;
1578         }
1579         zh->errCode = 0;
1580 #if HAVE_SYS_TIMES_H
1581         times (&zh->tms1);
1582 #endif
1583         if (!zh->res)
1584         {
1585             (zh->trans_no)--;
1586             zh->errCode = 109;
1587             return -1;
1588         }
1589         if (!zh->lock_normal || !zh->lock_shadow)
1590         {
1591             (zh->trans_no)--;
1592             zh->errCode = 2;
1593             return -1;
1594         }
1595         zebra_get_state (zh, &val, &seqno);
1596         if (val == 'd')
1597             val = 'o';
1598         
1599         if (!zh->reg)
1600             dirty = 1;
1601         else if (seqno != zh->reg->seqno)
1602         {
1603             yaz_log (YLOG_DEBUG, "reopen seqno cur/old %d/%d",
1604                      seqno, zh->reg->seqno);
1605             dirty = 1;
1606         }
1607         else if (zh->reg->last_val != val)
1608         {
1609             yaz_log (YLOG_DEBUG, "reopen last cur/old %d/%d",
1610                      val, zh->reg->last_val);
1611             dirty = 1;
1612         }
1613         if (!dirty)
1614             return 0;
1615         
1616         if (val == 'c')
1617             zebra_lock_r (zh->lock_shadow);
1618         else
1619             zebra_lock_r (zh->lock_normal);
1620         
1621         if (zh->reg)
1622         {
1623             resultSetInvalidate (zh);
1624             zebra_register_close (zh->service, zh->reg);
1625         }
1626         zh->reg = zebra_register_open (zh->service, zh->reg_name,
1627                                        0, val == 'c' ? 1 : 0,
1628                                        zh->res, zh->path_reg);
1629         if (!zh->reg)
1630         {
1631             zebra_unlock (zh->lock_normal);
1632             zebra_unlock (zh->lock_shadow);
1633             zh->trans_no--;
1634             zh->errCode = 109;
1635             return -1;
1636         }
1637         zh->reg->last_val = val;
1638         zh->reg->seqno = seqno;
1639     }
1640     read_res_for_transaction(zh);
1641     return 0;
1642 }
1643
1644 int zebra_end_trans (ZebraHandle zh)
1645 {
1646     ZebraTransactionStatus dummy;
1647     ASSERTZH;
1648     yaz_log(log_level, "zebra_end_trans");
1649     return zebra_end_transaction(zh, &dummy);
1650 }
1651
1652 int zebra_end_transaction (ZebraHandle zh, ZebraTransactionStatus *status)
1653 {
1654     char val;
1655     int seqno;
1656     const char *rval;
1657
1658     ASSERTZH;
1659     assert(status);
1660     yaz_log(log_level, "zebra_end_transaction");
1661
1662     status->processed = 0;
1663     status->inserted  = 0;
1664     status->updated   = 0;
1665     status->deleted   = 0;
1666     status->utime     = 0;
1667     status->stime     = 0;
1668
1669     if (!zh->res || !zh->reg)
1670     {
1671         zh->errCode = 2;
1672         zh->errString = "zebra_end_trans: no open transaction";
1673         return -1;
1674     }
1675     if (zh->trans_no != zh->trans_w_no)
1676     {
1677         zh->trans_no--;
1678         if (zh->trans_no != 0)
1679             return 0;
1680
1681         /* release read lock */
1682
1683         zebra_unlock (zh->lock_normal);
1684         zebra_unlock (zh->lock_shadow);
1685     }
1686     else
1687     {   /* release write lock */
1688         zh->trans_no--;
1689         zh->trans_w_no = 0;
1690         
1691         yaz_log (YLOG_DEBUG, "zebra_end_trans");
1692         rval = res_get (zh->res, "shadow");
1693         
1694         zebraExplain_runNumberIncrement (zh->reg->zei, 1);
1695         
1696         zebra_flush_reg (zh);
1697         
1698         resultSetInvalidate (zh);
1699
1700         zebra_register_close (zh->service, zh->reg);
1701         zh->reg = 0;
1702         
1703         yaz_log (YLOG_LOG, "Records: "ZINT_FORMAT" i/u/d "
1704                         ZINT_FORMAT"/"ZINT_FORMAT"/"ZINT_FORMAT, 
1705                  zh->records_processed, zh->records_inserted,
1706                  zh->records_updated, zh->records_deleted);
1707         
1708         status->processed = (int) zh->records_processed;
1709         status->inserted = (int) zh->records_inserted;
1710         status->updated = (int) zh->records_updated;
1711         status->deleted = (int) zh->records_deleted;
1712         
1713         zebra_get_state (zh, &val, &seqno);
1714         if (val != 'd')
1715         {
1716             BFiles bfs = bfs_create (rval, zh->path_reg);
1717             yaz_log (YLOG_DEBUG, "deleting shadow val=%c", val);
1718             bf_commitClean (bfs, rval);
1719             bfs_destroy (bfs);
1720         }
1721         if (!rval)
1722             seqno++;
1723         zebra_set_state (zh, 'o', seqno);
1724         
1725         zebra_unlock (zh->lock_shadow);
1726         zebra_unlock (zh->lock_normal);
1727         
1728     }
1729 #if HAVE_SYS_TIMES_H
1730     times (&zh->tms2);
1731     yaz_log (log_level, "user/system: %ld/%ld",
1732           (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1733           (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1734     
1735     status->utime = (long) (zh->tms2.tms_utime - zh->tms1.tms_utime);
1736     status->stime = (long) (zh->tms2.tms_stime - zh->tms1.tms_stime);
1737 #endif
1738     return 0;
1739 }
1740
1741 int zebra_repository_update (ZebraHandle zh, const char *path)
1742 {
1743     ASSERTZH;
1744     assert(path);
1745     zh->errCode = 0;
1746     yaz_log (log_level, "updating %s", path);
1747     repositoryUpdate (zh, path);
1748     return zh->errCode;
1749 }
1750
1751 int zebra_repository_delete (ZebraHandle zh, const char *path)
1752 {
1753     ASSERTZH;
1754     assert(path);
1755     zh->errCode = 0;
1756     yaz_log (log_level, "deleting %s", path);
1757     repositoryDelete (zh, path);
1758     return zh->errCode;
1759 }
1760
1761 int zebra_repository_show (ZebraHandle zh, const char *path)
1762 {
1763     ASSERTZH;
1764     assert(path);
1765     yaz_log(log_level, "zebra_repository_show");
1766     zh->errCode = 0;
1767     repositoryShow (zh, path);
1768     return zh->errCode;
1769 }
1770
1771 static int zebra_commit_ex (ZebraHandle zh, int clean_only)
1772 {
1773     int seqno;
1774     char val;
1775     const char *rval;
1776     BFiles bfs;
1777     ASSERTZH;
1778     zh->errCode = 0;
1779
1780     zebra_select_default_database(zh);
1781     if (!zh->res)
1782     {
1783         zh->errCode = 109;
1784         return -1;
1785     }
1786     rval = res_get (zh->res, "shadow");    
1787     if (!rval)
1788     {
1789         yaz_log (YLOG_WARN, "Cannot perform commit - No shadow area defined");
1790         return 0;
1791     }
1792
1793     zebra_lock_w (zh->lock_normal);
1794     zebra_lock_r (zh->lock_shadow);
1795
1796     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1797
1798     zebra_get_state (zh, &val, &seqno);
1799
1800     if (rval && *rval)
1801         bf_cache (bfs, rval);
1802     if (bf_commitExists (bfs))
1803     {
1804         if (clean_only)
1805             zebra_set_state (zh, 'd', seqno);
1806         else
1807         {
1808             zebra_set_state (zh, 'c', seqno);
1809             
1810             yaz_log (YLOG_DEBUG, "commit start");
1811             bf_commitExec (bfs);
1812 #ifndef WIN32
1813             sync ();
1814 #endif
1815         }
1816         yaz_log (YLOG_DEBUG, "commit clean");
1817         bf_commitClean (bfs, rval);
1818         seqno++;
1819         zebra_set_state (zh, 'o', seqno);
1820     }
1821     else
1822     {
1823         yaz_log (log_level, "nothing to commit");
1824     }
1825     bfs_destroy (bfs);
1826
1827     zebra_unlock (zh->lock_shadow);
1828     zebra_unlock (zh->lock_normal);
1829     return 0;
1830 }
1831
1832 int zebra_clean (ZebraHandle zh)
1833 {
1834     ASSERTZH;
1835     yaz_log(log_level, "zebra_clean");
1836     return zebra_commit_ex(zh, 1);
1837 }
1838
1839 int zebra_commit (ZebraHandle zh)
1840 {
1841     ASSERTZH;
1842     yaz_log(log_level, "zebra_commit");
1843     return zebra_commit_ex(zh, 0);
1844 }
1845
1846 int zebra_init (ZebraHandle zh)
1847 {
1848     const char *rval;
1849     BFiles bfs = 0;
1850     ASSERTZH;
1851     yaz_log(log_level, "zebra_init");
1852     zh->errCode = 0;
1853
1854     zebra_select_default_database(zh);
1855     if (!zh->res)
1856     {
1857         zh->errCode = 109;
1858         return -1;
1859     }
1860     rval = res_get (zh->res, "shadow");
1861
1862     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1863     if (!bfs)
1864         return -1;
1865     if (rval && *rval)
1866         bf_cache (bfs, rval);
1867     
1868     bf_reset (bfs);
1869     bfs_destroy (bfs);
1870     zebra_set_state (zh, 'o', 0);
1871     return 0;
1872 }
1873
1874 int zebra_compact (ZebraHandle zh)
1875 {
1876     BFiles bfs;
1877     ASSERTZH;
1878     yaz_log(log_level, "zebra_compact");
1879     zh->errCode = 0;
1880     if (!zh->res)
1881     {
1882         zh->errCode = 109;
1883         return -1;
1884     }
1885     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1886     inv_compact (bfs);
1887     bfs_destroy (bfs);
1888     return 0;
1889 }
1890
1891 int zebra_result (ZebraHandle zh, int *code, char **addinfo)
1892 {
1893     ASSERTZH;
1894     yaz_log(log_level, "zebra_result");
1895     *code = zh->errCode;
1896     *addinfo = zh->errString;
1897     return 0;
1898 }
1899
1900 int zebra_shadow_enable (ZebraHandle zh, int value)
1901 {
1902     ASSERTZH;
1903     yaz_log(log_level, "zebra_shadow_enable");
1904     zh->errCode = 0;
1905     zh->shadow_enable = value;
1906     return 0;
1907 }
1908
1909 int zebra_octet_term_encoding(ZebraHandle zh, const char *encoding)
1910 {
1911     ASSERTZH;
1912     assert(encoding);
1913     yaz_log(log_level, "zebra_octet_term_encoding");
1914     zh->errCode = 0;
1915
1916     if (zh->iconv_to_utf8 != 0)
1917         yaz_iconv_close(zh->iconv_to_utf8);
1918     if (zh->iconv_from_utf8 != 0)
1919         yaz_iconv_close(zh->iconv_from_utf8);
1920     
1921     zh->iconv_to_utf8 =
1922         yaz_iconv_open ("UTF-8", encoding);
1923     if (zh->iconv_to_utf8 == 0)
1924         yaz_log (YLOG_WARN, "iconv: %s to UTF-8 unsupported", encoding);
1925     zh->iconv_from_utf8 =
1926         yaz_iconv_open (encoding, "UTF-8");
1927     if (zh->iconv_to_utf8 == 0)
1928         yaz_log (YLOG_WARN, "iconv: UTF-8 to %s unsupported", encoding);
1929
1930     return 0;
1931 }
1932
1933 int zebra_record_encoding (ZebraHandle zh, const char *encoding)
1934 {
1935     ASSERTZH;
1936     yaz_log(log_level, "zebra_record_encoding");
1937     zh->errCode = 0;
1938     xfree(zh->record_encoding);
1939     zh->record_encoding = 0;
1940     if (encoding)
1941         zh->record_encoding = xstrdup (encoding);
1942     return 0;
1943 }
1944
1945 int zebra_set_resource(ZebraHandle zh, const char *name, const char *value)
1946 {
1947     ASSERTZH;
1948     assert(name);
1949     assert(value);
1950     yaz_log(log_level, "zebra_set_resource %s:%s",name,value);
1951     zh->errCode = 0;
1952     res_set(zh->res, name, value);
1953     return 0;
1954 }
1955
1956 const char *zebra_get_resource(ZebraHandle zh,
1957                                const char *name, const char *defaultvalue)
1958 {
1959     const char *v;
1960     ASSERTZH;
1961     assert(name);
1962     assert(defaultvalue);
1963     v= res_get_def( zh->res, name, (char *)defaultvalue);
1964     zh->errCode = 0;
1965     yaz_log(log_level, "zebra_get_resource %s:%s",name,v);
1966     return v;
1967 }
1968
1969 /* moved from zebra_api_ext.c by pop */
1970 /* FIXME: Should this really be public??? -Heikki */
1971
1972 int zebra_trans_no (ZebraHandle zh)
1973 {
1974     ASSERTZH;
1975     yaz_log(log_level, "zebra_trans_no");
1976     return zh->trans_no;
1977 }
1978
1979 int zebra_get_shadow_enable (ZebraHandle zh)
1980 {
1981     ASSERTZH;
1982     yaz_log(log_level, "zebra_get_shadow_enable");
1983     return (zh->shadow_enable);
1984 }
1985
1986 int zebra_set_shadow_enable (ZebraHandle zh, int value)
1987 {
1988     ASSERTZH;
1989     yaz_log(log_level, "zebra_set_shadow_enable %d",value);
1990     zh->shadow_enable = value;
1991     return 0;
1992 }
1993
1994 /* Used by Perl API.. Added the record buffer dup to zebra_records_retrieve
1995    so that it's identicical to the original api_records_retrieve */
1996 void api_records_retrieve (ZebraHandle zh, ODR stream,
1997                            const char *setname, Z_RecordComposition *comp,
1998                            oid_value input_format, int num_recs,
1999                            ZebraRetrievalRecord *recs)
2000 {
2001     zebra_records_retrieve(zh, stream, setname, comp, input_format,
2002                            num_recs, recs);
2003 }
2004
2005 /* ---------------------------------------------------------------------------
2006   Record insert(=update), delete 
2007
2008   If sysno is provided, then it's used to identify the record.
2009   If not, and match_criteria is provided, then sysno is guessed
2010   If not, and a record is provided, then sysno is got from there
2011 NOTE: Now returns 0 at success and updates sysno, which is an int*
2012   20-jun-2003 Heikki
2013 */
2014
2015 int zebra_add_record(ZebraHandle zh,
2016                      const char *buf, int buf_size)
2017 {
2018     SYSNO sysno = 0;
2019     return zebra_update_record(zh, 0, &sysno, 0, 0, buf, buf_size, 0);
2020 }
2021
2022 int zebra_insert_record (ZebraHandle zh, 
2023                          const char *recordType,
2024                          SYSNO *sysno, const char *match, const char *fname,
2025                          const char *buf, int buf_size, int force_update)
2026 {
2027     int res;
2028     ASSERTZH;
2029     assert(sysno);
2030     assert(buf);
2031     yaz_log(log_level, "zebra_insert_record sysno=" ZINT_FORMAT, *sysno);
2032
2033     if (buf_size < 1)
2034         buf_size = strlen(buf);
2035
2036     if (zebra_begin_trans(zh, 1))
2037         return 1;
2038     res = buffer_extract_record (zh, buf, buf_size, 
2039                                  0, /* delete_flag  */
2040                                  0, /* test_mode */
2041                                  recordType,
2042                                  sysno,   
2043                                  match, fname,
2044                                  0, 
2045                                  0); /* allow_update */
2046     zebra_end_trans(zh); 
2047     return res; 
2048 }
2049
2050 int zebra_update_record (ZebraHandle zh, 
2051                          const char *recordType,
2052                          SYSNO* sysno, const char *match, const char *fname,
2053                          const char *buf, int buf_size,
2054                          int force_update)
2055 {
2056     int res;
2057     ASSERTZH;
2058     assert(sysno);
2059     assert(buf);
2060
2061     yaz_log(log_level, "zebra_update_record sysno=" ZINT_FORMAT, *sysno);
2062
2063     if (buf_size < 1) buf_size = strlen(buf);
2064
2065     if (zebra_begin_trans(zh, 1))
2066         return 1;
2067     res = buffer_extract_record (zh, buf, buf_size, 
2068                                  0, /* delete_flag */
2069                                  0, /* test_mode */
2070                                  recordType,
2071                                  sysno,   
2072                                  match, fname,
2073                                  force_update, 
2074                                  1); /* allow_update */
2075     zebra_end_trans(zh); 
2076     return res; 
2077 }
2078
2079 int zebra_delete_record (ZebraHandle zh, 
2080                          const char *recordType,
2081                          SYSNO *sysno, const char *match, const char *fname,
2082                          const char *buf, int buf_size,
2083                          int force_update) 
2084 {
2085     int res;
2086     ASSERTZH;
2087     assert(sysno);
2088     assert(buf);
2089     yaz_log(log_level, "zebra_delete_record sysno=" ZINT_FORMAT, *sysno);
2090
2091     if (buf_size < 1) buf_size = strlen(buf);
2092
2093     if (zebra_begin_trans(zh, 1))
2094         return 1;
2095     res = buffer_extract_record (zh, buf, buf_size,
2096                                  1, /* delete_flag */
2097                                  0, /* test_mode */
2098                                  recordType,
2099                                  sysno,
2100                                  match,fname,
2101                                  force_update,
2102                                  1); /* allow_update */
2103     zebra_end_trans(zh);
2104     return res;   
2105 }
2106
2107 /* ---------------------------------------------------------------------------
2108   Searching 
2109 */
2110
2111 int zebra_search_PQF (ZebraHandle zh, const char *pqf_query,
2112                       const char *setname, zint *numhits)
2113 {
2114     zint hits = 0;
2115     int res = -1;
2116     Z_RPNQuery *query;
2117     ODR odr = odr_createmem(ODR_ENCODE);
2118     ASSERTZH;
2119     assert(pqf_query);
2120     assert(setname);
2121
2122     yaz_log(log_level, "zebra_search_PQF s=%s q=%s",setname, pqf_query);
2123     
2124     query = p_query_rpn (odr, PROTO_Z3950, pqf_query);
2125     
2126     if (!query)
2127         yaz_log (YLOG_WARN, "bad query %s\n", pqf_query);
2128     else
2129         res = zebra_search_RPN (zh, odr, query, setname, &hits);
2130     
2131     odr_destroy(odr);
2132
2133     yaz_log(log_level, "Hits: " ZINT_FORMAT, hits);
2134
2135     if (numhits)
2136         *numhits = hits;
2137
2138     return res;
2139 }
2140
2141 /* ---------------------------------------------------------------------------
2142   Sort - a simplified interface, with optional read locks.
2143 */
2144 int zebra_sort_by_specstr (ZebraHandle zh, ODR stream,
2145                            const char *sort_spec,
2146                            const char *output_setname,
2147                            const char **input_setnames) 
2148 {
2149     int num_input_setnames = 0;
2150     int sort_status = 0;
2151     Z_SortKeySpecList *sort_sequence;
2152     ASSERTZH;
2153     assert(stream);
2154     assert(sort_spec);
2155     assert(output_setname);
2156     assert(input_setnames);
2157     sort_sequence = yaz_sort_spec (stream, sort_spec);
2158     yaz_log(log_level, "sort (FIXME) ");
2159     if (!sort_sequence)
2160     {
2161         yaz_log(YLOG_WARN, "invalid sort specs '%s'", sort_spec);
2162         zh->errCode = 207;
2163         return -1;
2164     }
2165     
2166     /* we can do this, since the perl typemap code for char** will 
2167        put a NULL at the end of list */
2168     while (input_setnames[num_input_setnames]) num_input_setnames++;
2169
2170     if (zebra_begin_read (zh))
2171         return -1;
2172     
2173     resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
2174                    output_setname, sort_sequence, &sort_status);
2175     
2176     zebra_end_read(zh);
2177     return sort_status;
2178 }
2179
2180 struct BFiles_struct *zebra_get_bfs(ZebraHandle zh)
2181 {
2182     if (zh && zh->reg)
2183         return zh->reg->bfs;
2184     return 0;
2185 }