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