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