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