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