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