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