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