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