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