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