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