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