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