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