Many public functions returns ZEBRA_RES rather than int to avoid
[idzebra-moved-to-github.git] / index / zebraapi.c
1 /* $Id: zebraapi.c,v 1.161 2005-04-15 10:47:48 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 = isamc_open (reg->bfs, FNAME_ISAMC,
349                                     rw, key_isamc_m(res, &isamc_m))))
350         {
351             yaz_log (YLOG_WARN, "isamc_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 ZEBRA_RES 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 ZEBRA_OK;
411 }
412
413 ZEBRA_RES 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 ZEBRA_OK;
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             isamc_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 ZEBRA_RES zebra_stop(ZebraService zs)
464 {
465     if (!zs)
466         return ZEBRA_OK;
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 ZEBRA_OK;
485 }
486
487 ZEBRA_RES 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 ZEBRA_OK;
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 ZEBRA_OK;
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 void 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;
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 }
650
651 void map_basenames_func (void *vp, const char *name, const char *value)
652 {
653     struct map_baseinfo *p = (struct map_baseinfo *) vp;
654     int i, no;
655     char fromdb[128], todb[8][128];
656
657     assert(value);
658     assert(name);
659     assert(vp);
660     
661     no =
662         sscanf (value, "%127s %127s %127s %127s %127s %127s %127s %127s %127s",
663                 fromdb, todb[0], todb[1], todb[2], todb[3], todb[4],
664                 todb[5], todb[6], todb[7]);
665     if (no < 2)
666         return ;
667     no--;
668     for (i = 0; i<p->num_bases; i++)
669         if (p->basenames[i] && !STRCASECMP (p->basenames[i], fromdb))
670         {
671             p->basenames[i] = 0;
672             for (i = 0; i < no; i++)
673             {
674                 if (p->new_num_bases == p->new_num_max)
675                     return;
676                 p->new_basenames[(p->new_num_bases)++] = 
677                     nmem_strdup (p->mem, todb[i]);
678             }
679             return;
680         }
681 }
682
683 int zebra_select_default_database(ZebraHandle zh)
684 {
685     if (!zh->res)
686     {
687         /* no database has been selected - so we select based on
688            resource setting (including group)
689         */
690         const char *group = res_get(zh->service->global_res, "group");
691         const char *v = res_get_prefix(zh->service->global_res,
692                                        "database", group, "Default");
693         zebra_select_database(zh, v);
694     }
695     return 0;
696 }
697
698 void map_basenames (ZebraHandle zh, ODR stream,
699                     int *num_bases, char ***basenames)
700 {
701     struct map_baseinfo info;
702     struct map_baseinfo *p = &info;
703     int i;
704     ASSERTZH;
705     yaz_log(log_level, "map_basenames ");
706     assert(stream);
707
708     zh->errCode = 0;
709
710     info.zh = zh;
711
712     info.num_bases = *num_bases;
713     info.basenames = *basenames;
714     info.new_num_max = 128;
715     info.new_num_bases = 0;
716     info.new_basenames = (char **)
717         odr_malloc (stream, sizeof(*info.new_basenames) * info.new_num_max);
718     info.mem = stream->mem;
719
720     res_trav (zh->service->global_res, "mapdb", &info, map_basenames_func);
721     
722     for (i = 0; i<p->num_bases; i++)
723         if (p->basenames[i] && p->new_num_bases < p->new_num_max)
724         {
725             p->new_basenames[(p->new_num_bases)++] = 
726                 nmem_strdup (p->mem, p->basenames[i]);
727         }
728     *num_bases = info.new_num_bases;
729     *basenames = info.new_basenames;
730     for (i = 0; i<*num_bases; i++)
731         yaz_log (YLOG_DEBUG, "base %s", (*basenames)[i]);
732 }
733
734 ZEBRA_RES zebra_select_database (ZebraHandle zh, const char *basename)
735 {
736     ASSERTZH;
737     yaz_log(log_level, "zebra_select_database %s",basename);
738     assert(basename);
739     zh->errCode = 0;
740     return zebra_select_databases (zh, 1, &basename);
741 }
742
743 ZEBRA_RES zebra_select_databases (ZebraHandle zh, int num_bases,
744                                   const char **basenames)
745 {
746     int i;
747     const char *cp;
748     int len = 0;
749     char *new_reg = 0;
750     ASSERTZH;
751     assert(basenames);
752
753     yaz_log(log_level, "zebra_select_databases n=%d [0]=%s",
754                     num_bases,basenames[0]);
755     zh->errCode = 0;
756     
757     if (num_bases < 1)
758     {
759         zh->errCode = 23;
760         return ZEBRA_FAIL;
761     }
762     for (i = 0; i < zh->num_basenames; i++)
763         xfree(zh->basenames[i]);
764     xfree(zh->basenames);
765     
766     zh->num_basenames = num_bases;
767     zh->basenames = xmalloc(zh->num_basenames * sizeof(*zh->basenames));
768     for (i = 0; i < zh->num_basenames; i++)
769         zh->basenames[i] = xstrdup (basenames[i]);
770
771     cp = strrchr(basenames[0], '/');
772     if (cp)
773     {
774         len = cp - basenames[0];
775         new_reg = xmalloc(len + 1);
776         memcpy (new_reg, basenames[0], len);
777         new_reg[len] = '\0';
778     }
779     else
780         new_reg = xstrdup ("");
781     for (i = 1; i<num_bases; i++)
782     {
783         const char *cp1;
784
785         cp1 = strrchr (basenames[i], '/');
786         if (cp)
787         {
788             if (!cp1)
789             {
790                 zh->errCode = 23;
791                 return -1;
792             }
793             if (len != cp1 - basenames[i] ||
794                 memcmp (basenames[i], new_reg, len))
795             {
796                 zh->errCode = 23;
797                 return -1;
798             }
799         }
800         else
801         {
802             if (cp1)
803             {
804                 zh->errCode = 23;
805                 return ZEBRA_FAIL;
806             }
807         }
808     }
809     zebra_select_register (zh, new_reg);
810     xfree(new_reg);
811     if (!zh->res)
812     {
813         zh->errCode = 109;
814         return ZEBRA_FAIL;
815     }
816     if (!zh->lock_normal || !zh->lock_shadow)
817     {
818         zh->errCode = 2;
819         return ZEBRA_FAIL;
820     }
821     return ZEBRA_OK;
822 }
823
824 ZEBRA_RES zebra_search_RPN (ZebraHandle zh, ODR o, Z_RPNQuery *query,
825                             const char *setname, zint *hits)
826 {
827     ZEBRA_RES r;
828     ASSERTZH;
829     assert(o);
830     assert(query);
831     assert(hits);
832     assert(setname);
833     yaz_log(log_level, "zebra_search_rpn");
834     zh->errCode = 0;
835     zh->hits = 0;
836     *hits = 0;
837
838     if (zebra_begin_read(zh) == ZEBRA_FAIL)
839         return ZEBRA_FAIL;
840
841     r = resultSetAddRPN(zh, odr_extract_mem(o), query, 
842                         zh->num_basenames, zh->basenames, setname);
843     zebra_end_read(zh);
844     *hits = zh->hits;
845     return r;
846 }
847
848 ZEBRA_RES zebra_records_retrieve (ZebraHandle zh, ODR stream,
849                                   const char *setname,
850                                   Z_RecordComposition *comp,
851                                   oid_value input_format, int num_recs,
852                                   ZebraRetrievalRecord *recs)
853 {
854     ZebraMetaRecord *poset;
855     int i;
856     ZEBRA_RES ret = ZEBRA_OK;
857     zint *pos_array;
858     ASSERTZH;
859     assert(stream);
860     assert(setname);
861     assert(recs);
862     assert(num_recs>0);
863
864     yaz_log(log_level, "zebra_records_retrieve n=%d", num_recs);
865     zh->errCode = 0;
866
867     if (!zh->res)
868     {
869         zh->errCode = 30;
870         zh->errString = odr_strdup(stream, setname);
871         return ZEBRA_FAIL;
872     }
873     
874     zh->errCode = 0;
875
876     if (zebra_begin_read (zh) == ZEBRA_FAIL)
877         return ZEBRA_FAIL;
878
879     pos_array = (zint *) xmalloc(num_recs * sizeof(*pos_array));
880     for (i = 0; i<num_recs; i++)
881         pos_array[i] = recs[i].position;
882     poset = zebra_meta_records_create(zh, setname, num_recs, pos_array);
883     if (!poset)
884     {
885         yaz_log (YLOG_DEBUG, "zebraPosSetCreate error");
886         zh->errCode = 30;
887         zh->errString = nmem_strdup (stream->mem, setname);
888         ret = ZEBRA_FAIL;
889     }
890     else
891     {
892         for (i = 0; i<num_recs; i++)
893         {
894             if (poset[i].term)
895             {
896                 recs[i].errCode = 0;
897                 recs[i].format = VAL_SUTRS;
898                 recs[i].len = strlen(poset[i].term);
899                 recs[i].buf = poset[i].term;
900                 recs[i].base = poset[i].db;
901             }
902             else if (poset[i].sysno)
903             {
904                 char *buf;
905                 int len;
906                 recs[i].errCode =
907                     zebra_record_fetch(zh, poset[i].sysno, poset[i].score,
908                                        stream, input_format, comp,
909                                        &recs[i].format, &buf, &len,
910                                        &recs[i].base, &recs[i].errString);
911                 recs[i].len = len;
912                 if (len > 0)
913                 {
914                     recs[i].buf = (char*) odr_malloc(stream, len);
915                     memcpy(recs[i].buf, buf, len);
916                 }
917                 else
918                     recs[i].buf = buf;
919                 recs[i].score = poset[i].score;
920                 recs[i].sysno = poset[i].sysno;
921             }
922             else
923             {
924                 char num_str[20];
925
926                 sprintf (num_str, ZINT_FORMAT, pos_array[i]);   
927                 zh->errCode = 13;
928                 zh->errString = odr_strdup (stream, num_str);
929                 ret = ZEBRA_FAIL;
930                 break;
931             }
932         }
933         zebra_meta_records_destroy(zh, poset, num_recs);
934     }
935     zebra_end_read (zh);
936     xfree(pos_array);
937     return ret;
938 }
939
940 ZEBRA_RES zebra_scan_PQF(ZebraHandle zh, ODR stream, const char *query,
941                          int *position,
942                          int *num_entries, ZebraScanEntry **entries,
943                          int *is_partial)
944 {
945     YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
946     Z_AttributesPlusTerm *zapt;
947     int *attributeSet;
948     
949     if (!(zapt = yaz_pqf_scan(pqf_parser, stream, &attributeSet, query)))
950     {
951         yaz_pqf_destroy (pqf_parser);
952         return ZEBRA_FAIL;
953     }
954     yaz_pqf_destroy (pqf_parser);
955     return zebra_scan(zh, stream, zapt, VAL_BIB1,
956                       position, num_entries, entries, is_partial);
957 }
958
959 ZEBRA_RES zebra_scan (ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
960                       oid_value attributeset,
961                       int *position,
962                       int *num_entries, ZebraScanEntry **entries,
963                       int *is_partial)
964 {
965     ZEBRA_RES res;
966     ASSERTZH;
967     assert(stream);
968     assert(zapt);
969     assert(position);
970     assert(num_entries);
971     assert(is_partial);
972     assert(entries);
973     yaz_log(log_level, "zebra_scan");
974     zh->errCode = 0;
975     if (zebra_begin_read (zh) == ZEBRA_FAIL)
976     {
977         *entries = 0;
978         *num_entries = 0;
979         return ZEBRA_FAIL;
980     }
981     res = rpn_scan (zh, stream, zapt, attributeset,
982                     zh->num_basenames, zh->basenames, position,
983                     num_entries, entries, is_partial, 0, 0);
984     zebra_end_read (zh);
985     return res;
986 }
987
988 ZEBRA_RES zebra_sort (ZebraHandle zh, ODR stream,
989                       int num_input_setnames, const char **input_setnames,
990                       const char *output_setname,
991                       Z_SortKeySpecList *sort_sequence,
992                       int *sort_status)
993 {
994     ASSERTZH;
995     assert(stream);
996     assert(num_input_setnames>0);
997     assert(input_setnames);
998     assert(sort_sequence);
999     assert(sort_status);
1000     yaz_log(log_level, "zebra_sort");
1001     zh->errCode = 0;
1002     if (zebra_begin_read (zh) == ZEBRA_FAIL)
1003         return ZEBRA_FAIL;
1004     resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
1005                    output_setname, sort_sequence, sort_status);
1006     return zebra_end_read(zh);
1007 }
1008
1009 int zebra_deleteResultSet(ZebraHandle zh, int function,
1010                           int num_setnames, char **setnames,
1011                           int *statuses)
1012 {
1013     int i, status;
1014     ASSERTZH;
1015     assert(statuses);
1016     yaz_log(log_level, "zebra_deleteResultSet n=%d",num_setnames);
1017     zh->errCode = 0;
1018     if (zebra_begin_read(zh))
1019         return Z_DeleteStatus_systemProblemAtTarget;
1020     switch (function)
1021     {
1022     case Z_DeleteResultSetRequest_list:
1023         assert(num_setnames>0);
1024         assert(setnames);
1025         resultSetDestroy (zh, num_setnames, setnames, statuses);
1026         break;
1027     case Z_DeleteResultSetRequest_all:
1028         resultSetDestroy (zh, -1, 0, statuses);
1029         break;
1030     }
1031     zebra_end_read (zh);
1032     status = Z_DeleteStatus_success;
1033     for (i = 0; i<num_setnames; i++)
1034         if (statuses[i] == Z_DeleteStatus_resultSetDidNotExist)
1035             status = statuses[i];
1036     return status;
1037 }
1038
1039 int zebra_errCode (ZebraHandle zh)
1040 {
1041     if (zh)
1042     {
1043         yaz_log(log_level, "zebra_errCode: %d",zh->errCode);
1044         return zh->errCode;
1045     }
1046     yaz_log(log_level, "zebra_errCode: o");
1047     return 0; 
1048 }
1049
1050 const char *zebra_errString (ZebraHandle zh)
1051 {
1052     const char *e="";
1053     if (zh)
1054         e= diagbib1_str (zh->errCode);
1055     yaz_log(log_level, "zebra_errString: %s",e);
1056     return e;
1057 }
1058
1059 char *zebra_errAdd (ZebraHandle zh)
1060 {
1061     char *a="";
1062     if (zh)
1063         a= zh->errString;
1064     yaz_log(log_level, "zebra_errAdd: %s",a);
1065     return a;
1066 }
1067
1068 void zebra_clearError(ZebraHandle zh)
1069 {
1070     if (zh)
1071     {
1072         zh->errCode = 0;
1073         zh->errString = 0;
1074     }
1075 }
1076
1077 ZEBRA_RES zebra_auth (ZebraHandle zh, const char *user, const char *pass)
1078 {
1079     const char *p;
1080     char u[40];
1081     ZebraService zs;
1082
1083     ASSERTZH;
1084     zh->errCode = 0;
1085     zs= zh->service;
1086     
1087     sprintf(u, "perm.%.30s", user ? user : "anonymous");
1088     p = res_get(zs->global_res, u);
1089     xfree(zh->user_perm);
1090     zh->user_perm = xstrdup(p ? p : "r");
1091
1092     /* users that don't require a password .. */
1093     if (zh->user_perm && strchr(zh->user_perm, 'a'))
1094         return ZEBRA_OK;
1095     
1096     if (!zs->passwd_db || !passwd_db_auth (zs->passwd_db, user, pass))
1097         return ZEBRA_OK;
1098     return ZEBRA_FAIL;
1099 }
1100
1101 ZEBRA_RES zebra_admin_import_begin (ZebraHandle zh, const char *database,
1102                                const char *record_type)
1103 {
1104     ASSERTZH;
1105     yaz_log(log_level, "zebra_admin_import_begin db=%s rt=%s", 
1106                      database, record_type);
1107     zh->errCode = 0;
1108     if (zebra_select_database(zh, database) == ZEBRA_FAIL)
1109         return ZEBRA_FAIL;
1110     return zebra_begin_trans(zh, 1);
1111 }
1112
1113 ZEBRA_RES zebra_admin_import_end (ZebraHandle zh)
1114 {
1115     ASSERTZH;
1116     yaz_log(log_level, "zebra_admin_import_end");
1117     zh->errCode = 0;
1118     return zebra_end_trans(zh);
1119 }
1120
1121 ZEBRA_RES zebra_admin_import_segment (ZebraHandle zh, Z_Segment *segment)
1122 {
1123     ZEBRA_RES res = ZEBRA_OK;
1124     SYSNO sysno;
1125     int i;
1126     ASSERTZH;
1127     yaz_log(log_level, "zebra_admin_import_segment");
1128     zh->errCode = 0;
1129     for (i = 0; i<segment->num_segmentRecords; i++)
1130     {
1131         Z_NamePlusRecord *npr = segment->segmentRecords[i];
1132
1133         if (npr->which == Z_NamePlusRecord_intermediateFragment)
1134         {
1135             Z_FragmentSyntax *fragment = npr->u.intermediateFragment;
1136             if (fragment->which == Z_FragmentSyntax_notExternallyTagged)
1137             {
1138                 Odr_oct *oct = fragment->u.notExternallyTagged;
1139                 sysno = 0;
1140                 
1141                 if ( zebra_update_record(zh, 
1142                                          0, /* record Type */
1143                                          &sysno,
1144                                          0, /* match */
1145                                          0, /* fname */
1146                                          oct->buf, oct->len,
1147                                          0) == ZEBRA_FAIL)
1148                     res = ZEBRA_FAIL;
1149             }
1150         }
1151     }
1152     return res;
1153 }
1154
1155 ZEBRA_RES zebra_admin_exchange_record (ZebraHandle zh,
1156                                        const char *rec_buf,
1157                                        size_t rec_len,
1158                                        const char *recid_buf, size_t recid_len,
1159                                        int action)
1160     /* 1 = insert. Fail it already exists */
1161     /* 2 = replace. Fail it does not exist */
1162     /* 3 = delete. Fail if does not exist */
1163     /* 4 = update. Insert/replace */
1164 {
1165     ZEBRA_RES res;
1166     SYSNO sysno = 0;
1167     char *rinfo = 0;
1168     char recid_z[256];
1169     ASSERTZH;
1170     assert(action>0 && action <=4);
1171     assert(rec_buf);
1172
1173     yaz_log(log_level, "zebra_admin_exchange_record ac=%d", action);
1174     zh->errCode = 0;
1175
1176     if (!recid_buf || recid_len <= 0 || recid_len >= sizeof(recid_z))
1177         return ZEBRA_FAIL;
1178
1179     memcpy (recid_z, recid_buf, recid_len);
1180     recid_z[recid_len] = 0;
1181
1182     if (zebra_begin_trans(zh, 1) == ZEBRA_FAIL)
1183         return ZEBRA_FAIL;
1184
1185     rinfo = dict_lookup (zh->reg->matchDict, recid_z);
1186     if (rinfo)
1187     {
1188         if (action == 1)  /* fail if insert */
1189         {
1190              zebra_end_trans(zh);
1191              return ZEBRA_FAIL;
1192         }
1193
1194         memcpy (&sysno, rinfo+1, sizeof(sysno));
1195     }
1196     else
1197     {
1198         if (action == 2 || action == 3) /* fail if delete or update */
1199         {
1200             zebra_end_trans(zh);
1201             return ZEBRA_FAIL;
1202         }
1203         action = 1;  /* make it an insert (if it's an update).. */
1204     }
1205     res = buffer_extract_record (zh, rec_buf, rec_len,
1206                                  action == 3 ? 1 : 0 /* delete flag */,
1207                                  0, /* test mode */
1208                                  0, /* recordType */
1209                                  &sysno, 
1210                                  0, /* match */
1211                                  0, /* fname */
1212                            0, /* force update */
1213                                  1  /* allow update */
1214         );
1215     if (action == 1)
1216     {
1217         dict_insert (zh->reg->matchDict, recid_z, sizeof(sysno), &sysno);
1218     }
1219     else if (action == 3)
1220     {
1221         dict_delete (zh->reg->matchDict, recid_z);
1222     }
1223     zebra_end_trans(zh);
1224     return res;
1225 }
1226
1227 int delete_w_handle(const char *info, void *handle)
1228 {
1229     ZebraHandle zh = (ZebraHandle) handle;
1230     ISAM_P pos;
1231     ASSERTZH;
1232
1233     if (*info == sizeof(pos))
1234     {
1235         memcpy (&pos, info+1, sizeof(pos));
1236         isamb_unlink(zh->reg->isamb, pos);
1237     }
1238     return 0;
1239 }
1240
1241 static int delete_SU_handle(void *handle, int ord)
1242 {
1243     ZebraHandle zh = (ZebraHandle) handle;
1244     char ord_buf[20];
1245     int ord_len;
1246
1247     ord_len = key_SU_encode (ord, ord_buf);
1248     ord_buf[ord_len] = '\0';
1249
1250     assert (zh->reg->isamb);
1251     dict_delete_subtree(zh->reg->dict, ord_buf,
1252                         zh, delete_w_handle);
1253     return 0;
1254 }
1255
1256 ZEBRA_RES zebra_drop_database  (ZebraHandle zh, const char *database)
1257 {
1258     ZEBRA_RES ret = ZEBRA_OK;
1259     ASSERTZH;
1260     yaz_log(log_level, "zebra_drop_database");
1261     zh->errCode = 0;
1262
1263     if (zebra_select_database (zh, database) == ZEBRA_FAIL)
1264         return ZEBRA_FAIL;
1265     if (zebra_begin_trans (zh, 1) == ZEBRA_FAIL)
1266         return ZEBRA_FAIL;
1267     if (zh->reg->isamb)
1268     {
1269         zebraExplain_curDatabase (zh->reg->zei, database);
1270         
1271         zebraExplain_trav_ord(zh->reg->zei, zh, delete_SU_handle);
1272         zebraExplain_removeDatabase(zh->reg->zei, zh);
1273     }
1274     else
1275     {
1276         yaz_log(YLOG_WARN, "drop database only supported for isam:b");
1277         ret = ZEBRA_FAIL;
1278     }
1279     zebra_end_trans (zh);
1280     return ret;
1281 }
1282
1283 ZEBRA_RES zebra_create_database (ZebraHandle zh, const char *database)
1284 {
1285     ASSERTZH;
1286     yaz_log(log_level, "zebra_create_database %s", database);
1287     assert(database);
1288     zh->errCode = 0;
1289
1290     if (zebra_select_database (zh, database) == ZEBRA_FAIL)
1291         return ZEBRA_FAIL;
1292     if (zebra_begin_trans (zh, 1))
1293         return ZEBRA_FAIL;
1294
1295     /* announce database */
1296     if (zebraExplain_newDatabase (zh->reg->zei, database, 0 
1297                                   /* explainDatabase */))
1298     {
1299         zebra_end_trans (zh);
1300         zh->errCode = 224;
1301         zh->errString = "database already exist";
1302         return ZEBRA_FAIL;
1303     }
1304     return zebra_end_trans (zh);
1305 }
1306
1307 int zebra_string_norm (ZebraHandle zh, unsigned reg_id,
1308                        const char *input_str, int input_len,
1309                        char *output_str, int output_len)
1310 {
1311     WRBUF wrbuf;
1312     ASSERTZH;
1313     assert(input_str);
1314     assert(output_str);
1315     yaz_log(log_level, "zebra_string_norm ");
1316     zh->errCode = 0;
1317     if (!zh->reg->zebra_maps)
1318         return -1;
1319     wrbuf = zebra_replace(zh->reg->zebra_maps, reg_id, "",
1320                           input_str, input_len);
1321     if (!wrbuf)
1322         return -2;
1323     if (wrbuf_len(wrbuf) >= output_len)
1324         return -3;
1325     if (wrbuf_len(wrbuf))
1326         memcpy (output_str, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
1327     output_str[wrbuf_len(wrbuf)] = '\0';
1328     return wrbuf_len(wrbuf);
1329 }
1330
1331 static void zebra_set_state (ZebraHandle zh, int val, int seqno)
1332 {
1333     char state_fname[256];
1334     char *fname;
1335     long p = getpid();
1336     FILE *f;
1337     ASSERTZH;
1338     yaz_log(log_level, "zebra_set_state v=%d seq=%d", val, seqno);
1339     zh->errCode = 0;
1340
1341     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1342     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1343     f = fopen (fname, "w");
1344
1345     yaz_log (YLOG_DEBUG, "zebra_set_state: %c %d %ld", val, seqno, p);
1346     fprintf (f, "%c %d %ld\n", val, seqno, p);
1347     fclose (f);
1348     xfree(fname);
1349 }
1350
1351 static void zebra_get_state (ZebraHandle zh, char *val, int *seqno)
1352 {
1353     char state_fname[256];
1354     char *fname;
1355     FILE *f;
1356
1357     ASSERTZH;
1358     yaz_log(log_level, "zebra_get_state ");
1359     zh->errCode = 0;
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, "r");
1363     *val = 'o';
1364     *seqno = 0;
1365
1366     if (f)
1367     {
1368         fscanf (f, "%c %d", val, seqno);
1369         fclose (f);
1370     }
1371     xfree(fname);
1372 }
1373
1374 ZEBRA_RES zebra_begin_read (ZebraHandle zh)
1375 {
1376     return zebra_begin_trans(zh, 0);
1377 }
1378
1379 ZEBRA_RES zebra_end_read (ZebraHandle zh)
1380 {
1381     return zebra_end_trans(zh);
1382 }
1383
1384 static void read_res_for_transaction(ZebraHandle zh)
1385 {
1386     const char *group = res_get(zh->res, "group");
1387     const char *v;
1388     /* FIXME - do we still use groups ?? */
1389     
1390     zh->m_group = group;
1391     v = res_get_prefix(zh->res, "followLinks", group, "1");
1392     zh->m_follow_links = atoi(v);
1393
1394     zh->m_record_id = res_get_prefix(zh->res, "recordId", group, 0);
1395     zh->m_record_type = res_get_prefix(zh->res, "recordType", group, 0);
1396
1397     v = res_get_prefix(zh->res, "storeKeys", group, "1");
1398     zh->m_store_keys = atoi(v);
1399
1400     v = res_get_prefix(zh->res, "storeData", group, "1");
1401     zh->m_store_data = atoi(v);
1402
1403     v = res_get_prefix(zh->res, "explainDatabase", group, "0");
1404     zh->m_explain_database = atoi(v);
1405
1406     v = res_get_prefix(zh->res, "openRW", group, "1");
1407     zh->m_flag_rw = atoi(v);
1408
1409     v = res_get_prefix(zh->res, "fileVerboseLimit", group, "100000");
1410     zh->m_file_verbose_limit = atoi(v);
1411 }
1412
1413 ZEBRA_RES zebra_begin_trans(ZebraHandle zh, int rw)
1414 {
1415     ASSERTZH;
1416     zebra_select_default_database(zh);
1417     if (!zh->res)
1418     {
1419         zh->errCode = 2;
1420         zh->errString = "zebra_begin_trans: no database selected";
1421         return ZEBRA_FAIL;
1422     }
1423     ASSERTZHRES;
1424     yaz_log(log_level, "zebra_begin_trans rw=%d",rw);
1425
1426     if (zh->user_perm)
1427     {
1428         if (rw && !strchr(zh->user_perm, 'w'))
1429         {
1430             zh->errCode = 223;
1431             zh->errString = 0;
1432             return ZEBRA_FAIL;
1433         }
1434     }
1435
1436     assert (zh->res);
1437     if (rw)
1438     {
1439         int pass;
1440         int seqno = 0;
1441         char val = '?';
1442         const char *rval = 0;
1443         
1444         (zh->trans_no++);
1445         if (zh->trans_w_no)
1446         {
1447             read_res_for_transaction(zh);
1448             return 0;
1449         }
1450         if (zh->trans_no != 1)
1451         {
1452             zh->errCode = 2;
1453             zh->errString = "zebra_begin_trans: write trans not allowed within read trans";
1454             return ZEBRA_FAIL;
1455         }
1456         if (zh->reg)
1457         {
1458             resultSetInvalidate (zh);
1459             zebra_register_close (zh->service, zh->reg);
1460         }
1461         zh->trans_w_no = zh->trans_no;
1462
1463         zh->errCode = 0;
1464         
1465         zh->records_inserted = 0;
1466         zh->records_updated = 0;
1467         zh->records_deleted = 0;
1468         zh->records_processed = 0;
1469         
1470 #if HAVE_SYS_TIMES_H
1471         times (&zh->tms1);
1472 #endif
1473         /* lock */
1474         if (zh->shadow_enable)
1475             rval = res_get (zh->res, "shadow");
1476         
1477         for (pass = 0; pass < 2; pass++)
1478         {
1479             if (rval)
1480             {
1481                 zebra_lock_r (zh->lock_normal);
1482                 zebra_lock_w (zh->lock_shadow);
1483             }
1484             else
1485             {
1486                 zebra_lock_w (zh->lock_normal);
1487                 zebra_lock_w (zh->lock_shadow);
1488             }
1489             
1490             zebra_get_state (zh, &val, &seqno);
1491             if (val == 'c')
1492             {
1493                 yaz_log (YLOG_WARN, "previous transaction didn't finish commit");
1494                 zebra_unlock (zh->lock_shadow);
1495                 zebra_unlock (zh->lock_normal);
1496                 zebra_commit (zh);
1497                 continue;
1498             }
1499             else if (val == 'd')
1500             {
1501                 if (rval)
1502                 {
1503                     BFiles bfs = bfs_create (res_get (zh->res, "shadow"),
1504                                              zh->path_reg);
1505                     yaz_log (YLOG_WARN, "previous transaction didn't reach commit");
1506                     bf_commitClean (bfs, rval);
1507                     bfs_destroy (bfs);
1508             }
1509                 else
1510                 {
1511                     yaz_log (YLOG_WARN, "your previous transaction didn't finish");
1512                 }
1513             }
1514             break;
1515         }
1516         if (pass == 2)
1517         {
1518             yaz_log (YLOG_FATAL, "zebra_begin_trans couldn't finish commit");
1519             abort();
1520             return ZEBRA_FAIL;
1521         }
1522         zebra_set_state (zh, 'd', seqno);
1523         
1524         zh->reg = zebra_register_open (zh->service, zh->reg_name,
1525                                        1, rval ? 1 : 0, zh->res,
1526                                        zh->path_reg);
1527         if (zh->reg)
1528             zh->reg->seqno = seqno;
1529         else
1530         {
1531             zebra_set_state (zh, 'o', seqno);
1532             
1533             zebra_unlock (zh->lock_shadow);
1534             zebra_unlock (zh->lock_normal);
1535
1536             zh->trans_no--;
1537             zh->trans_w_no = 0;
1538
1539             zh->errCode = 2;
1540             zh->errString = "zebra_begin_trans: cannot open register";
1541             yaz_log(YLOG_FATAL, zh->errString);
1542             return ZEBRA_FAIL;
1543         }
1544     }
1545     else
1546     {
1547         int dirty = 0;
1548         char val;
1549         int seqno;
1550         
1551         (zh->trans_no)++;
1552         
1553         if (zh->trans_no != 1)
1554         {
1555             zebra_flush_reg (zh);
1556             return ZEBRA_OK;
1557         }
1558         zh->errCode = 0;
1559 #if HAVE_SYS_TIMES_H
1560         times (&zh->tms1);
1561 #endif
1562         if (!zh->res)
1563         {
1564             (zh->trans_no)--;
1565             zh->errCode = 109;
1566             return ZEBRA_FAIL;
1567         }
1568         if (!zh->lock_normal || !zh->lock_shadow)
1569         {
1570             (zh->trans_no)--;
1571             zh->errCode = 2;
1572             return ZEBRA_FAIL;
1573         }
1574         zebra_get_state (zh, &val, &seqno);
1575         if (val == 'd')
1576             val = 'o';
1577         
1578         if (!zh->reg)
1579             dirty = 1;
1580         else if (seqno != zh->reg->seqno)
1581         {
1582             yaz_log (YLOG_DEBUG, "reopen seqno cur/old %d/%d",
1583                      seqno, zh->reg->seqno);
1584             dirty = 1;
1585         }
1586         else if (zh->reg->last_val != val)
1587         {
1588             yaz_log (YLOG_DEBUG, "reopen last cur/old %d/%d",
1589                      val, zh->reg->last_val);
1590             dirty = 1;
1591         }
1592         if (!dirty)
1593             return ZEBRA_OK;
1594         
1595         if (val == 'c')
1596             zebra_lock_r (zh->lock_shadow);
1597         else
1598             zebra_lock_r (zh->lock_normal);
1599         
1600         if (zh->reg)
1601         {
1602             resultSetInvalidate (zh);
1603             zebra_register_close (zh->service, zh->reg);
1604         }
1605         zh->reg = zebra_register_open (zh->service, zh->reg_name,
1606                                        0, val == 'c' ? 1 : 0,
1607                                        zh->res, zh->path_reg);
1608         if (!zh->reg)
1609         {
1610             zebra_unlock (zh->lock_normal);
1611             zebra_unlock (zh->lock_shadow);
1612             zh->trans_no--;
1613             zh->errCode = 109;
1614             return ZEBRA_FAIL;
1615         }
1616         zh->reg->last_val = val;
1617         zh->reg->seqno = seqno;
1618     }
1619     read_res_for_transaction(zh);
1620     return ZEBRA_OK;
1621 }
1622
1623 ZEBRA_RES zebra_end_trans (ZebraHandle zh)
1624 {
1625     ZebraTransactionStatus dummy;
1626     ASSERTZH;
1627     yaz_log(log_level, "zebra_end_trans");
1628     return zebra_end_transaction(zh, &dummy);
1629 }
1630
1631 ZEBRA_RES zebra_end_transaction (ZebraHandle zh, ZebraTransactionStatus *status)
1632 {
1633     char val;
1634     int seqno;
1635     const char *rval;
1636
1637     ASSERTZH;
1638     assert(status);
1639     yaz_log(log_level, "zebra_end_transaction");
1640
1641     status->processed = 0;
1642     status->inserted  = 0;
1643     status->updated   = 0;
1644     status->deleted   = 0;
1645     status->utime     = 0;
1646     status->stime     = 0;
1647
1648     if (!zh->res || !zh->reg)
1649     {
1650         zh->errCode = 2;
1651         zh->errString = "zebra_end_trans: no open transaction";
1652         return ZEBRA_FAIL;
1653     }
1654     if (zh->trans_no != zh->trans_w_no)
1655     {
1656         zh->trans_no--;
1657         if (zh->trans_no != 0)
1658             return ZEBRA_OK;
1659
1660         /* release read lock */
1661
1662         zebra_unlock (zh->lock_normal);
1663         zebra_unlock (zh->lock_shadow);
1664     }
1665     else
1666     {   /* release write lock */
1667         zh->trans_no--;
1668         zh->trans_w_no = 0;
1669         
1670         yaz_log (YLOG_DEBUG, "zebra_end_trans");
1671         rval = res_get (zh->res, "shadow");
1672         
1673         zebraExplain_runNumberIncrement (zh->reg->zei, 1);
1674         
1675         zebra_flush_reg (zh);
1676         
1677         resultSetInvalidate (zh);
1678
1679         zebra_register_close (zh->service, zh->reg);
1680         zh->reg = 0;
1681         
1682         yaz_log (YLOG_LOG, "Records: "ZINT_FORMAT" i/u/d "
1683                         ZINT_FORMAT"/"ZINT_FORMAT"/"ZINT_FORMAT, 
1684                  zh->records_processed, zh->records_inserted,
1685                  zh->records_updated, zh->records_deleted);
1686         
1687         status->processed = (int) zh->records_processed;
1688         status->inserted = (int) zh->records_inserted;
1689         status->updated = (int) zh->records_updated;
1690         status->deleted = (int) zh->records_deleted;
1691         
1692         zebra_get_state (zh, &val, &seqno);
1693         if (val != 'd')
1694         {
1695             BFiles bfs = bfs_create (rval, zh->path_reg);
1696             yaz_log (YLOG_DEBUG, "deleting shadow val=%c", val);
1697             bf_commitClean (bfs, rval);
1698             bfs_destroy (bfs);
1699         }
1700         if (!rval)
1701             seqno++;
1702         zebra_set_state (zh, 'o', seqno);
1703         
1704         zebra_unlock (zh->lock_shadow);
1705         zebra_unlock (zh->lock_normal);
1706         
1707     }
1708 #if HAVE_SYS_TIMES_H
1709     times (&zh->tms2);
1710     yaz_log (log_level, "user/system: %ld/%ld",
1711           (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1712           (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1713     
1714     status->utime = (long) (zh->tms2.tms_utime - zh->tms1.tms_utime);
1715     status->stime = (long) (zh->tms2.tms_stime - zh->tms1.tms_stime);
1716 #endif
1717     return ZEBRA_OK;
1718 }
1719
1720 int zebra_repository_update (ZebraHandle zh, const char *path)
1721 {
1722     ASSERTZH;
1723     assert(path);
1724     zh->errCode = 0;
1725     yaz_log (log_level, "updating %s", path);
1726     repositoryUpdate (zh, path);
1727     return zh->errCode;
1728 }
1729
1730 int zebra_repository_delete (ZebraHandle zh, const char *path)
1731 {
1732     ASSERTZH;
1733     assert(path);
1734     zh->errCode = 0;
1735     yaz_log (log_level, "deleting %s", path);
1736     repositoryDelete (zh, path);
1737     return zh->errCode;
1738 }
1739
1740 int zebra_repository_show (ZebraHandle zh, const char *path)
1741 {
1742     ASSERTZH;
1743     assert(path);
1744     yaz_log(log_level, "zebra_repository_show");
1745     zh->errCode = 0;
1746     repositoryShow (zh, path);
1747     return zh->errCode;
1748 }
1749
1750 static int zebra_commit_ex (ZebraHandle zh, int clean_only)
1751 {
1752     int seqno;
1753     char val;
1754     const char *rval;
1755     BFiles bfs;
1756     ASSERTZH;
1757     zh->errCode = 0;
1758
1759     zebra_select_default_database(zh);
1760     if (!zh->res)
1761     {
1762         zh->errCode = 109;
1763         return -1;
1764     }
1765     rval = res_get (zh->res, "shadow");    
1766     if (!rval)
1767     {
1768         yaz_log (YLOG_WARN, "Cannot perform commit - No shadow area defined");
1769         return 0;
1770     }
1771
1772     zebra_lock_w (zh->lock_normal);
1773     zebra_lock_r (zh->lock_shadow);
1774
1775     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1776
1777     zebra_get_state (zh, &val, &seqno);
1778
1779     if (rval && *rval)
1780         bf_cache (bfs, rval);
1781     if (bf_commitExists (bfs))
1782     {
1783         if (clean_only)
1784             zebra_set_state (zh, 'd', seqno);
1785         else
1786         {
1787             zebra_set_state (zh, 'c', seqno);
1788             
1789             yaz_log (YLOG_DEBUG, "commit start");
1790             bf_commitExec (bfs);
1791 #ifndef WIN32
1792             sync ();
1793 #endif
1794         }
1795         yaz_log (YLOG_DEBUG, "commit clean");
1796         bf_commitClean (bfs, rval);
1797         seqno++;
1798         zebra_set_state (zh, 'o', seqno);
1799     }
1800     else
1801     {
1802         yaz_log (log_level, "nothing to commit");
1803     }
1804     bfs_destroy (bfs);
1805
1806     zebra_unlock (zh->lock_shadow);
1807     zebra_unlock (zh->lock_normal);
1808     return 0;
1809 }
1810
1811 ZEBRA_RES zebra_clean (ZebraHandle zh)
1812 {
1813     ASSERTZH;
1814     yaz_log(log_level, "zebra_clean");
1815     return zebra_commit_ex(zh, 1);
1816 }
1817
1818 ZEBRA_RES zebra_commit (ZebraHandle zh)
1819 {
1820     ASSERTZH;
1821     yaz_log(log_level, "zebra_commit");
1822     return zebra_commit_ex(zh, 0);
1823 }
1824
1825 ZEBRA_RES zebra_init (ZebraHandle zh)
1826 {
1827     const char *rval;
1828     BFiles bfs = 0;
1829     ASSERTZH;
1830     yaz_log(log_level, "zebra_init");
1831     zh->errCode = 0;
1832
1833     zebra_select_default_database(zh);
1834     if (!zh->res)
1835     {
1836         zh->errCode = 109;
1837         return ZEBRA_FAIL;
1838     }
1839     rval = res_get (zh->res, "shadow");
1840
1841     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1842     if (!bfs)
1843         return ZEBRA_FAIL;
1844     if (rval && *rval)
1845         bf_cache (bfs, rval);
1846     
1847     bf_reset (bfs);
1848     bfs_destroy (bfs);
1849     zebra_set_state (zh, 'o', 0);
1850     return ZEBRA_OK;
1851 }
1852
1853 int zebra_compact (ZebraHandle zh)
1854 {
1855     BFiles bfs;
1856     ASSERTZH;
1857     yaz_log(log_level, "zebra_compact");
1858     zh->errCode = 0;
1859     if (!zh->res)
1860     {
1861         zh->errCode = 109;
1862         return -1;
1863     }
1864     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1865     inv_compact (bfs);
1866     bfs_destroy (bfs);
1867     return 0;
1868 }
1869
1870 int zebra_result (ZebraHandle zh, int *code, char **addinfo)
1871 {
1872     ASSERTZH;
1873     yaz_log(log_level, "zebra_result");
1874     *code = zh->errCode;
1875     *addinfo = zh->errString;
1876     return 0;
1877 }
1878
1879 void zebra_shadow_enable (ZebraHandle zh, int value)
1880 {
1881     ASSERTZH;
1882     yaz_log(log_level, "zebra_shadow_enable");
1883     zh->errCode = 0;
1884     zh->shadow_enable = value;
1885 }
1886
1887 ZEBRA_RES zebra_octet_term_encoding(ZebraHandle zh, const char *encoding)
1888 {
1889     ASSERTZH;
1890     assert(encoding);
1891     yaz_log(log_level, "zebra_octet_term_encoding");
1892     zh->errCode = 0;
1893
1894     if (zh->iconv_to_utf8 != 0)
1895         yaz_iconv_close(zh->iconv_to_utf8);
1896     if (zh->iconv_from_utf8 != 0)
1897         yaz_iconv_close(zh->iconv_from_utf8);
1898     
1899     zh->iconv_to_utf8 =
1900         yaz_iconv_open ("UTF-8", encoding);
1901     if (zh->iconv_to_utf8 == 0)
1902         yaz_log (YLOG_WARN, "iconv: %s to UTF-8 unsupported", encoding);
1903     zh->iconv_from_utf8 =
1904         yaz_iconv_open (encoding, "UTF-8");
1905     if (zh->iconv_to_utf8 == 0)
1906         yaz_log (YLOG_WARN, "iconv: UTF-8 to %s unsupported", encoding);
1907
1908     return ZEBRA_OK;
1909 }
1910
1911 ZEBRA_RES zebra_record_encoding (ZebraHandle zh, const char *encoding)
1912 {
1913     ASSERTZH;
1914     yaz_log(log_level, "zebra_record_encoding");
1915     zh->errCode = 0;
1916     xfree(zh->record_encoding);
1917     zh->record_encoding = 0;
1918     if (encoding)
1919         zh->record_encoding = xstrdup (encoding);
1920     return ZEBRA_OK;
1921 }
1922
1923 void zebra_set_resource(ZebraHandle zh, const char *name, const char *value)
1924 {
1925     ASSERTZH;
1926     assert(name);
1927     assert(value);
1928     yaz_log(log_level, "zebra_set_resource %s:%s",name,value);
1929     zh->errCode = 0;
1930     res_set(zh->res, name, value);
1931 }
1932
1933 const char *zebra_get_resource(ZebraHandle zh,
1934                                const char *name, const char *defaultvalue)
1935 {
1936     const char *v;
1937     ASSERTZH;
1938     assert(name);
1939     assert(defaultvalue);
1940     v= res_get_def( zh->res, name, (char *)defaultvalue);
1941     zh->errCode = 0;
1942     yaz_log(log_level, "zebra_get_resource %s:%s",name,v);
1943     return v;
1944 }
1945
1946 /* moved from zebra_api_ext.c by pop */
1947 /* FIXME: Should this really be public??? -Heikki */
1948
1949 int zebra_trans_no (ZebraHandle zh)
1950 {
1951     ASSERTZH;
1952     yaz_log(log_level, "zebra_trans_no");
1953     return zh->trans_no;
1954 }
1955
1956 int zebra_get_shadow_enable (ZebraHandle zh)
1957 {
1958     ASSERTZH;
1959     yaz_log(log_level, "zebra_get_shadow_enable");
1960     return (zh->shadow_enable);
1961 }
1962
1963 void zebra_set_shadow_enable (ZebraHandle zh, int value)
1964 {
1965     ASSERTZH;
1966     yaz_log(log_level, "zebra_set_shadow_enable %d",value);
1967     zh->shadow_enable = value;
1968 }
1969
1970 /* Used by Perl API.. Added the record buffer dup to zebra_records_retrieve
1971    so that it's identicical to the original api_records_retrieve */
1972 void api_records_retrieve (ZebraHandle zh, ODR stream,
1973                            const char *setname, Z_RecordComposition *comp,
1974                            oid_value input_format, int num_recs,
1975                            ZebraRetrievalRecord *recs)
1976 {
1977     zebra_records_retrieve(zh, stream, setname, comp, input_format,
1978                            num_recs, recs);
1979 }
1980
1981 /* ---------------------------------------------------------------------------
1982   Record insert(=update), delete 
1983
1984   If sysno is provided, then it's used to identify the record.
1985   If not, and match_criteria is provided, then sysno is guessed
1986   If not, and a record is provided, then sysno is got from there
1987 NOTE: Now returns 0 at success and updates sysno, which is an int*
1988   20-jun-2003 Heikki
1989 */
1990
1991 int zebra_add_record(ZebraHandle zh,
1992                      const char *buf, int buf_size)
1993 {
1994     SYSNO sysno = 0;
1995     return zebra_update_record(zh, 0, &sysno, 0, 0, buf, buf_size, 0);
1996 }
1997
1998 ZEBRA_RES zebra_insert_record (ZebraHandle zh, 
1999                                const char *recordType,
2000                                SYSNO *sysno, const char *match,
2001                                const char *fname,
2002                                const char *buf, int buf_size, int force_update)
2003 {
2004     ZEBRA_RES res;
2005     ASSERTZH;
2006     assert(sysno);
2007     assert(buf);
2008     yaz_log(log_level, "zebra_insert_record sysno=" ZINT_FORMAT, *sysno);
2009
2010     if (buf_size < 1)
2011         buf_size = strlen(buf);
2012
2013     if (zebra_begin_trans(zh, 1) == ZEBRA_FAIL)
2014         return ZEBRA_FAIL;
2015     res = buffer_extract_record (zh, buf, buf_size, 
2016                                  0, /* delete_flag  */
2017                                  0, /* test_mode */
2018                                  recordType,
2019                                  sysno,   
2020                                  match, fname,
2021                                  0, 
2022                                  0); /* allow_update */
2023     zebra_end_trans(zh); 
2024     return res; 
2025 }
2026
2027 ZEBRA_RES zebra_update_record (ZebraHandle zh, 
2028                                const char *recordType,
2029                                SYSNO* sysno, const char *match,
2030                                const char *fname,
2031                                const char *buf, int buf_size,
2032                                int force_update)
2033 {
2034     ZEBRA_RES res;
2035     ASSERTZH;
2036     assert(sysno);
2037     assert(buf);
2038
2039     yaz_log(log_level, "zebra_update_record sysno=" ZINT_FORMAT, *sysno);
2040
2041     if (buf_size < 1) buf_size = strlen(buf);
2042
2043     if (zebra_begin_trans(zh, 1) == ZEBRA_FAIL)
2044         return ZEBRA_FAIL;
2045     res = buffer_extract_record (zh, buf, buf_size, 
2046                                  0, /* delete_flag */
2047                                  0, /* test_mode */
2048                                  recordType,
2049                                  sysno,   
2050                                  match, fname,
2051                                  force_update, 
2052                                  1); /* allow_update */
2053     zebra_end_trans(zh); 
2054     return res; 
2055 }
2056
2057 ZEBRA_RES zebra_delete_record (ZebraHandle zh, 
2058                                const char *recordType,
2059                                SYSNO *sysno, const char *match,
2060                                const char *fname,
2061                                const char *buf, int buf_size,
2062                                int force_update) 
2063 {
2064     ZEBRA_RES res;
2065     ASSERTZH;
2066     assert(sysno);
2067     assert(buf);
2068     yaz_log(log_level, "zebra_delete_record sysno=" ZINT_FORMAT, *sysno);
2069
2070     if (buf_size < 1) buf_size = strlen(buf);
2071
2072     if (zebra_begin_trans(zh, 1) == ZEBRA_FAIL)
2073         return ZEBRA_FAIL;
2074     res = buffer_extract_record (zh, buf, buf_size,
2075                                  1, /* delete_flag */
2076                                  0, /* test_mode */
2077                                  recordType,
2078                                  sysno,
2079                                  match,fname,
2080                                  force_update,
2081                                  1); /* allow_update */
2082     zebra_end_trans(zh);
2083     return res;
2084 }
2085
2086 /* ---------------------------------------------------------------------------
2087   Searching 
2088 */
2089
2090 ZEBRA_RES zebra_search_PQF (ZebraHandle zh, const char *pqf_query,
2091                             const char *setname, zint *numhits)
2092 {
2093     zint hits = 0;
2094     ZEBRA_RES res = ZEBRA_OK;
2095     Z_RPNQuery *query;
2096     ODR odr = odr_createmem(ODR_ENCODE);
2097     ASSERTZH;
2098     assert(pqf_query);
2099     assert(setname);
2100
2101     yaz_log(log_level, "zebra_search_PQF s=%s q=%s", setname, pqf_query);
2102     
2103     query = p_query_rpn (odr, PROTO_Z3950, pqf_query);
2104     
2105     if (!query)
2106     {
2107         yaz_log (YLOG_WARN, "bad query %s\n", pqf_query);
2108         res = ZEBRA_FAIL;
2109     }
2110     else
2111         res = zebra_search_RPN (zh, odr, query, setname, &hits);
2112     
2113     odr_destroy(odr);
2114
2115     yaz_log(log_level, "Hits: " ZINT_FORMAT, hits);
2116
2117     if (numhits)
2118         *numhits = hits;
2119
2120     return res;
2121 }
2122
2123 /* ---------------------------------------------------------------------------
2124   Sort - a simplified interface, with optional read locks.
2125 */
2126 int zebra_sort_by_specstr (ZebraHandle zh, ODR stream,
2127                            const char *sort_spec,
2128                            const char *output_setname,
2129                            const char **input_setnames) 
2130 {
2131     int num_input_setnames = 0;
2132     int sort_status = 0;
2133     Z_SortKeySpecList *sort_sequence;
2134     ASSERTZH;
2135     assert(stream);
2136     assert(sort_spec);
2137     assert(output_setname);
2138     assert(input_setnames);
2139     sort_sequence = yaz_sort_spec (stream, sort_spec);
2140     yaz_log(log_level, "sort (FIXME) ");
2141     if (!sort_sequence)
2142     {
2143         yaz_log(YLOG_WARN, "invalid sort specs '%s'", sort_spec);
2144         zh->errCode = 207;
2145         return -1;
2146     }
2147     
2148     /* we can do this, since the perl typemap code for char** will 
2149        put a NULL at the end of list */
2150     while (input_setnames[num_input_setnames]) num_input_setnames++;
2151
2152     if (zebra_begin_read (zh))
2153         return -1;
2154     
2155     resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
2156                    output_setname, sort_sequence, &sort_status);
2157     
2158     zebra_end_read(zh);
2159     return sort_status;
2160 }
2161
2162 struct BFiles_struct *zebra_get_bfs(ZebraHandle zh)
2163 {
2164     if (zh && zh->reg)
2165         return zh->reg->bfs;
2166     return 0;
2167 }