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