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