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