Generic snippet support. Unlike previous versions of snippet
[idzebra-moved-to-github.git] / index / zebraapi.c
1 /* $Id: zebraapi.c,v 1.257 2007-08-21 11:06:47 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, setname,
1148                                        poset[i].sysno, poset[i].score,
1149                                        hit_snippet,
1150                                        stream, input_format, comp,
1151                                        &recs[i].format, &buf, &len,
1152                                        &recs[i].base, &recs[i].errString);
1153                 
1154                 recs[i].len = len;
1155                 if (len > 0)
1156                 {
1157                     recs[i].buf = (char*) odr_malloc(stream, len);
1158                     memcpy(recs[i].buf, buf, len);
1159                 }
1160                 else
1161                     recs[i].buf = buf;
1162                 recs[i].score = poset[i].score;
1163                 recs[i].sysno = poset[i].sysno;
1164                 zebra_snippets_destroy(hit_snippet);
1165             }
1166             else
1167             {
1168                 /* only need to set it once */
1169                 if (pos_array[i] < zh->approx_limit && ret == ZEBRA_OK)
1170                 {
1171                     zebra_setError_zint(zh,
1172                                         YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE,
1173                                         pos_array[i]);
1174                     ret = ZEBRA_FAIL;
1175                     break;
1176                 }
1177                 recs[i].buf = 0;  /* no record and no error issued */
1178                 recs[i].len = 0;
1179                 recs[i].errCode = 0;
1180                 recs[i].format = 0;
1181                 recs[i].sysno = 0;
1182             }
1183         }
1184         zebra_meta_records_destroy(zh, poset, num_recs);
1185     }
1186     zebra_end_read (zh);
1187     xfree(pos_array);
1188     return ret;
1189 }
1190
1191 ZEBRA_RES zebra_scan_PQF(ZebraHandle zh, ODR stream, const char *query,
1192                          int *position,
1193                          int *num_entries, ZebraScanEntry **entries,
1194                          int *is_partial,
1195                          const char *setname)
1196 {
1197     YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
1198     Z_AttributesPlusTerm *zapt;
1199     Odr_oid *attributeSet;
1200     ZEBRA_RES res;
1201     
1202     if (!(zapt = yaz_pqf_scan(pqf_parser, stream, &attributeSet, query)))
1203     {
1204         res = ZEBRA_FAIL;
1205         zh->errCode = YAZ_BIB1_SCAN_MALFORMED_SCAN;
1206     }
1207     else
1208     {
1209         res = zebra_scan(zh, stream, zapt, yaz_oid_attset_bib_1,
1210                          position, num_entries, entries, is_partial,
1211                          setname);
1212     }
1213     yaz_pqf_destroy (pqf_parser);
1214     return res;
1215 }
1216
1217 ZEBRA_RES zebra_scan(ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
1218                      const Odr_oid *attributeset,
1219                      int *position,
1220                      int *num_entries, ZebraScanEntry **entries,
1221                      int *is_partial,
1222                      const char *setname)
1223 {
1224     ZEBRA_RES res;
1225     RSET limit_rset = 0;
1226
1227     ZEBRA_CHECK_HANDLE(zh);
1228
1229     assert(stream);
1230     assert(zapt);
1231     assert(position);
1232     assert(num_entries);
1233     assert(is_partial);
1234     assert(entries);
1235     yaz_log(log_level, "zebra_scan");
1236
1237     if (zebra_begin_read (zh) == ZEBRA_FAIL)
1238     {
1239         *entries = 0;
1240         *num_entries = 0;
1241         return ZEBRA_FAIL;
1242     }
1243     if (setname)
1244     {
1245         limit_rset = resultSetRef(zh, setname);
1246         if (!limit_rset)
1247         {
1248             zebra_setError(zh, 
1249                            YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST,
1250                            setname);
1251             zebra_end_read (zh);
1252             return ZEBRA_FAIL;
1253         }
1254     }
1255     res = rpn_scan(zh, stream, zapt, attributeset,
1256                    zh->num_basenames, zh->basenames, position,
1257                    num_entries, entries, is_partial, limit_rset);
1258     zebra_end_read(zh);
1259     return res;
1260 }
1261
1262 ZEBRA_RES zebra_sort (ZebraHandle zh, ODR stream,
1263                       int num_input_setnames, const char **input_setnames,
1264                       const char *output_setname,
1265                       Z_SortKeySpecList *sort_sequence,
1266                       int *sort_status)
1267 {
1268     ZEBRA_RES res;
1269     ZEBRA_CHECK_HANDLE(zh);
1270     assert(stream);
1271     assert(num_input_setnames>0);
1272     assert(input_setnames);
1273     assert(sort_sequence);
1274     assert(sort_status);
1275     yaz_log(log_level, "zebra_sort");
1276
1277     if (zebra_begin_read(zh) == ZEBRA_FAIL)
1278         return ZEBRA_FAIL;
1279     res = resultSetSort(zh, stream->mem, num_input_setnames, input_setnames,
1280                         output_setname, sort_sequence, sort_status);
1281     zebra_end_read(zh);
1282     return res;
1283 }
1284
1285 int zebra_deleteResultSet(ZebraHandle zh, int function,
1286                           int num_setnames, char **setnames,
1287                           int *statuses)
1288 {
1289     int i, status;
1290     ASSERTZH;
1291     assert(statuses);
1292     yaz_log(log_level, "zebra_deleteResultSet n=%d",num_setnames);
1293
1294     if (zebra_begin_read(zh))
1295         return Z_DeleteStatus_systemProblemAtTarget;
1296     switch (function)
1297     {
1298     case Z_DeleteResultSetRequest_list:
1299         assert(num_setnames>0);
1300         assert(setnames);
1301         resultSetDestroy (zh, num_setnames, setnames, statuses);
1302         break;
1303     case Z_DeleteResultSetRequest_all:
1304         resultSetDestroy (zh, -1, 0, statuses);
1305         break;
1306     }
1307     zebra_end_read (zh);
1308     status = Z_DeleteStatus_success;
1309     for (i = 0; i<num_setnames; i++)
1310         if (statuses[i] == Z_DeleteStatus_resultSetDidNotExist)
1311             status = statuses[i];
1312     return status;
1313 }
1314
1315 int zebra_errCode (ZebraHandle zh)
1316 {
1317     if (zh)
1318     {
1319         yaz_log(log_level, "zebra_errCode: %d",zh->errCode);
1320         return zh->errCode;
1321     }
1322     yaz_log(log_level, "zebra_errCode: o");
1323     return 0; 
1324 }
1325
1326 const char *zebra_errString (ZebraHandle zh)
1327 {
1328     const char *e = 0;
1329     if (zh)
1330         e= diagbib1_str (zh->errCode);
1331     yaz_log(log_level, "zebra_errString: %s",e);
1332     return e;
1333 }
1334
1335 char *zebra_errAdd (ZebraHandle zh)
1336 {
1337     char *a = 0;
1338     if (zh)
1339         a= zh->errString;
1340     yaz_log(log_level, "zebra_errAdd: %s",a);
1341     return a;
1342 }
1343
1344 ZEBRA_RES zebra_auth (ZebraHandle zh, const char *user, const char *pass)
1345 {
1346     const char *p;
1347     const char *astring;
1348     char u[40];
1349     ZebraService zs;
1350
1351     ZEBRA_CHECK_HANDLE(zh);
1352
1353     zs = zh->service;
1354     
1355     sprintf(u, "perm.%.30s", user ? user : "anonymous");
1356     p = res_get(zs->global_res, u);
1357     xfree(zh->user_perm);
1358     zh->user_perm = xstrdup(p ? p : "r");
1359
1360     /* Determine database access list */
1361     astring = res_get(zs->dbaccess, user ? user : "anonymous");
1362     if (astring)
1363         zh->dbaccesslist = xstrdup(astring);
1364     else
1365         zh->dbaccesslist = 0;
1366
1367     /* users that don't require a password .. */
1368     if (zh->user_perm && strchr(zh->user_perm, 'a'))
1369         return ZEBRA_OK;
1370     
1371     if (!zs->passwd_db || !passwd_db_auth (zs->passwd_db, user, pass))
1372         return ZEBRA_OK;
1373     return ZEBRA_FAIL;
1374 }
1375
1376 ZEBRA_RES zebra_admin_import_begin (ZebraHandle zh, const char *database,
1377                                const char *record_type)
1378 {
1379     yaz_log(log_level, "zebra_admin_import_begin db=%s rt=%s", 
1380                      database, record_type);
1381     if (zebra_select_database(zh, database) == ZEBRA_FAIL)
1382         return ZEBRA_FAIL;
1383     return zebra_begin_trans(zh, 1);
1384 }
1385
1386 ZEBRA_RES zebra_admin_import_end (ZebraHandle zh)
1387 {
1388     ZEBRA_CHECK_HANDLE(zh);
1389     yaz_log(log_level, "zebra_admin_import_end");
1390     return zebra_end_trans(zh);
1391 }
1392
1393 ZEBRA_RES zebra_admin_import_segment (ZebraHandle zh, Z_Segment *segment)
1394 {
1395     ZEBRA_RES res = ZEBRA_OK;
1396     zint sysno;
1397     int i;
1398     ZEBRA_CHECK_HANDLE(zh);
1399     yaz_log(log_level, "zebra_admin_import_segment");
1400
1401     for (i = 0; i<segment->num_segmentRecords; i++)
1402     {
1403         Z_NamePlusRecord *npr = segment->segmentRecords[i];
1404
1405         if (npr->which == Z_NamePlusRecord_intermediateFragment)
1406         {
1407             Z_FragmentSyntax *fragment = npr->u.intermediateFragment;
1408             if (fragment->which == Z_FragmentSyntax_notExternallyTagged)
1409             {
1410                 Odr_oct *oct = fragment->u.notExternallyTagged;
1411                 sysno = 0;
1412                 
1413                 if (zebra_update_record(
1414                         zh, 
1415                         action_update,
1416                         0, /* record Type */
1417                         &sysno,
1418                         0, /* match */
1419                         0, /* fname */
1420                         (const char *) oct->buf, oct->len) == ZEBRA_FAIL)
1421                     res = ZEBRA_FAIL;
1422             }
1423         }
1424     }
1425     return res;
1426 }
1427
1428 int delete_w_handle(const char *info, void *handle)
1429 {
1430     ZebraHandle zh = (ZebraHandle) handle;
1431     ISAM_P pos;
1432     ASSERTZH;
1433
1434     if (*info == sizeof(pos))
1435     {
1436         memcpy (&pos, info+1, sizeof(pos));
1437         isamb_unlink(zh->reg->isamb, pos);
1438     }
1439     return 0;
1440 }
1441
1442 static int delete_SU_handle(void *handle, int ord)
1443 {
1444     ZebraHandle zh = (ZebraHandle) handle;
1445     char ord_buf[20];
1446     int ord_len;
1447
1448     ord_len = key_SU_encode (ord, ord_buf);
1449     ord_buf[ord_len] = '\0';
1450
1451     assert (zh->reg->isamb);
1452     dict_delete_subtree(zh->reg->dict, ord_buf,
1453                         zh, delete_w_handle);
1454     return 0;
1455 }
1456
1457 ZEBRA_RES zebra_drop_database(ZebraHandle zh, const char *db)
1458 {
1459     ZEBRA_RES ret = ZEBRA_OK;
1460
1461     yaz_log(log_level, "zebra_drop_database %s", db);
1462     ZEBRA_CHECK_HANDLE(zh);
1463
1464     if (zebra_select_database (zh, db) == ZEBRA_FAIL)
1465         return ZEBRA_FAIL;
1466     if (zebra_begin_trans (zh, 1) == ZEBRA_FAIL)
1467         return ZEBRA_FAIL;
1468     if (zh->reg->isamb)
1469     {
1470         int db_ord;
1471         if (zebraExplain_curDatabase (zh->reg->zei, db))
1472         {
1473             zebra_setError(zh, YAZ_BIB1_DATABASE_DOES_NOT_EXIST, db);
1474             ret = ZEBRA_FAIL;
1475         }
1476         else
1477         {
1478             db_ord = zebraExplain_get_database_ord(zh->reg->zei);
1479             dict_delete_subtree_ord(zh->reg->matchDict, db_ord,
1480                                     0 /* handle */, 0 /* func */);
1481             zebraExplain_trav_ord(zh->reg->zei, zh, delete_SU_handle);
1482             zebraExplain_removeDatabase(zh->reg->zei, zh);
1483             zebra_remove_file_match(zh);
1484         }
1485     }
1486     else
1487     {
1488         yaz_log(YLOG_WARN, "drop database only supported for isam:b");
1489         zebra_setError(zh, YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED,
1490                        "drop database only supported for isam:b");
1491         ret = ZEBRA_FAIL;
1492     }
1493     if (zebra_end_trans (zh) != ZEBRA_OK)
1494     {
1495         yaz_log(YLOG_WARN, "zebra_end_trans failed");
1496         ret = ZEBRA_FAIL;
1497     }
1498     return ret;
1499 }
1500
1501 ZEBRA_RES zebra_create_database (ZebraHandle zh, const char *db)
1502 {
1503     yaz_log(log_level, "zebra_create_database %s", db);
1504     ZEBRA_CHECK_HANDLE(zh);
1505     assert(db);
1506
1507     if (zebra_select_database (zh, db) == ZEBRA_FAIL)
1508         return ZEBRA_FAIL;
1509     if (zebra_begin_trans (zh, 1))
1510         return ZEBRA_FAIL;
1511
1512     /* announce database */
1513     if (zebraExplain_newDatabase (zh->reg->zei, db, 0 
1514                                   /* explainDatabase */))
1515     {
1516         if (zebra_end_trans (zh) != ZEBRA_OK)
1517         {
1518             yaz_log(YLOG_WARN, "zebra_end_trans failed");
1519         }
1520         zebra_setError(zh, YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED, db);
1521         return ZEBRA_FAIL;
1522     }
1523     return zebra_end_trans (zh);
1524 }
1525
1526 int zebra_string_norm(ZebraHandle zh, unsigned reg_id,
1527                       const char *input_str, int input_len,
1528                       char *output_str, int output_len)
1529 {
1530     WRBUF wrbuf;
1531     ASSERTZH;
1532     assert(input_str);
1533     assert(output_str);
1534     yaz_log(log_level, "zebra_string_norm ");
1535
1536     if (!zh->reg->zebra_maps)
1537         return -1;
1538     wrbuf = zebra_replace(zh->reg->zebra_maps, reg_id, "",
1539                           input_str, input_len);
1540     if (!wrbuf)
1541         return -2;
1542     if (wrbuf_len(wrbuf) >= output_len)
1543         return -3;
1544     if (wrbuf_len(wrbuf))
1545         memcpy (output_str, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
1546     output_str[wrbuf_len(wrbuf)] = '\0';
1547     return wrbuf_len(wrbuf);
1548 }
1549
1550 /** \brief set register state (state*.LCK)
1551     \param zh Zebra handle
1552     \param val state
1553     \param seqno sequence number
1554     
1555     val is one of:
1556     d=writing to shadow(shadow enabled); writing to register (shadow disabled)
1557     o=reading only
1558     c=commit (writing to register, reading from shadow, shadow mode only)
1559 */
1560 static void zebra_set_state (ZebraHandle zh, int val, int seqno)
1561 {
1562     char state_fname[256];
1563     char *fname;
1564     long p = getpid();
1565     FILE *f;
1566     ASSERTZH;
1567     yaz_log(log_level, "zebra_set_state v=%d seq=%d", val, seqno);
1568
1569     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1570     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1571     f = fopen (fname, "w");
1572
1573     yaz_log (YLOG_DEBUG, "zebra_set_state: %c %d %ld", val, seqno, p);
1574     fprintf (f, "%c %d %ld\n", val, seqno, p);
1575     fclose (f);
1576     xfree(fname);
1577 }
1578
1579 static void zebra_get_state (ZebraHandle zh, char *val, int *seqno)
1580 {
1581     char state_fname[256];
1582     char *fname;
1583     FILE *f;
1584
1585     ASSERTZH;
1586     yaz_log(log_level, "zebra_get_state ");
1587
1588     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1589     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1590     f = fopen (fname, "r");
1591     *val = 'o';
1592     *seqno = 0;
1593
1594     if (f)
1595     {
1596         fscanf (f, "%c %d", val, seqno);
1597         fclose (f);
1598     }
1599     xfree(fname);
1600 }
1601
1602 ZEBRA_RES zebra_begin_read (ZebraHandle zh)
1603 {
1604     return zebra_begin_trans(zh, 0);
1605 }
1606
1607 ZEBRA_RES zebra_end_read (ZebraHandle zh)
1608 {
1609     return zebra_end_trans(zh);
1610 }
1611
1612 static void read_res_for_transaction(ZebraHandle zh)
1613 {
1614     const char *group = res_get(zh->res, "group");
1615     const char *v;
1616     /* FIXME - do we still use groups ?? */
1617     
1618     zh->m_group = group;
1619     v = res_get_prefix(zh->res, "followLinks", group, "1");
1620     zh->m_follow_links = atoi(v);
1621
1622     zh->m_record_id = res_get_prefix(zh->res, "recordId", group, 0);
1623     zh->m_record_type = res_get_prefix(zh->res, "recordType", group, 0);
1624
1625     v = res_get_prefix(zh->res, "storeKeys", group, "1");
1626     zh->m_store_keys = atoi(v);
1627
1628     v = res_get_prefix(zh->res, "storeData", group, "1");
1629     zh->m_store_data = atoi(v);
1630
1631     v = res_get_prefix(zh->res, "explainDatabase", group, "0");
1632     zh->m_explain_database = atoi(v);
1633
1634     v = res_get_prefix(zh->res, "openRW", group, "1");
1635     zh->m_flag_rw = atoi(v);
1636
1637     v = res_get_prefix(zh->res, "fileVerboseLimit", group, "1000");
1638     zh->m_file_verbose_limit = atoi(v);
1639 }
1640
1641 ZEBRA_RES zebra_begin_trans(ZebraHandle zh, int rw)
1642 {
1643     ZEBRA_CHECK_HANDLE(zh);
1644     zebra_select_default_database(zh);
1645     if (!zh->res)
1646     {
1647         zebra_setError(zh, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
1648                        "zebra_begin_trans: no database selected");
1649         return ZEBRA_FAIL;
1650     }
1651     ASSERTZHRES;
1652     yaz_log(log_level, "zebra_begin_trans rw=%d",rw);
1653
1654     if (zh->user_perm)
1655     {
1656         if (rw && !strchr(zh->user_perm, 'w'))
1657         {
1658             zebra_setError(
1659                 zh,
1660                 YAZ_BIB1_ES_PERMISSION_DENIED_ON_ES_CANNOT_MODIFY_OR_DELETE,
1661                 0);
1662             return ZEBRA_FAIL;
1663         }
1664     }
1665
1666     assert (zh->res);
1667     if (rw)
1668     {
1669         int seqno = 0;
1670         char val = '?';
1671         const char *rval = 0;
1672         
1673         (zh->trans_no++);
1674         if (zh->trans_w_no)
1675         {
1676             read_res_for_transaction(zh);
1677             return 0;
1678         }
1679         if (zh->trans_no != 1)
1680         {
1681             zebra_setError(zh, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
1682                            "zebra_begin_trans: no write trans within read");
1683             return ZEBRA_FAIL;
1684         }
1685         if (zh->reg)
1686         {
1687             resultSetInvalidate (zh);
1688             zebra_register_close(zh->service, zh->reg);
1689         }
1690         zh->trans_w_no = zh->trans_no;
1691
1692         zh->records_inserted = 0;
1693         zh->records_updated = 0;
1694         zh->records_deleted = 0;
1695         zh->records_processed = 0;
1696         zh->records_skipped = 0;
1697         
1698 #if HAVE_SYS_TIMES_H
1699         times (&zh->tms1);
1700 #endif
1701         /* lock */
1702         if (zh->shadow_enable)
1703             rval = res_get (zh->res, "shadow");
1704         
1705         if (rval)
1706         {
1707             zebra_lock_r(zh->lock_normal);
1708             zebra_lock_w(zh->lock_shadow);
1709         }
1710         else
1711         {
1712             zebra_lock_w(zh->lock_normal);
1713             zebra_lock_w(zh->lock_shadow);
1714         }
1715         zebra_get_state (zh, &val, &seqno);
1716         if (val != 'o')
1717         {
1718             /* either we didn't finish commit or shadow is dirty */
1719             if (!rval)
1720             {
1721                 yaz_log(YLOG_WARN, "previous transaction did not finish "
1722                         "(shadow disabled)");
1723             }
1724             zebra_unlock (zh->lock_shadow);
1725             zebra_unlock (zh->lock_normal);
1726             if (zebra_commit (zh))
1727             {
1728                 zh->trans_no--;
1729                 zh->trans_w_no = 0;
1730                 return ZEBRA_FAIL;
1731             }
1732             if (rval)
1733             {
1734                 zebra_lock_r(zh->lock_normal);
1735                 zebra_lock_w(zh->lock_shadow);
1736             }
1737             else
1738             {
1739                 zebra_lock_w(zh->lock_normal);
1740                 zebra_lock_w(zh->lock_shadow);
1741             }
1742         }
1743
1744         zebra_set_state (zh, 'd', seqno);
1745         
1746         zh->reg = zebra_register_open(zh->service, zh->reg_name,
1747                                       1, rval ? 1 : 0, zh->res,
1748                                       zh->path_reg);
1749         if (zh->reg)
1750             zh->reg->seqno = seqno;
1751         else
1752         {
1753             zebra_set_state (zh, 'o', seqno);
1754             
1755             zebra_unlock (zh->lock_shadow);
1756             zebra_unlock (zh->lock_normal);
1757
1758             zh->trans_no--;
1759             zh->trans_w_no = 0;
1760
1761             zebra_setError(zh, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
1762                            "zebra_begin_trans: cannot open register");
1763             yaz_log(YLOG_FATAL, "%s", zh->errString);
1764             return ZEBRA_FAIL;
1765         }
1766         zebraExplain_curDatabase(zh->reg->zei, zh->basenames[0]);
1767     }
1768     else
1769     {
1770         int dirty = 0;
1771         char val;
1772         int seqno;
1773         
1774         (zh->trans_no)++;
1775         
1776         if (zh->trans_no != 1)
1777         {
1778             return zebra_flush_reg (zh);
1779         }
1780 #if HAVE_SYS_TIMES_H
1781         times (&zh->tms1);
1782 #endif
1783         if (!zh->res)
1784         {
1785             (zh->trans_no)--;
1786             zh->errCode = YAZ_BIB1_DATABASE_UNAVAILABLE;
1787             return ZEBRA_FAIL;
1788         }
1789         if (!zh->lock_normal || !zh->lock_shadow)
1790         {
1791             (zh->trans_no)--;
1792             zh->errCode = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1793             return ZEBRA_FAIL;
1794         }
1795         zebra_get_state (zh, &val, &seqno);
1796         if (val == 'd')
1797             val = 'o';
1798         
1799         if (!zh->reg)
1800             dirty = 1;
1801         else if (seqno != zh->reg->seqno)
1802         {
1803             yaz_log (YLOG_DEBUG, "reopen seqno cur/old %d/%d",
1804                      seqno, zh->reg->seqno);
1805             dirty = 1;
1806         }
1807         else if (zh->reg->last_val != val)
1808         {
1809             yaz_log (YLOG_DEBUG, "reopen last cur/old %d/%d",
1810                      val, zh->reg->last_val);
1811             dirty = 1;
1812         }
1813         if (!dirty)
1814             return ZEBRA_OK;
1815         
1816         if (val == 'c')
1817             zebra_lock_r (zh->lock_shadow);
1818         else
1819             zebra_lock_r (zh->lock_normal);
1820         
1821         if (zh->reg)
1822         {
1823             resultSetInvalidate (zh);
1824             zebra_register_close(zh->service, zh->reg);
1825         }
1826         zh->reg = zebra_register_open(zh->service, zh->reg_name,
1827                                       0, val == 'c' ? 1 : 0,
1828                                       zh->res, zh->path_reg);
1829         if (!zh->reg)
1830         {
1831             zebra_unlock (zh->lock_normal);
1832             zebra_unlock (zh->lock_shadow);
1833             zh->trans_no--;
1834             zh->errCode = YAZ_BIB1_DATABASE_UNAVAILABLE;
1835             return ZEBRA_FAIL;
1836         }
1837         zh->reg->last_val = val;
1838         zh->reg->seqno = seqno;
1839     }
1840     read_res_for_transaction(zh);
1841     return ZEBRA_OK;
1842 }
1843
1844 ZEBRA_RES zebra_end_trans (ZebraHandle zh)
1845 {
1846     ZebraTransactionStatus dummy;
1847
1848     yaz_log(log_level, "zebra_end_trans");
1849     ZEBRA_CHECK_HANDLE(zh);
1850     return zebra_end_transaction(zh, &dummy);
1851 }
1852
1853 ZEBRA_RES zebra_end_transaction (ZebraHandle zh, ZebraTransactionStatus *status)
1854 {
1855     char val;
1856     int seqno;
1857     const char *rval;
1858
1859     ZEBRA_CHECK_HANDLE(zh);
1860
1861     assert(status);
1862     yaz_log(log_level, "zebra_end_transaction");
1863
1864     status->processed = 0;
1865     status->inserted  = 0;
1866     status->updated   = 0;
1867     status->deleted   = 0;
1868     status->utime     = 0;
1869     status->stime     = 0;
1870
1871     if (!zh->res || !zh->reg)
1872     {
1873         zebra_setError(zh, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
1874                        "zebra_end_trans: no open transaction");
1875         return ZEBRA_FAIL;
1876     }
1877     if (zh->trans_no != zh->trans_w_no)
1878     {
1879         zh->trans_no--;
1880         if (zh->trans_no != 0)
1881             return ZEBRA_OK;
1882
1883         /* release read lock */
1884
1885         zebra_unlock (zh->lock_normal);
1886         zebra_unlock (zh->lock_shadow);
1887     }
1888     else
1889     {   /* release write lock */
1890         zh->trans_no--;
1891         zh->trans_w_no = 0;
1892         
1893         yaz_log (YLOG_DEBUG, "zebra_end_trans");
1894         rval = res_get (zh->res, "shadow");
1895         
1896         zebraExplain_runNumberIncrement (zh->reg->zei, 1);
1897         
1898         zebra_flush_reg (zh);
1899         
1900         resultSetInvalidate (zh);
1901
1902         zebra_register_close(zh->service, zh->reg);
1903         zh->reg = 0;
1904         
1905         yaz_log (YLOG_LOG, "Records: "ZINT_FORMAT" i/u/d "
1906                         ZINT_FORMAT"/"ZINT_FORMAT"/"ZINT_FORMAT, 
1907                  zh->records_processed, zh->records_inserted,
1908                  zh->records_updated, zh->records_deleted);
1909         
1910         status->processed = zh->records_processed;
1911         status->inserted = zh->records_inserted;
1912         status->updated = zh->records_updated;
1913         status->deleted = zh->records_deleted;
1914         
1915         zebra_get_state (zh, &val, &seqno);
1916         if (val != 'd')
1917         {
1918             BFiles bfs = bfs_create (rval, zh->path_reg);
1919             yaz_log (YLOG_DEBUG, "deleting shadow val=%c", val);
1920             bf_commitClean (bfs, rval);
1921             bfs_destroy (bfs);
1922         }
1923         if (!rval)
1924             seqno++;
1925         zebra_set_state (zh, 'o', seqno);
1926         
1927         zebra_unlock (zh->lock_shadow);
1928         zebra_unlock (zh->lock_normal);
1929         
1930     }
1931 #if HAVE_SYS_TIMES_H
1932     times (&zh->tms2);
1933     yaz_log (log_level, "user/system: %ld/%ld",
1934           (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1935           (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1936     
1937     status->utime = (long) (zh->tms2.tms_utime - zh->tms1.tms_utime);
1938     status->stime = (long) (zh->tms2.tms_stime - zh->tms1.tms_stime);
1939 #endif
1940     return ZEBRA_OK;
1941 }
1942
1943 ZEBRA_RES zebra_repository_update(ZebraHandle zh, const char *path)
1944 {
1945     ASSERTZH;
1946     assert(path);
1947     yaz_log (log_level, "updating %s", path);
1948
1949     if (zh->m_record_id && !strcmp (zh->m_record_id, "file"))
1950         return zebra_update_file_match(zh, path);
1951     else
1952         return zebra_update_from_path(zh, path);
1953 }
1954
1955 ZEBRA_RES zebra_repository_delete(ZebraHandle zh, const char *path)
1956 {
1957     ASSERTZH;
1958     assert(path);
1959     yaz_log (log_level, "deleting %s", path);
1960     return zebra_delete_from_path(zh, path);
1961 }
1962
1963 ZEBRA_RES zebra_repository_show(ZebraHandle zh, const char *path)
1964 {
1965     ASSERTZH;
1966     assert(path);
1967     yaz_log(log_level, "zebra_repository_show");
1968     repositoryShow (zh, path);
1969     return ZEBRA_OK;
1970 }
1971
1972 static ZEBRA_RES zebra_commit_ex(ZebraHandle zh, int clean_only)
1973 {
1974     int seqno;
1975     char val;
1976     const char *rval;
1977     BFiles bfs;
1978     ZEBRA_RES res = ZEBRA_OK;
1979
1980     ASSERTZH;
1981
1982     zebra_select_default_database(zh);
1983     if (!zh->res)
1984     {
1985         zh->errCode = YAZ_BIB1_DATABASE_UNAVAILABLE;
1986         return ZEBRA_FAIL;
1987     }
1988     rval = res_get(zh->res, "shadow");    
1989     if (!rval)
1990     {
1991         yaz_log (YLOG_WARN, "Cannot perform commit - No shadow area defined");
1992         return ZEBRA_OK;
1993     }
1994
1995     zebra_lock_w(zh->lock_normal);
1996     zebra_lock_r(zh->lock_shadow);
1997
1998     bfs = bfs_create(res_get (zh->res, "register"), zh->path_reg);
1999     if (!bfs)
2000     {
2001         zebra_unlock(zh->lock_shadow);
2002         zebra_unlock(zh->lock_normal);
2003         return ZEBRA_FAIL;
2004     }
2005     zebra_get_state(zh, &val, &seqno);
2006
2007     if (val == 'd')
2008     {
2009         /* shadow area is dirty and so we must throw it away */
2010         yaz_log(YLOG_WARN, "previous transaction didn't reach commit");
2011         clean_only = 1;
2012     }
2013
2014     if (rval && *rval)
2015         bf_cache (bfs, rval);
2016     if (bf_commitExists (bfs))
2017     {
2018         if (clean_only)
2019             zebra_set_state(zh, 'd', seqno);
2020         else
2021         {
2022             zebra_set_state(zh, 'c', seqno);
2023             
2024             yaz_log(YLOG_DEBUG, "commit start");
2025             if (bf_commitExec (bfs))
2026                 res = ZEBRA_FAIL;
2027         }
2028         if (res == ZEBRA_OK)
2029         {
2030             seqno++;
2031             zebra_set_state(zh, 'o', seqno);
2032             
2033             zebra_unlock(zh->lock_shadow);
2034             zebra_unlock(zh->lock_normal);
2035             
2036             zebra_lock_w(zh->lock_shadow);
2037             bf_commitClean(bfs, rval);
2038             zebra_unlock(zh->lock_shadow);
2039         }
2040         else
2041         {
2042             zebra_unlock(zh->lock_shadow);
2043             zebra_unlock(zh->lock_normal);
2044             yaz_log(YLOG_WARN, "zebra_commit: failed");
2045         }
2046     }
2047     else
2048     {
2049         zebra_unlock(zh->lock_shadow);
2050         zebra_unlock(zh->lock_normal);
2051         yaz_log(log_level, "nothing to commit");
2052     }
2053     bfs_destroy(bfs);
2054
2055     return res;
2056 }
2057
2058 ZEBRA_RES zebra_clean(ZebraHandle zh)
2059 {
2060     yaz_log(log_level, "zebra_clean");
2061     ZEBRA_CHECK_HANDLE(zh);
2062     return zebra_commit_ex(zh, 1);
2063 }
2064
2065 ZEBRA_RES zebra_commit(ZebraHandle zh)
2066 {
2067     yaz_log(log_level, "zebra_commit");
2068     ZEBRA_CHECK_HANDLE(zh);
2069     return zebra_commit_ex(zh, 0);
2070 }
2071
2072
2073 ZEBRA_RES zebra_init(ZebraHandle zh)
2074 {
2075     const char *rval;
2076     BFiles bfs = 0;
2077
2078     yaz_log(log_level, "zebra_init");
2079
2080     ZEBRA_CHECK_HANDLE(zh);
2081
2082     zebra_select_default_database(zh);
2083     if (!zh->res)
2084     {
2085         zebra_setError(zh, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
2086                        "cannot select default database");
2087         return ZEBRA_FAIL;
2088     }
2089     rval = res_get (zh->res, "shadow");
2090
2091     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
2092     if (!bfs)
2093     {
2094         zebra_setError(zh, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR, "bfs_create");
2095         return ZEBRA_FAIL;
2096     }
2097     if (rval && *rval)
2098         bf_cache (bfs, rval);
2099     
2100     bf_reset (bfs);
2101     bfs_destroy (bfs);
2102     zebra_set_state (zh, 'o', 0);
2103     return ZEBRA_OK;
2104 }
2105
2106 ZEBRA_RES zebra_compact(ZebraHandle zh)
2107 {
2108     BFiles bfs;
2109
2110     yaz_log(log_level, "zebra_compact");
2111     ZEBRA_CHECK_HANDLE(zh);
2112     if (!zh->res)
2113     {
2114         zh->errCode = YAZ_BIB1_DATABASE_UNAVAILABLE;
2115         return ZEBRA_FAIL;
2116     }
2117     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
2118     inv_compact (bfs);
2119     bfs_destroy (bfs);
2120     return ZEBRA_OK;
2121 }
2122
2123 void zebra_result(ZebraHandle zh, int *code, char **addinfo)
2124 {
2125     yaz_log(log_level, "zebra_result");
2126     if (zh)
2127     {
2128         *code = zh->errCode;
2129         *addinfo = zh->errString;
2130     }
2131     else
2132     {
2133         *code = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
2134         *addinfo ="ZebraHandle is NULL";
2135     }
2136 }
2137
2138 void zebra_shadow_enable(ZebraHandle zh, int value)
2139 {
2140     ASSERTZH;
2141     yaz_log(log_level, "zebra_shadow_enable");
2142     zh->shadow_enable = value;
2143 }
2144
2145 ZEBRA_RES zebra_octet_term_encoding(ZebraHandle zh, const char *encoding)
2146 {
2147     yaz_log(log_level, "zebra_octet_term_encoding %s", encoding);
2148     ZEBRA_CHECK_HANDLE(zh);
2149     assert(encoding);
2150
2151     if (zh->iconv_to_utf8 != 0)
2152         yaz_iconv_close(zh->iconv_to_utf8);
2153     if (zh->iconv_from_utf8 != 0)
2154         yaz_iconv_close(zh->iconv_from_utf8);
2155     
2156     zh->iconv_to_utf8 =
2157         yaz_iconv_open ("UTF-8", encoding);
2158     if (zh->iconv_to_utf8 == 0)
2159         yaz_log (YLOG_WARN, "iconv: %s to UTF-8 unsupported", encoding);
2160     zh->iconv_from_utf8 =
2161         yaz_iconv_open (encoding, "UTF-8");
2162     if (zh->iconv_to_utf8 == 0)
2163         yaz_log (YLOG_WARN, "iconv: UTF-8 to %s unsupported", encoding);
2164
2165     return ZEBRA_OK;
2166 }
2167
2168 ZEBRA_RES zebra_record_encoding (ZebraHandle zh, const char *encoding)
2169 {
2170     yaz_log(log_level, "zebra_record_encoding");
2171     ZEBRA_CHECK_HANDLE(zh);
2172     xfree(zh->record_encoding);
2173     zh->record_encoding = 0;
2174     if (encoding)
2175         zh->record_encoding = xstrdup (encoding);
2176     return ZEBRA_OK;
2177 }
2178
2179 void zebra_set_resource(ZebraHandle zh, const char *name, const char *value)
2180 {
2181     assert(name);
2182     assert(value);
2183     yaz_log(log_level, "zebra_set_resource %s:%s", name, value);
2184     ASSERTZH;
2185     res_set(zh->res, name, value);
2186 }
2187
2188 const char *zebra_get_resource(ZebraHandle zh,
2189                                const char *name, const char *defaultvalue)
2190 {
2191     const char *v;
2192     ASSERTZH;
2193     assert(name);
2194     v = res_get_def (zh->res, name, (char *)defaultvalue);
2195     yaz_log(log_level, "zebra_get_resource %s:%s", name, v);
2196     return v;
2197 }
2198
2199 /* moved from zebra_api_ext.c by pop */
2200 /* FIXME: Should this really be public??? -Heikki */
2201
2202 int zebra_trans_no (ZebraHandle zh)
2203 {
2204     yaz_log(log_level, "zebra_trans_no");
2205     ASSERTZH;
2206     return zh->trans_no;
2207 }
2208
2209 int zebra_get_shadow_enable (ZebraHandle zh)
2210 {
2211     yaz_log(log_level, "zebra_get_shadow_enable");
2212     ASSERTZH;
2213     return zh->shadow_enable;
2214 }
2215
2216 void zebra_set_shadow_enable (ZebraHandle zh, int value)
2217 {
2218     yaz_log(log_level, "zebra_set_shadow_enable %d",value);
2219     ASSERTZH;
2220     zh->shadow_enable = value;
2221 }
2222
2223 ZEBRA_RES zebra_add_record(ZebraHandle zh,
2224                            const char *buf, int buf_size)
2225 {
2226     return zebra_update_record(zh, action_update, 
2227                                0 /* record type */,
2228                                0 /* sysno */ ,
2229                                0 /* match */, 
2230                                0 /* fname */,
2231                                buf, buf_size);
2232 }
2233
2234 ZEBRA_RES zebra_update_record(ZebraHandle zh, 
2235                               enum zebra_recctrl_action_t action,
2236                               const char *recordType,
2237                               zint *sysno, const char *match,
2238                               const char *fname,
2239                               const char *buf, int buf_size)
2240 {
2241     ZEBRA_RES res;
2242
2243     ZEBRA_CHECK_HANDLE(zh);
2244
2245     assert(buf);
2246
2247     yaz_log(log_level, "zebra_update_record");
2248     if (sysno)
2249         yaz_log(log_level, " sysno=" ZINT_FORMAT, *sysno);
2250
2251     if (buf_size < 1)
2252         buf_size = strlen(buf);
2253
2254     if (zebra_begin_trans(zh, 1) == ZEBRA_FAIL)
2255         return ZEBRA_FAIL;
2256     res = zebra_buffer_extract_record(zh, buf, buf_size, 
2257                                       action,
2258                                       0, /* test_mode */
2259                                       recordType,
2260                                       sysno,   
2261                                       match, 
2262                                       fname);
2263     if (zebra_end_trans(zh) != ZEBRA_OK)
2264     {
2265         yaz_log(YLOG_WARN, "zebra_end_trans failed");
2266         res = ZEBRA_FAIL;
2267     }
2268     return res; 
2269 }
2270
2271 /* ---------------------------------------------------------------------------
2272   Searching 
2273 */
2274
2275 ZEBRA_RES zebra_search_PQF(ZebraHandle zh, const char *pqf_query,
2276                            const char *setname, zint *hits)
2277 {
2278     zint lhits = 0;
2279     ZEBRA_RES res = ZEBRA_OK;
2280     Z_RPNQuery *query;
2281     ODR odr;
2282
2283
2284     ZEBRA_CHECK_HANDLE(zh);
2285
2286     odr = odr_createmem(ODR_ENCODE);
2287
2288     assert(pqf_query);
2289     assert(setname);
2290
2291     yaz_log(log_level, "zebra_search_PQF s=%s q=%s", setname, pqf_query);
2292     
2293     query = p_query_rpn(odr, pqf_query);
2294     
2295     if (!query)
2296     {
2297         yaz_log (YLOG_WARN, "bad query %s\n", pqf_query);
2298         zh->errCode = YAZ_BIB1_MALFORMED_QUERY;
2299         res = ZEBRA_FAIL;
2300     }
2301     else
2302         res = zebra_search_RPN(zh, odr, query, setname, &lhits);
2303     
2304     odr_destroy(odr);
2305
2306     yaz_log(log_level, "Hits: " ZINT_FORMAT, lhits);
2307
2308     if (hits)
2309         *hits = lhits;
2310
2311     return res;
2312 }
2313
2314 /* ---------------------------------------------------------------------------
2315   Sort - a simplified interface, with optional read locks.
2316 */
2317 int zebra_sort_by_specstr (ZebraHandle zh, ODR stream,
2318                            const char *sort_spec,
2319                            const char *output_setname,
2320                            const char **input_setnames) 
2321 {
2322     int num_input_setnames = 0;
2323     int sort_status = 0;
2324     Z_SortKeySpecList *sort_sequence;
2325
2326     ZEBRA_CHECK_HANDLE(zh);
2327     assert(stream);
2328     assert(sort_spec);
2329     assert(output_setname);
2330     assert(input_setnames);
2331     sort_sequence = yaz_sort_spec (stream, sort_spec);
2332     yaz_log(log_level, "sort (FIXME) ");
2333     if (!sort_sequence)
2334     {
2335         yaz_log(YLOG_WARN, "invalid sort specs '%s'", sort_spec);
2336         zh->errCode = YAZ_BIB1_CANNOT_SORT_ACCORDING_TO_SEQUENCE;
2337         return -1;
2338     }
2339     
2340     /* we can do this, since the perl typemap code for char** will 
2341        put a NULL at the end of list */
2342     while (input_setnames[num_input_setnames]) num_input_setnames++;
2343
2344     if (zebra_begin_read (zh))
2345         return -1;
2346     
2347     resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
2348                    output_setname, sort_sequence, &sort_status);
2349     
2350     zebra_end_read(zh);
2351     return sort_status;
2352 }
2353
2354 /* ---------------------------------------------------------------------------
2355   Get BFS for Zebra system (to make alternative storage methods)
2356 */
2357 struct BFiles_struct *zebra_get_bfs(ZebraHandle zh)
2358 {
2359     if (zh && zh->reg)
2360         return zh->reg->bfs;
2361     return 0;
2362 }
2363
2364
2365 /* ---------------------------------------------------------------------------
2366   Set limit for search/scan
2367 */
2368 ZEBRA_RES zebra_set_limit(ZebraHandle zh, int complement_flag, zint *ids)
2369 {
2370     ZEBRA_CHECK_HANDLE(zh);
2371     zebra_limit_destroy(zh->m_limit);
2372     zh->m_limit = zebra_limit_create(complement_flag, ids);
2373     return ZEBRA_OK;
2374 }
2375
2376 /*
2377   Set Error code + addinfo
2378 */
2379 void zebra_setError(ZebraHandle zh, int code, const char *addinfo)
2380 {
2381     if (!zh)
2382         return;
2383     zh->errCode = code;
2384     nmem_reset(zh->nmem_error);
2385     zh->errString = addinfo ? nmem_strdup(zh->nmem_error, addinfo) : 0;
2386 }
2387
2388 void zebra_setError_zint(ZebraHandle zh, int code, zint i)
2389 {
2390     char vstr[60];
2391     sprintf(vstr, ZINT_FORMAT, i);
2392
2393     zh->errCode = code;
2394     nmem_reset(zh->nmem_error);
2395     zh->errString = nmem_strdup(zh->nmem_error, vstr);
2396 }
2397
2398 void zebra_lock_prefix(Res res, char *path)
2399 {
2400     const char *lock_dir = res_get_def (res, "lockDir", "");
2401     
2402     strcpy(path, lock_dir);
2403     if (*path && path[strlen(path)-1] != '/')
2404         strcat (path, "/");
2405 }
2406
2407 /*
2408  * Local variables:
2409  * c-basic-offset: 4
2410  * indent-tabs-mode: nil
2411  * End:
2412  * vim: shiftwidth=4 tabstop=8 expandtab
2413  */
2414