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