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