Use Odr_oid for OIDs. Require YAZ 3.0.2 or later.
[idzebra-moved-to-github.git] / index / zebraapi.c
1 /* $Id: zebraapi.c,v 1.255 2007-05-08 12:50:04 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 ZebraHandle zebra_open(ZebraService zs, Res res)
103 {
104     ZebraHandle zh;
105     const char *default_encoding;
106     if (!log_level_initialized)
107     {
108         log_level = yaz_log_module_level("zebraapi");
109         log_level_initialized = 1;
110     }
111
112     yaz_log(log_level, "zebra_open");
113
114     if (!zs)
115         return 0;
116
117     zh = (ZebraHandle) xmalloc(sizeof(*zh));
118     yaz_log (YLOG_DEBUG, "zebra_open zs=%p returns %p", zs, zh);
119
120     zh->service = zs;
121     zh->reg = 0;          /* no register attached yet */
122     zh->sets = 0;
123     zh->destroyed = 0;
124     zh->errCode = 0;
125     zh->errString = 0;
126     zh->res = 0; 
127     zh->session_res = res_open(zs->global_res, res);
128     zh->user_perm = 0;
129     zh->dbaccesslist = 0;
130
131     zh->reg_name = xstrdup ("");
132     zh->path_reg = 0;
133     zh->num_basenames = 0;
134     zh->basenames = 0;
135
136     zh->approx_limit = DEFAULT_APPROX_LIMIT;
137     zh->trans_no = 0;
138     zh->trans_w_no = 0;
139
140     zh->lock_normal = 0;
141     zh->lock_shadow = 0;
142
143     zh->shadow_enable = 1;
144     zh->m_staticrank = 0;
145     zh->m_segment_indexing = 0;
146
147     zh->break_handler_func = 0;
148     zh->break_handler_data = 0;
149
150     default_encoding = res_get_def(zh->session_res, "encoding", "ISO-8859-1");
151
152     zh->iconv_to_utf8 =
153         yaz_iconv_open ("UTF-8", default_encoding);
154     if (zh->iconv_to_utf8 == 0)
155         yaz_log (YLOG_WARN, "iconv: %s to UTF-8 unsupported",
156            default_encoding);
157     zh->iconv_from_utf8 =
158         yaz_iconv_open (default_encoding, "UTF-8");
159     if (zh->iconv_to_utf8 == 0)
160         yaz_log (YLOG_WARN, "iconv: UTF-8 to %s unsupported",
161            default_encoding);
162
163     zh->record_encoding = 0;
164
165     zebra_mutex_cond_lock (&zs->session_lock);
166
167     zh->next = zs->sessions;
168     zs->sessions = zh;
169
170     zebra_mutex_cond_unlock (&zs->session_lock);
171
172     zh->store_data_buf = 0;
173
174     zh->m_limit = zebra_limit_create(1, 0);
175
176     zh->nmem_error = nmem_create();
177
178     return zh;
179 }
180
181 ZebraService zebra_start(const char *configName)
182 {
183     return zebra_start_res(configName, 0, 0);
184 }
185
186 ZebraService zebra_start_res(const char *configName, Res def_res, Res over_res)
187 {
188     Res res;
189
190     zebra_flock_init();
191
192     if (!log_level_initialized)
193     {
194         log_level = yaz_log_module_level("zebraapi");
195         log_level_initialized = 1;
196     }
197     
198     yaz_log(YLOG_LOG, "zebra_start %s %s", ZEBRAVER,
199             configName ? configName : "");
200
201     if ((res = res_open(def_res, over_res)))
202     {
203         const char *passwd_plain = 0;
204         const char *passwd_encrypt = 0;
205         const char *dbaccess = 0;
206         ZebraService zh = 0;
207
208         if (configName)
209         {
210             ZEBRA_RES ret = res_read_file(res, configName);
211             if (ret != ZEBRA_OK)
212             {
213                 res_close(res);
214                 return 0;
215             }
216             if (zebra_check_res(res))
217             {
218                 yaz_log(YLOG_FATAL, "Configuration error(s) for %s",
219                         configName);
220                 return 0;
221             }
222         }
223         else
224         {
225             zebra_check_res(res);
226         }
227
228         zh = xmalloc(sizeof(*zh));
229         zh->global_res = res;
230         zh->sessions = 0;
231         
232         zebra_chdir (zh);
233         
234         zebra_mutex_cond_init (&zh->session_lock);
235         passwd_plain = res_get (zh->global_res, "passwd");
236         passwd_encrypt = res_get (zh->global_res, "passwd.c");
237         dbaccess = res_get (zh->global_res, "dbaccess");
238
239         if (!passwd_plain && !passwd_encrypt)
240             zh->passwd_db = NULL;
241         else 
242         {
243             zh->passwd_db = passwd_db_open();
244             if (!zh->passwd_db)
245                 yaz_log (YLOG_WARN|YLOG_ERRNO, "passwd_db_open failed");
246             else
247             {
248                 if (passwd_plain)
249                     passwd_db_file_plain(zh->passwd_db, passwd_plain);
250                 if (passwd_encrypt)
251                     passwd_db_file_crypt(zh->passwd_db, passwd_encrypt);
252             }
253         }
254
255         if (!dbaccess)
256             zh->dbaccess = NULL;
257         else {
258             zh->dbaccess = res_open(NULL, NULL);
259             if (res_read_file(zh->dbaccess, dbaccess) != ZEBRA_OK) {
260                 yaz_log(YLOG_FATAL, "Failed to read %s", dbaccess);
261                 return NULL;
262             }
263         }
264
265         zh->timing = yaz_timing_create();
266         zh->path_root = res_get (zh->global_res, "root");
267         zh->nmem = nmem_create();
268         zh->record_classes = recTypeClass_create (zh->global_res, zh->nmem);
269
270         if (1)
271         {
272             const char *module_path = res_get(res, "modulePath");
273             if (module_path)
274                 recTypeClass_load_modules(&zh->record_classes, zh->nmem,
275                                           module_path);
276         }
277         return zh;
278     }
279     return 0;
280 }
281
282 void zebra_filter_info(ZebraService zs, void *cd,
283                         void (*cb)(void *cd, const char *name))
284 {
285     ASSERTZS;
286     assert(cb);
287     recTypeClass_info(zs->record_classes, cd, cb);
288 }
289
290 void zebra_pidfname(ZebraService zs, char *path)
291 {
292     ASSERTZS;
293     zebra_lock_prefix (zs->global_res, path);
294     strcat(path, "zebrasrv.pid");
295 }
296
297 Dict dict_open_res (BFiles bfs, const char *name, int cache, int rw,
298                     int compact_flag, Res res)
299 {
300     int page_size = 4096;
301     char resource_str[200];
302     sprintf (resource_str, "dict.%.100s.pagesize", name);
303     assert(bfs);
304     assert(name);
305
306     if (res_get_int(res, resource_str, &page_size) == ZEBRA_OK)
307         yaz_log(YLOG_LOG, "Using custom dictionary page size %d for %s",
308                 page_size, name);
309     return dict_open(bfs, name, cache, rw, compact_flag, page_size);
310 }
311
312 static
313 struct zebra_register *zebra_register_open(ZebraService zs, const char *name,
314                                            int rw, int useshadow, Res res,
315                                            const char *reg_path)
316 {
317     struct zebra_register *reg;
318     int record_compression = REC_COMPRESS_NONE;
319     const char *recordCompression = 0;
320     const char *profilePath;
321     char cwd[1024];
322     int sort_type = ZEBRA_SORT_TYPE_FLAT;
323     ZEBRA_RES ret = ZEBRA_OK;
324
325     ASSERTZS;
326     
327     reg = xmalloc(sizeof(*reg));
328
329     assert (name);
330     reg->name = xstrdup (name);
331
332     reg->seqno = 0;
333     reg->last_val = 0;
334
335     assert (res);
336
337     yaz_log (YLOG_DEBUG, "zebra_register_open rw=%d useshadow=%d p=%p n=%s rp=%s",
338              rw, useshadow, reg, name, reg_path ? reg_path : "(none)");
339     
340     reg->dh = data1_create();
341     if (!reg->dh)
342     {
343         xfree(reg->name);
344         xfree(reg);
345         return 0;
346     }
347     reg->bfs = bfs_create (res_get (res, "register"), reg_path);
348     if (!reg->bfs)
349     {
350         data1_destroy(reg->dh);
351         xfree(reg->name);
352         xfree(reg);
353         return 0;
354     }
355     if (useshadow)
356     {
357         if (bf_cache (reg->bfs, res_get (res, "shadow")) == ZEBRA_FAIL)
358         {
359             bfs_destroy(reg->bfs);
360             data1_destroy(reg->dh);
361             xfree(reg->name);
362             xfree(reg);
363             return 0;
364         }
365     }
366
367     getcwd(cwd, sizeof(cwd)-1);
368     profilePath = res_get_def(res, "profilePath", 0);
369
370     data1_set_tabpath (reg->dh, profilePath);
371     data1_set_tabroot (reg->dh, reg_path);
372     reg->recTypes = recTypes_init (zs->record_classes, reg->dh);
373
374     reg->zebra_maps =
375         zebra_maps_open(res, reg_path, profilePath);
376     if (!reg->zebra_maps)
377     {
378         recTypes_destroy(reg->recTypes);
379         bfs_destroy(reg->bfs);
380         data1_destroy(reg->dh);
381         xfree(reg->name);
382         xfree(reg);
383         return 0;
384     }
385     reg->rank_classes = NULL;
386
387     reg->key_block = 0;
388     reg->keys = zebra_rec_keys_open();
389
390     reg->sortKeys = zebra_rec_keys_open();
391
392     reg->records = 0;
393     reg->dict = 0;
394     reg->sort_index = 0;
395     reg->isams = 0;
396     reg->matchDict = 0;
397     reg->isamc = 0;
398     reg->isamb = 0;
399     reg->zei = 0;
400     
401     /* installing rank classes */
402     zebraRankInstall (reg, rank_1_class);
403     zebraRankInstall (reg, rank_similarity_class);
404     zebraRankInstall (reg, rank_static_class);
405
406     recordCompression = res_get_def (res, "recordCompression", "none");
407     if (!strcmp (recordCompression, "none"))
408         record_compression = REC_COMPRESS_NONE;
409     if (!strcmp (recordCompression, "bzip2"))
410         record_compression = REC_COMPRESS_BZIP2;
411
412     if (1)
413     {
414         const char *index_fname = res_get_def(res, "index", "default.idx");
415         if (index_fname && *index_fname)
416         {
417             if (zebra_maps_read_file(reg->zebra_maps, index_fname) != ZEBRA_OK)
418                 ret = ZEBRA_FAIL;
419         }
420     }
421
422     if (!(reg->records = rec_open (reg->bfs, rw, record_compression)))
423     {
424         yaz_log (YLOG_WARN, "rec_open failed");
425         ret = ZEBRA_FAIL;
426     }
427     if (rw)
428     {
429         reg->matchDict = dict_open_res (reg->bfs, GMATCH_DICT, 20, 1, 0, res);
430     }
431     if (!(reg->dict = dict_open_res (reg->bfs, FNAME_DICT, 40, rw, 0, res)))
432     {
433         yaz_log (YLOG_WARN, "dict_open failed");
434         ret = ZEBRA_FAIL;
435     }
436
437     
438     if (res_get_match (res, "sortindex", "f", "f"))
439         sort_type = ZEBRA_SORT_TYPE_FLAT;
440     else if (res_get_match (res, "sortindex", "i", "f"))
441         sort_type = ZEBRA_SORT_TYPE_ISAMB;
442     else
443     {
444         yaz_log (YLOG_WARN, "bad_value for 'sortindex'");
445         ret = ZEBRA_FAIL;
446     }
447
448
449     if (!(reg->sort_index = zebra_sort_open(reg->bfs, rw, sort_type)))
450     {
451         yaz_log (YLOG_WARN, "zebra_sort_open failed");
452         ret = ZEBRA_FAIL;
453     }
454     if (res_get_match (res, "isam", "s", ISAM_DEFAULT))
455     {
456         struct ISAMS_M_s isams_m;
457         if (!(reg->isams = isams_open (reg->bfs, FNAME_ISAMS, rw,
458                                       key_isams_m(res, &isams_m))))
459         {
460             yaz_log (YLOG_WARN, "isams_open failed");
461             ret = ZEBRA_FAIL;
462         }
463     }
464     if (res_get_match (res, "isam", "c", ISAM_DEFAULT))
465     {
466         struct ISAMC_M_s isamc_m;
467         if (!(reg->isamc = isamc_open (reg->bfs, FNAME_ISAMC,
468                                     rw, key_isamc_m(res, &isamc_m))))
469         {
470             yaz_log (YLOG_WARN, "isamc_open failed");
471             ret = ZEBRA_FAIL;
472         }
473     }
474     if (res_get_match (res, "isam", "b", ISAM_DEFAULT))
475     {
476         struct ISAMC_M_s isamc_m;
477         
478         if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
479                                        rw, key_isamc_m(res, &isamc_m), 0)))
480         {
481             yaz_log (YLOG_WARN, "isamb_open failed");
482             ret = ZEBRA_FAIL;
483         }
484     }
485     if (res_get_match (res, "isam", "bc", ISAM_DEFAULT))
486     {
487         struct ISAMC_M_s isamc_m;
488         
489         if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
490                                        rw, key_isamc_m(res, &isamc_m), 1)))
491         {
492             yaz_log (YLOG_WARN, "isamb_open failed");
493             ret = ZEBRA_FAIL;
494         }
495     }
496     if (res_get_match (res, "isam", "null", ISAM_DEFAULT))
497     {
498         struct ISAMC_M_s isamc_m;
499         
500         if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
501                                        rw, key_isamc_m(res, &isamc_m), -1)))
502         {
503             yaz_log (YLOG_WARN, "isamb_open failed");
504             ret = ZEBRA_FAIL;
505         }
506     }
507     if (ret == ZEBRA_OK)
508     {
509         reg->zei = zebraExplain_open(reg->records, reg->dh,
510                                      res, rw, reg,
511                                      zebra_extract_explain);
512         if (!reg->zei)
513         {
514             yaz_log (YLOG_WARN, "Cannot obtain EXPLAIN information");
515             ret = ZEBRA_FAIL;
516         }
517     }
518     
519     if (ret != ZEBRA_OK)
520     {
521         zebra_register_close(zs, reg);
522         return 0;
523     }
524     yaz_log (YLOG_DEBUG, "zebra_register_open ok p=%p", reg);
525     return reg;
526 }
527
528 ZEBRA_RES zebra_admin_shutdown (ZebraHandle zh)
529 {
530     ZEBRA_CHECK_HANDLE(zh);
531     yaz_log(log_level, "zebra_admin_shutdown");
532
533     zebra_mutex_cond_lock (&zh->service->session_lock);
534     zh->service->stop_flag = 1;
535     zebra_mutex_cond_unlock (&zh->service->session_lock);
536     return ZEBRA_OK;
537 }
538
539 ZEBRA_RES zebra_admin_start (ZebraHandle zh)
540 {
541     ZebraService zs;
542     ZEBRA_CHECK_HANDLE(zh);
543     yaz_log(log_level, "zebra_admin_start");
544     zs = zh->service;
545     zebra_mutex_cond_lock (&zs->session_lock);
546     zebra_mutex_cond_unlock (&zs->session_lock);
547     return ZEBRA_OK;
548 }
549
550 static void zebra_register_close(ZebraService zs, struct zebra_register *reg)
551 {
552     ASSERTZS;
553     assert(reg);
554     yaz_log(YLOG_DEBUG, "zebra_register_close p=%p", reg);
555     reg->stop_flag = 0;
556     zebra_chdir (zs);
557     
558     zebraExplain_close (reg->zei);
559     dict_close (reg->dict);
560     if (reg->matchDict)
561         dict_close (reg->matchDict);
562     zebra_sort_close(reg->sort_index);
563     if (reg->isams)
564         isams_close (reg->isams);
565     if (reg->isamc)
566         isamc_close (reg->isamc);
567     if (reg->isamb)
568         isamb_close (reg->isamb);
569     rec_close (&reg->records);
570
571     recTypes_destroy (reg->recTypes);
572     zebra_maps_close (reg->zebra_maps);
573     zebraRankDestroy (reg);
574     bfs_destroy (reg->bfs);
575     data1_destroy (reg->dh);
576
577     zebra_rec_keys_close(reg->keys);
578     zebra_rec_keys_close(reg->sortKeys);
579
580     key_block_destroy(&reg->key_block);
581     xfree(reg->name);
582     xfree(reg);
583 }
584
585 ZEBRA_RES zebra_stop(ZebraService zs)
586 {
587     if (!zs)
588         return ZEBRA_OK;
589     while (zs->sessions)
590     {
591         zebra_close (zs->sessions);
592     }
593         
594     zebra_mutex_cond_destroy (&zs->session_lock);
595
596     if (zs->passwd_db)
597         passwd_db_close (zs->passwd_db);
598
599     recTypeClass_destroy(zs->record_classes);
600     nmem_destroy(zs->nmem);
601     res_close (zs->global_res);
602
603     yaz_timing_stop(zs->timing);
604     yaz_log (YLOG_LOG, "zebra_stop: %4.2f %4.2f %4.2f",
605              yaz_timing_get_real(zs->timing),
606              yaz_timing_get_user(zs->timing),
607              yaz_timing_get_sys(zs->timing));
608     
609
610     yaz_timing_destroy(&zs->timing);
611     xfree(zs);
612     return ZEBRA_OK;
613 }
614
615 ZEBRA_RES zebra_close(ZebraHandle zh)
616 {
617     ZebraService zs;
618     struct zebra_session **sp;
619     int i;
620
621     yaz_log(log_level, "zebra_close");
622     ZEBRA_CHECK_HANDLE(zh);
623
624     zh->errCode = 0;
625     
626     zs = zh->service;
627     yaz_log (YLOG_DEBUG, "zebra_close zh=%p", zh);
628     resultSetDestroy (zh, -1, 0, 0);
629
630     if (zh->reg)
631         zebra_register_close(zh->service, zh->reg);
632     zebra_close_res (zh);
633     res_close(zh->session_res);
634
635     xfree(zh->record_encoding);
636
637     xfree(zh->dbaccesslist);
638
639     for (i = 0; i < zh->num_basenames; i++)
640         xfree(zh->basenames[i]);
641     xfree(zh->basenames);
642
643     if (zh->iconv_to_utf8 != 0)
644         yaz_iconv_close (zh->iconv_to_utf8);
645     if (zh->iconv_from_utf8 != 0)
646         yaz_iconv_close (zh->iconv_from_utf8);
647
648     zebra_mutex_cond_lock (&zs->session_lock);
649     zebra_lock_destroy (zh->lock_normal);
650     zebra_lock_destroy (zh->lock_shadow);
651     sp = &zs->sessions;
652     while (1)
653     {
654         assert (*sp);
655         if (*sp == zh)
656         {
657             *sp = (*sp)->next;
658             break;
659         }
660         sp = &(*sp)->next;
661     }
662     zebra_mutex_cond_unlock (&zs->session_lock);
663     xfree(zh->reg_name);
664     xfree(zh->user_perm);
665     zh->service = 0; /* more likely to trigger an assert */
666
667     zebra_limit_destroy(zh->m_limit);
668
669     nmem_destroy(zh->nmem_error);
670
671     xfree(zh->path_reg);
672     xfree(zh);
673     return ZEBRA_OK;
674 }
675
676 struct map_baseinfo {
677     ZebraHandle zh;
678     NMEM mem;
679     int num_bases;
680     char **basenames;
681     int new_num_bases;
682     char **new_basenames;
683     int new_num_max;
684 };
685
686 static void zebra_open_res(ZebraHandle zh)
687 {
688     char fname[512];
689     ASSERTZH;
690     zh->errCode = 0;
691
692     if (zh->path_reg)
693     {
694         sprintf(fname, "%.200s/zebra.cfg", zh->path_reg);
695         zh->res = res_open(zh->session_res, 0);
696         res_read_file(zh->res, fname);
697     }
698     else if (*zh->reg_name == 0)
699     {
700         zh->res = res_open(zh->session_res, 0);
701     }
702     else
703     {
704         yaz_log (YLOG_WARN, "no register root specified");
705         zh->res = 0;  /* no path for register - fail! */
706     }
707 }
708
709 static void zebra_close_res (ZebraHandle zh)
710 {
711     ASSERTZH;
712     zh->errCode = 0;
713     res_close (zh->res);
714     zh->res = 0;
715 }
716
717 static void zebra_select_register (ZebraHandle zh, const char *new_reg)
718 {
719     ASSERTZH;
720     zh->errCode = 0;
721     if (zh->res && strcmp (zh->reg_name, new_reg) == 0)
722         return;
723     if (!zh->res)
724     {
725         assert (zh->reg == 0);
726         assert (*zh->reg_name == 0);
727     }
728     else
729     {
730         if (zh->reg)
731         {
732             resultSetInvalidate (zh);
733             zebra_register_close(zh->service, zh->reg);
734             zh->reg = 0;
735         }
736         zebra_close_res(zh);
737     }
738     xfree(zh->reg_name);
739     zh->reg_name = xstrdup (new_reg);
740
741     xfree(zh->path_reg);
742     zh->path_reg = 0;
743     if (zh->service->path_root)
744     {
745         zh->path_reg = xmalloc(strlen(zh->service->path_root) + 
746                                 strlen(zh->reg_name) + 3);
747         strcpy (zh->path_reg, zh->service->path_root);
748         if (*zh->reg_name)
749         {
750             strcat (zh->path_reg, "/");
751             strcat (zh->path_reg, zh->reg_name);
752         }
753     }
754     zebra_open_res(zh);
755     
756     if (zh->lock_normal)
757         zebra_lock_destroy (zh->lock_normal);
758     zh->lock_normal = 0;
759
760     if (zh->lock_shadow)
761         zebra_lock_destroy (zh->lock_shadow);
762     zh->lock_shadow = 0;
763
764     if (zh->res)
765     {
766         char fname[512];
767         const char *lock_area = res_get (zh->res, "lockDir");
768         
769         if (!lock_area && zh->path_reg)
770             res_set (zh->res, "lockDir", zh->path_reg);
771         sprintf (fname, "norm.%s.LCK", zh->reg_name);
772         zh->lock_normal =
773             zebra_lock_create (res_get(zh->res, "lockDir"), fname);
774         
775         sprintf (fname, "shadow.%s.LCK", zh->reg_name);
776         zh->lock_shadow =
777             zebra_lock_create (res_get(zh->res, "lockDir"), fname);
778
779         if (!zh->lock_normal || !zh->lock_shadow)
780         {
781             if (zh->lock_normal)
782             {
783                 zebra_lock_destroy(zh->lock_normal);
784                 zh->lock_normal = 0;
785             }
786             if (zh->lock_shadow)
787             {
788                 zebra_lock_destroy(zh->lock_shadow);
789                 zh->lock_shadow = 0;
790             }
791             zebra_close_res(zh);
792         }
793     }
794     if (zh->res)
795     {
796         int approx = 0;
797         if (res_get_int(zh->res, "estimatehits", &approx) == ZEBRA_OK)
798             zebra_set_approx_limit(zh, approx);
799     }
800     if (zh->res)
801     {
802         if (res_get_int(zh->res, "staticrank", &zh->m_staticrank) == ZEBRA_OK)
803             yaz_log(YLOG_LOG, "static rank set and is %d", zh->m_staticrank);
804     }
805     if (zh->res)
806     {
807         if (res_get_int(zh->res, "segment", &zh->m_segment_indexing) == 
808             ZEBRA_OK)
809         {
810             yaz_log(YLOG_DEBUG, "segment indexing set and is %d",
811                     zh->m_segment_indexing);
812         }
813     }
814 }
815
816 void map_basenames_func (void *vp, const char *name, const char *value)
817 {
818     struct map_baseinfo *p = (struct map_baseinfo *) vp;
819     int i, no;
820     char fromdb[128], todb[8][128];
821
822     assert(value);
823     assert(name);
824     assert(vp);
825     
826     no =
827         sscanf (value, "%127s %127s %127s %127s %127s %127s %127s %127s %127s",
828                 fromdb, todb[0], todb[1], todb[2], todb[3], todb[4],
829                 todb[5], todb[6], todb[7]);
830     if (no < 2)
831         return ;
832     no--;
833     for (i = 0; i<p->num_bases; i++)
834         if (p->basenames[i] && !STRCASECMP (p->basenames[i], fromdb))
835         {
836             p->basenames[i] = 0;
837             for (i = 0; i < no; i++)
838             {
839                 if (p->new_num_bases == p->new_num_max)
840                     return;
841                 p->new_basenames[(p->new_num_bases)++] = 
842                     nmem_strdup (p->mem, todb[i]);
843             }
844             return;
845         }
846 }
847
848 int zebra_select_default_database(ZebraHandle zh)
849 {
850     if (!zh->res)
851     {
852         /* no database has been selected - so we select based on
853            resource setting (including group)
854         */
855         const char *group = res_get(zh->session_res, "group");
856         const char *v = res_get_prefix(zh->session_res,
857                                        "database", group, "Default");
858         return zebra_select_database(zh, v);
859     }
860     return 0;
861 }
862
863 void map_basenames (ZebraHandle zh, ODR stream,
864                     int *num_bases, char ***basenames)
865 {
866     struct map_baseinfo info;
867     struct map_baseinfo *p = &info;
868     int i;
869     ASSERTZH;
870     yaz_log(log_level, "map_basenames ");
871     assert(stream);
872
873     info.zh = zh;
874
875     info.num_bases = *num_bases;
876     info.basenames = *basenames;
877     info.new_num_max = 128;
878     info.new_num_bases = 0;
879     info.new_basenames = (char **)
880         odr_malloc (stream, sizeof(*info.new_basenames) * info.new_num_max);
881     info.mem = stream->mem;
882
883     res_trav (zh->session_res, "mapdb", &info, map_basenames_func);
884     
885     for (i = 0; i<p->num_bases; i++)
886         if (p->basenames[i] && p->new_num_bases < p->new_num_max)
887         {
888             p->new_basenames[(p->new_num_bases)++] = 
889                 nmem_strdup (p->mem, p->basenames[i]);
890         }
891     *num_bases = info.new_num_bases;
892     *basenames = info.new_basenames;
893     for (i = 0; i<*num_bases; i++)
894         yaz_log (YLOG_DEBUG, "base %s", (*basenames)[i]);
895 }
896
897 ZEBRA_RES zebra_select_database (ZebraHandle zh, const char *basename)
898 {
899     ZEBRA_CHECK_HANDLE(zh);
900
901     yaz_log(log_level, "zebra_select_database %s",basename);
902     assert(basename);
903     return zebra_select_databases (zh, 1, &basename);
904 }
905
906 ZEBRA_RES zebra_select_databases (ZebraHandle zh, int num_bases,
907                                   const char **basenames)
908 {
909     int i;
910     const char *cp;
911     int len = 0;
912     char *new_reg = 0;
913
914     ZEBRA_CHECK_HANDLE(zh);
915     assert(basenames);
916
917     yaz_log(log_level, "zebra_select_databases n=%d [0]=%s",
918                     num_bases,basenames[0]);
919     zh->errCode = 0;
920     
921     if (num_bases < 1)
922     {
923         zh->errCode = YAZ_BIB1_COMBI_OF_SPECIFIED_DATABASES_UNSUPP;
924         return ZEBRA_FAIL;
925     }
926
927     /* Check if the user has access to all databases (Seb) */
928     /* You could argue that this should happen later, after we have
929      * determined that the database(s) exist. */
930     if (zh->dbaccesslist) {
931         for (i = 0; i < num_bases; i++) {
932             const char *db = basenames[i];
933             char *p, *pp;
934             for (p = zh->dbaccesslist; p && *p; p = pp) {
935                 int len;
936                 if ((pp = strchr(p, '+'))) {
937                     len = pp - p;
938                     pp++;
939                 }
940                 else
941                     len = strlen(p);
942                 if (len == strlen(db) && !strncmp(db, p, len))
943                     break;
944             }
945             if (!p) {
946                 zh->errCode = YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED;
947                 return ZEBRA_FAIL;
948             }
949         }
950     }
951
952     for (i = 0; i < zh->num_basenames; i++)
953         xfree(zh->basenames[i]);
954     xfree(zh->basenames);
955     
956     zh->num_basenames = num_bases;
957     zh->basenames = xmalloc(zh->num_basenames * sizeof(*zh->basenames));
958     for (i = 0; i < zh->num_basenames; i++)
959         zh->basenames[i] = xstrdup (basenames[i]);
960
961     cp = strrchr(basenames[0], '/');
962     if (cp)
963     {
964         len = cp - basenames[0];
965         new_reg = xmalloc(len + 1);
966         memcpy (new_reg, basenames[0], len);
967         new_reg[len] = '\0';
968     }
969     else
970         new_reg = xstrdup ("");
971     for (i = 1; i<num_bases; i++)
972     {
973         const char *cp1;
974
975         cp1 = strrchr (basenames[i], '/');
976         if (cp)
977         {
978             if (!cp1)
979             {
980                 zh->errCode = YAZ_BIB1_COMBI_OF_SPECIFIED_DATABASES_UNSUPP;
981                 return -1;
982             }
983             if (len != cp1 - basenames[i] ||
984                 memcmp (basenames[i], new_reg, len))
985             {
986                 zh->errCode = YAZ_BIB1_COMBI_OF_SPECIFIED_DATABASES_UNSUPP;
987                 return -1;
988             }
989         }
990         else
991         {
992             if (cp1)
993             {
994                 zh->errCode = YAZ_BIB1_COMBI_OF_SPECIFIED_DATABASES_UNSUPP;
995                 return ZEBRA_FAIL;
996             }
997         }
998     }
999     zebra_select_register (zh, new_reg);
1000     xfree(new_reg);
1001     if (!zh->res)
1002     {
1003         zh->errCode = YAZ_BIB1_DATABASE_UNAVAILABLE;
1004         return ZEBRA_FAIL;
1005     }
1006     if (!zh->lock_normal || !zh->lock_shadow)
1007     {
1008         zh->errCode = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1009         return ZEBRA_FAIL;
1010     }
1011     return ZEBRA_OK;
1012 }
1013
1014 ZEBRA_RES zebra_set_approx_limit(ZebraHandle zh, zint approx_limit)
1015 {
1016     if (approx_limit == 0)
1017         approx_limit = DEFAULT_APPROX_LIMIT;
1018     zh->approx_limit = approx_limit;
1019     return ZEBRA_OK;
1020 }
1021
1022 void zebra_set_partial_result(ZebraHandle zh)
1023 {
1024     zh->partial_result = 1;
1025 }
1026
1027
1028 ZEBRA_RES zebra_set_break_handler(ZebraHandle zh,
1029                                   int (*f)(void *client_data),
1030                                   void *client_data)
1031 {
1032     zh->break_handler_func = f;
1033     zh->break_handler_data = client_data;
1034     return ZEBRA_OK;
1035 }
1036
1037 ZEBRA_RES zebra_search_RPN_x(ZebraHandle zh, ODR o, Z_RPNQuery *query,
1038                              const char *setname, zint *hits,
1039                              int *estimated_hit_count,
1040                              int *partial_resultset)
1041 {
1042     ZEBRA_RES r;
1043     
1044     ZEBRA_CHECK_HANDLE(zh);
1045
1046     assert(o);
1047     assert(query);
1048     assert(hits);
1049     assert(setname);
1050     yaz_log(log_level, "zebra_search_rpn");
1051
1052     zh->partial_result = 0;
1053
1054     if (zebra_begin_read(zh) == ZEBRA_FAIL)
1055         return ZEBRA_FAIL;
1056
1057     r = resultSetAddRPN(zh, odr_extract_mem(o), query, 
1058                         zh->num_basenames, zh->basenames, setname,
1059                         hits, estimated_hit_count);
1060
1061     *partial_resultset = zh->partial_result;
1062     zebra_end_read(zh);
1063     return r;
1064 }
1065
1066 ZEBRA_RES zebra_search_RPN(ZebraHandle zh, ODR o, Z_RPNQuery *query,
1067                            const char *setname, zint *hits)
1068 {
1069     int estimated_hit_count;
1070     int partial_resultset;
1071     return zebra_search_RPN_x(zh, o, query, setname, hits,
1072                               &estimated_hit_count,
1073                               &partial_resultset);
1074 }
1075
1076 ZEBRA_RES zebra_records_retrieve(ZebraHandle zh, ODR stream,
1077                                  const char *setname,
1078                                  Z_RecordComposition *comp,
1079                                  const Odr_oid *input_format, int num_recs,
1080                                  ZebraRetrievalRecord *recs)
1081 {
1082     ZebraMetaRecord *poset;
1083     int i;
1084     ZEBRA_RES ret = ZEBRA_OK;
1085     zint *pos_array;
1086
1087     ZEBRA_CHECK_HANDLE(zh);
1088     assert(stream);
1089     assert(setname);
1090     assert(recs);
1091     assert(num_recs>0);
1092
1093     yaz_log(log_level, "zebra_records_retrieve n=%d", num_recs);
1094
1095     if (!zh->res)
1096     {
1097         zebra_setError(zh, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST,
1098                        setname);
1099         return ZEBRA_FAIL;
1100     }
1101     
1102     if (zebra_begin_read (zh) == ZEBRA_FAIL)
1103         return ZEBRA_FAIL;
1104
1105     pos_array = (zint *) xmalloc(num_recs * sizeof(*pos_array));
1106     for (i = 0; i<num_recs; i++)
1107         pos_array[i] = recs[i].position;
1108     poset = zebra_meta_records_create(zh, setname, num_recs, pos_array);
1109     if (!poset)
1110     {
1111         yaz_log (YLOG_DEBUG, "zebraPosSetCreate error");
1112         zebra_setError(zh, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST,
1113                        setname);
1114         ret = ZEBRA_FAIL;
1115     }
1116     else
1117     {
1118         for (i = 0; i<num_recs; i++)
1119         {
1120             if (poset[i].term)
1121             {
1122                 recs[i].errCode = 0;
1123                 recs[i].format = yaz_oid_recsyn_sutrs;
1124                 recs[i].len = strlen(poset[i].term);
1125                 recs[i].buf = poset[i].term;
1126                 recs[i].base = poset[i].db;
1127             }
1128             else if (poset[i].sysno)
1129             {
1130                 char *buf;
1131                 int len = 0;
1132                 zebra_snippets *hit_snippet = zebra_snippets_create();
1133
1134                 /* we disable hit snippets for now. It does not work well
1135                  and it slows retrieval down a lot */
1136 #if 0
1137                 zebra_snippets_hit_vector(zh, setname, poset[i].sysno, 
1138                                           hit_snippet);
1139 #endif
1140                 recs[i].errCode =
1141                     zebra_record_fetch(zh, poset[i].sysno, poset[i].score,
1142                                        hit_snippet,
1143                                        stream, input_format, comp,
1144                                        &recs[i].format, &buf, &len,
1145                                        &recs[i].base, &recs[i].errString);
1146                 
1147                 recs[i].len = len;
1148                 if (len > 0)
1149                 {
1150                     recs[i].buf = (char*) odr_malloc(stream, len);
1151                     memcpy(recs[i].buf, buf, len);
1152                 }
1153                 else
1154                     recs[i].buf = buf;
1155                 recs[i].score = poset[i].score;
1156                 recs[i].sysno = poset[i].sysno;
1157                 zebra_snippets_destroy(hit_snippet);
1158             }
1159             else
1160             {
1161                 /* only need to set it once */
1162                 if (pos_array[i] < zh->approx_limit && ret == ZEBRA_OK)
1163                 {
1164                     zebra_setError_zint(zh,
1165                                         YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE,
1166                                         pos_array[i]);
1167                     ret = ZEBRA_FAIL;
1168                     break;
1169                 }
1170                 recs[i].buf = 0;  /* no record and no error issued */
1171                 recs[i].len = 0;
1172                 recs[i].errCode = 0;
1173                 recs[i].format = 0;
1174                 recs[i].sysno = 0;
1175             }
1176         }
1177         zebra_meta_records_destroy(zh, poset, num_recs);
1178     }
1179     zebra_end_read (zh);
1180     xfree(pos_array);
1181     return ret;
1182 }
1183
1184 ZEBRA_RES zebra_scan_PQF(ZebraHandle zh, ODR stream, const char *query,
1185                          int *position,
1186                          int *num_entries, ZebraScanEntry **entries,
1187                          int *is_partial,
1188                          const char *setname)
1189 {
1190     YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
1191     Z_AttributesPlusTerm *zapt;
1192     Odr_oid *attributeSet;
1193     ZEBRA_RES res;
1194     
1195     if (!(zapt = yaz_pqf_scan(pqf_parser, stream, &attributeSet, query)))
1196     {
1197         res = ZEBRA_FAIL;
1198         zh->errCode = YAZ_BIB1_SCAN_MALFORMED_SCAN;
1199     }
1200     else
1201     {
1202         res = zebra_scan(zh, stream, zapt, yaz_oid_attset_bib_1,
1203                          position, num_entries, entries, is_partial,
1204                          setname);
1205     }
1206     yaz_pqf_destroy (pqf_parser);
1207     return res;
1208 }
1209
1210 ZEBRA_RES zebra_scan(ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
1211                      const Odr_oid *attributeset,
1212                      int *position,
1213                      int *num_entries, ZebraScanEntry **entries,
1214                      int *is_partial,
1215                      const char *setname)
1216 {
1217     ZEBRA_RES res;
1218     RSET limit_rset = 0;
1219
1220     ZEBRA_CHECK_HANDLE(zh);
1221
1222     assert(stream);
1223     assert(zapt);
1224     assert(position);
1225     assert(num_entries);
1226     assert(is_partial);
1227     assert(entries);
1228     yaz_log(log_level, "zebra_scan");
1229
1230     if (zebra_begin_read (zh) == ZEBRA_FAIL)
1231     {
1232         *entries = 0;
1233         *num_entries = 0;
1234         return ZEBRA_FAIL;
1235     }
1236     if (setname)
1237     {
1238         limit_rset = resultSetRef(zh, setname);
1239         if (!limit_rset)
1240         {
1241             zebra_setError(zh, 
1242                            YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST,
1243                            setname);
1244             zebra_end_read (zh);
1245             return ZEBRA_FAIL;
1246         }
1247     }
1248     res = rpn_scan(zh, stream, zapt, attributeset,
1249                    zh->num_basenames, zh->basenames, position,
1250                    num_entries, entries, is_partial, limit_rset);
1251     zebra_end_read(zh);
1252     return res;
1253 }
1254
1255 ZEBRA_RES zebra_sort (ZebraHandle zh, ODR stream,
1256                       int num_input_setnames, const char **input_setnames,
1257                       const char *output_setname,
1258                       Z_SortKeySpecList *sort_sequence,
1259                       int *sort_status)
1260 {
1261     ZEBRA_RES res;
1262     ZEBRA_CHECK_HANDLE(zh);
1263     assert(stream);
1264     assert(num_input_setnames>0);
1265     assert(input_setnames);
1266     assert(sort_sequence);
1267     assert(sort_status);
1268     yaz_log(log_level, "zebra_sort");
1269
1270     if (zebra_begin_read(zh) == ZEBRA_FAIL)
1271         return ZEBRA_FAIL;
1272     res = resultSetSort(zh, stream->mem, num_input_setnames, input_setnames,
1273                         output_setname, sort_sequence, sort_status);
1274     zebra_end_read(zh);
1275     return res;
1276 }
1277
1278 int zebra_deleteResultSet(ZebraHandle zh, int function,
1279                           int num_setnames, char **setnames,
1280                           int *statuses)
1281 {
1282     int i, status;
1283     ASSERTZH;
1284     assert(statuses);
1285     yaz_log(log_level, "zebra_deleteResultSet n=%d",num_setnames);
1286
1287     if (zebra_begin_read(zh))
1288         return Z_DeleteStatus_systemProblemAtTarget;
1289     switch (function)
1290     {
1291     case Z_DeleteResultSetRequest_list:
1292         assert(num_setnames>0);
1293         assert(setnames);
1294         resultSetDestroy (zh, num_setnames, setnames, statuses);
1295         break;
1296     case Z_DeleteResultSetRequest_all:
1297         resultSetDestroy (zh, -1, 0, statuses);
1298         break;
1299     }
1300     zebra_end_read (zh);
1301     status = Z_DeleteStatus_success;
1302     for (i = 0; i<num_setnames; i++)
1303         if (statuses[i] == Z_DeleteStatus_resultSetDidNotExist)
1304             status = statuses[i];
1305     return status;
1306 }
1307
1308 int zebra_errCode (ZebraHandle zh)
1309 {
1310     if (zh)
1311     {
1312         yaz_log(log_level, "zebra_errCode: %d",zh->errCode);
1313         return zh->errCode;
1314     }
1315     yaz_log(log_level, "zebra_errCode: o");
1316     return 0; 
1317 }
1318
1319 const char *zebra_errString (ZebraHandle zh)
1320 {
1321     const char *e = 0;
1322     if (zh)
1323         e= diagbib1_str (zh->errCode);
1324     yaz_log(log_level, "zebra_errString: %s",e);
1325     return e;
1326 }
1327
1328 char *zebra_errAdd (ZebraHandle zh)
1329 {
1330     char *a = 0;
1331     if (zh)
1332         a= zh->errString;
1333     yaz_log(log_level, "zebra_errAdd: %s",a);
1334     return a;
1335 }
1336
1337 ZEBRA_RES zebra_auth (ZebraHandle zh, const char *user, const char *pass)
1338 {
1339     const char *p;
1340     const char *astring;
1341     char u[40];
1342     ZebraService zs;
1343
1344     ZEBRA_CHECK_HANDLE(zh);
1345
1346     zs = zh->service;
1347     
1348     sprintf(u, "perm.%.30s", user ? user : "anonymous");
1349     p = res_get(zs->global_res, u);
1350     xfree(zh->user_perm);
1351     zh->user_perm = xstrdup(p ? p : "r");
1352
1353     /* Determine database access list */
1354     astring = res_get(zs->dbaccess, user ? user : "anonymous");
1355     if (astring)
1356         zh->dbaccesslist = xstrdup(astring);
1357     else
1358         zh->dbaccesslist = 0;
1359
1360     /* users that don't require a password .. */
1361     if (zh->user_perm && strchr(zh->user_perm, 'a'))
1362         return ZEBRA_OK;
1363     
1364     if (!zs->passwd_db || !passwd_db_auth (zs->passwd_db, user, pass))
1365         return ZEBRA_OK;
1366     return ZEBRA_FAIL;
1367 }
1368
1369 ZEBRA_RES zebra_admin_import_begin (ZebraHandle zh, const char *database,
1370                                const char *record_type)
1371 {
1372     yaz_log(log_level, "zebra_admin_import_begin db=%s rt=%s", 
1373                      database, record_type);
1374     if (zebra_select_database(zh, database) == ZEBRA_FAIL)
1375         return ZEBRA_FAIL;
1376     return zebra_begin_trans(zh, 1);
1377 }
1378
1379 ZEBRA_RES zebra_admin_import_end (ZebraHandle zh)
1380 {
1381     ZEBRA_CHECK_HANDLE(zh);
1382     yaz_log(log_level, "zebra_admin_import_end");
1383     return zebra_end_trans(zh);
1384 }
1385
1386 ZEBRA_RES zebra_admin_import_segment (ZebraHandle zh, Z_Segment *segment)
1387 {
1388     ZEBRA_RES res = ZEBRA_OK;
1389     zint sysno;
1390     int i;
1391     ZEBRA_CHECK_HANDLE(zh);
1392     yaz_log(log_level, "zebra_admin_import_segment");
1393
1394     for (i = 0; i<segment->num_segmentRecords; i++)
1395     {
1396         Z_NamePlusRecord *npr = segment->segmentRecords[i];
1397
1398         if (npr->which == Z_NamePlusRecord_intermediateFragment)
1399         {
1400             Z_FragmentSyntax *fragment = npr->u.intermediateFragment;
1401             if (fragment->which == Z_FragmentSyntax_notExternallyTagged)
1402             {
1403                 Odr_oct *oct = fragment->u.notExternallyTagged;
1404                 sysno = 0;
1405                 
1406                 if (zebra_update_record(
1407                         zh, 
1408                         action_update,
1409                         0, /* record Type */
1410                         &sysno,
1411                         0, /* match */
1412                         0, /* fname */
1413                         (const char *) oct->buf, oct->len) == ZEBRA_FAIL)
1414                     res = ZEBRA_FAIL;
1415             }
1416         }
1417     }
1418     return res;
1419 }
1420
1421 int delete_w_handle(const char *info, void *handle)
1422 {
1423     ZebraHandle zh = (ZebraHandle) handle;
1424     ISAM_P pos;
1425     ASSERTZH;
1426
1427     if (*info == sizeof(pos))
1428     {
1429         memcpy (&pos, info+1, sizeof(pos));
1430         isamb_unlink(zh->reg->isamb, pos);
1431     }
1432     return 0;
1433 }
1434
1435 static int delete_SU_handle(void *handle, int ord)
1436 {
1437     ZebraHandle zh = (ZebraHandle) handle;
1438     char ord_buf[20];
1439     int ord_len;
1440
1441     ord_len = key_SU_encode (ord, ord_buf);
1442     ord_buf[ord_len] = '\0';
1443
1444     assert (zh->reg->isamb);
1445     dict_delete_subtree(zh->reg->dict, ord_buf,
1446                         zh, delete_w_handle);
1447     return 0;
1448 }
1449
1450 ZEBRA_RES zebra_drop_database(ZebraHandle zh, const char *db)
1451 {
1452     ZEBRA_RES ret = ZEBRA_OK;
1453
1454     yaz_log(log_level, "zebra_drop_database %s", db);
1455     ZEBRA_CHECK_HANDLE(zh);
1456
1457     if (zebra_select_database (zh, db) == ZEBRA_FAIL)
1458         return ZEBRA_FAIL;
1459     if (zebra_begin_trans (zh, 1) == ZEBRA_FAIL)
1460         return ZEBRA_FAIL;
1461     if (zh->reg->isamb)
1462     {
1463         int db_ord;
1464         if (zebraExplain_curDatabase (zh->reg->zei, db))
1465         {
1466             zebra_setError(zh, YAZ_BIB1_DATABASE_DOES_NOT_EXIST, db);
1467             ret = ZEBRA_FAIL;
1468         }
1469         else
1470         {
1471             db_ord = zebraExplain_get_database_ord(zh->reg->zei);
1472             dict_delete_subtree_ord(zh->reg->matchDict, db_ord,
1473                                     0 /* handle */, 0 /* func */);
1474             zebraExplain_trav_ord(zh->reg->zei, zh, delete_SU_handle);
1475             zebraExplain_removeDatabase(zh->reg->zei, zh);
1476             zebra_remove_file_match(zh);
1477         }
1478     }
1479     else
1480     {
1481         yaz_log(YLOG_WARN, "drop database only supported for isam:b");
1482         zebra_setError(zh, YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED,
1483                        "drop database only supported for isam:b");
1484         ret = ZEBRA_FAIL;
1485     }
1486     if (zebra_end_trans (zh) != ZEBRA_OK)
1487     {
1488         yaz_log(YLOG_WARN, "zebra_end_trans failed");
1489         ret = ZEBRA_FAIL;
1490     }
1491     return ret;
1492 }
1493
1494 ZEBRA_RES zebra_create_database (ZebraHandle zh, const char *db)
1495 {
1496     yaz_log(log_level, "zebra_create_database %s", db);
1497     ZEBRA_CHECK_HANDLE(zh);
1498     assert(db);
1499
1500     if (zebra_select_database (zh, db) == ZEBRA_FAIL)
1501         return ZEBRA_FAIL;
1502     if (zebra_begin_trans (zh, 1))
1503         return ZEBRA_FAIL;
1504
1505     /* announce database */
1506     if (zebraExplain_newDatabase (zh->reg->zei, db, 0 
1507                                   /* explainDatabase */))
1508     {
1509         if (zebra_end_trans (zh) != ZEBRA_OK)
1510         {
1511             yaz_log(YLOG_WARN, "zebra_end_trans failed");
1512         }
1513         zebra_setError(zh, YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED, db);
1514         return ZEBRA_FAIL;
1515     }
1516     return zebra_end_trans (zh);
1517 }
1518
1519 int zebra_string_norm(ZebraHandle zh, unsigned reg_id,
1520                       const char *input_str, int input_len,
1521                       char *output_str, int output_len)
1522 {
1523     WRBUF wrbuf;
1524     ASSERTZH;
1525     assert(input_str);
1526     assert(output_str);
1527     yaz_log(log_level, "zebra_string_norm ");
1528
1529     if (!zh->reg->zebra_maps)
1530         return -1;
1531     wrbuf = zebra_replace(zh->reg->zebra_maps, reg_id, "",
1532                           input_str, input_len);
1533     if (!wrbuf)
1534         return -2;
1535     if (wrbuf_len(wrbuf) >= output_len)
1536         return -3;
1537     if (wrbuf_len(wrbuf))
1538         memcpy (output_str, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
1539     output_str[wrbuf_len(wrbuf)] = '\0';
1540     return wrbuf_len(wrbuf);
1541 }
1542
1543 /** \brief set register state (state*.LCK)
1544     \param zh Zebra handle
1545     \param val state
1546     \param seqno sequence number
1547     
1548     val is one of:
1549     d=writing to shadow(shadow enabled); writing to register (shadow disabled)
1550     o=reading only
1551     c=commit (writing to register, reading from shadow, shadow mode only)
1552 */
1553 static void zebra_set_state (ZebraHandle zh, int val, int seqno)
1554 {
1555     char state_fname[256];
1556     char *fname;
1557     long p = getpid();
1558     FILE *f;
1559     ASSERTZH;
1560     yaz_log(log_level, "zebra_set_state v=%d seq=%d", val, seqno);
1561
1562     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1563     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1564     f = fopen (fname, "w");
1565
1566     yaz_log (YLOG_DEBUG, "zebra_set_state: %c %d %ld", val, seqno, p);
1567     fprintf (f, "%c %d %ld\n", val, seqno, p);
1568     fclose (f);
1569     xfree(fname);
1570 }
1571
1572 static void zebra_get_state (ZebraHandle zh, char *val, int *seqno)
1573 {
1574     char state_fname[256];
1575     char *fname;
1576     FILE *f;
1577
1578     ASSERTZH;
1579     yaz_log(log_level, "zebra_get_state ");
1580
1581     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1582     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1583     f = fopen (fname, "r");
1584     *val = 'o';
1585     *seqno = 0;
1586
1587     if (f)
1588     {
1589         fscanf (f, "%c %d", val, seqno);
1590         fclose (f);
1591     }
1592     xfree(fname);
1593 }
1594
1595 ZEBRA_RES zebra_begin_read (ZebraHandle zh)
1596 {
1597     return zebra_begin_trans(zh, 0);
1598 }
1599
1600 ZEBRA_RES zebra_end_read (ZebraHandle zh)
1601 {
1602     return zebra_end_trans(zh);
1603 }
1604
1605 static void read_res_for_transaction(ZebraHandle zh)
1606 {
1607     const char *group = res_get(zh->res, "group");
1608     const char *v;
1609     /* FIXME - do we still use groups ?? */
1610     
1611     zh->m_group = group;
1612     v = res_get_prefix(zh->res, "followLinks", group, "1");
1613     zh->m_follow_links = atoi(v);
1614
1615     zh->m_record_id = res_get_prefix(zh->res, "recordId", group, 0);
1616     zh->m_record_type = res_get_prefix(zh->res, "recordType", group, 0);
1617
1618     v = res_get_prefix(zh->res, "storeKeys", group, "1");
1619     zh->m_store_keys = atoi(v);
1620
1621     v = res_get_prefix(zh->res, "storeData", group, "1");
1622     zh->m_store_data = atoi(v);
1623
1624     v = res_get_prefix(zh->res, "explainDatabase", group, "0");
1625     zh->m_explain_database = atoi(v);
1626
1627     v = res_get_prefix(zh->res, "openRW", group, "1");
1628     zh->m_flag_rw = atoi(v);
1629
1630     v = res_get_prefix(zh->res, "fileVerboseLimit", group, "1000");
1631     zh->m_file_verbose_limit = atoi(v);
1632 }
1633
1634 ZEBRA_RES zebra_begin_trans(ZebraHandle zh, int rw)
1635 {
1636     ZEBRA_CHECK_HANDLE(zh);
1637     zebra_select_default_database(zh);
1638     if (!zh->res)
1639     {
1640         zebra_setError(zh, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
1641                        "zebra_begin_trans: no database selected");
1642         return ZEBRA_FAIL;
1643     }
1644     ASSERTZHRES;
1645     yaz_log(log_level, "zebra_begin_trans rw=%d",rw);
1646
1647     if (zh->user_perm)
1648     {
1649         if (rw && !strchr(zh->user_perm, 'w'))
1650         {
1651             zebra_setError(
1652                 zh,
1653                 YAZ_BIB1_ES_PERMISSION_DENIED_ON_ES_CANNOT_MODIFY_OR_DELETE,
1654                 0);
1655             return ZEBRA_FAIL;
1656         }
1657     }
1658
1659     assert (zh->res);
1660     if (rw)
1661     {
1662         int seqno = 0;
1663         char val = '?';
1664         const char *rval = 0;
1665         
1666         (zh->trans_no++);
1667         if (zh->trans_w_no)
1668         {
1669             read_res_for_transaction(zh);
1670             return 0;
1671         }
1672         if (zh->trans_no != 1)
1673         {
1674             zebra_setError(zh, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
1675                            "zebra_begin_trans: no write trans within read");
1676             return ZEBRA_FAIL;
1677         }
1678         if (zh->reg)
1679         {
1680             resultSetInvalidate (zh);
1681             zebra_register_close(zh->service, zh->reg);
1682         }
1683         zh->trans_w_no = zh->trans_no;
1684
1685         zh->records_inserted = 0;
1686         zh->records_updated = 0;
1687         zh->records_deleted = 0;
1688         zh->records_processed = 0;
1689         zh->records_skipped = 0;
1690         
1691 #if HAVE_SYS_TIMES_H
1692         times (&zh->tms1);
1693 #endif
1694         /* lock */
1695         if (zh->shadow_enable)
1696             rval = res_get (zh->res, "shadow");
1697         
1698         if (rval)
1699         {
1700             zebra_lock_r(zh->lock_normal);
1701             zebra_lock_w(zh->lock_shadow);
1702         }
1703         else
1704         {
1705             zebra_lock_w(zh->lock_normal);
1706             zebra_lock_w(zh->lock_shadow);
1707         }
1708         zebra_get_state (zh, &val, &seqno);
1709         if (val != 'o')
1710         {
1711             /* either we didn't finish commit or shadow is dirty */
1712             if (!rval)
1713             {
1714                 yaz_log(YLOG_WARN, "previous transaction did not finish "
1715                         "(shadow disabled)");
1716             }
1717             zebra_unlock (zh->lock_shadow);
1718             zebra_unlock (zh->lock_normal);
1719             if (zebra_commit (zh))
1720             {
1721                 zh->trans_no--;
1722                 zh->trans_w_no = 0;
1723                 return ZEBRA_FAIL;
1724             }
1725             if (rval)
1726             {
1727                 zebra_lock_r(zh->lock_normal);
1728                 zebra_lock_w(zh->lock_shadow);
1729             }
1730             else
1731             {
1732                 zebra_lock_w(zh->lock_normal);
1733                 zebra_lock_w(zh->lock_shadow);
1734             }
1735         }
1736
1737         zebra_set_state (zh, 'd', seqno);
1738         
1739         zh->reg = zebra_register_open(zh->service, zh->reg_name,
1740                                       1, rval ? 1 : 0, zh->res,
1741                                       zh->path_reg);
1742         if (zh->reg)
1743             zh->reg->seqno = seqno;
1744         else
1745         {
1746             zebra_set_state (zh, 'o', seqno);
1747             
1748             zebra_unlock (zh->lock_shadow);
1749             zebra_unlock (zh->lock_normal);
1750
1751             zh->trans_no--;
1752             zh->trans_w_no = 0;
1753
1754             zebra_setError(zh, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
1755                            "zebra_begin_trans: cannot open register");
1756             yaz_log(YLOG_FATAL, "%s", zh->errString);
1757             return ZEBRA_FAIL;
1758         }
1759         zebraExplain_curDatabase(zh->reg->zei, zh->basenames[0]);
1760     }
1761     else
1762     {
1763         int dirty = 0;
1764         char val;
1765         int seqno;
1766         
1767         (zh->trans_no)++;
1768         
1769         if (zh->trans_no != 1)
1770         {
1771             return zebra_flush_reg (zh);
1772         }
1773 #if HAVE_SYS_TIMES_H
1774         times (&zh->tms1);
1775 #endif
1776         if (!zh->res)
1777         {
1778             (zh->trans_no)--;
1779             zh->errCode = YAZ_BIB1_DATABASE_UNAVAILABLE;
1780             return ZEBRA_FAIL;
1781         }
1782         if (!zh->lock_normal || !zh->lock_shadow)
1783         {
1784             (zh->trans_no)--;
1785             zh->errCode = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1786             return ZEBRA_FAIL;
1787         }
1788         zebra_get_state (zh, &val, &seqno);
1789         if (val == 'd')
1790             val = 'o';
1791         
1792         if (!zh->reg)
1793             dirty = 1;
1794         else if (seqno != zh->reg->seqno)
1795         {
1796             yaz_log (YLOG_DEBUG, "reopen seqno cur/old %d/%d",
1797                      seqno, zh->reg->seqno);
1798             dirty = 1;
1799         }
1800         else if (zh->reg->last_val != val)
1801         {
1802             yaz_log (YLOG_DEBUG, "reopen last cur/old %d/%d",
1803                      val, zh->reg->last_val);
1804             dirty = 1;
1805         }
1806         if (!dirty)
1807             return ZEBRA_OK;
1808         
1809         if (val == 'c')
1810             zebra_lock_r (zh->lock_shadow);
1811         else
1812             zebra_lock_r (zh->lock_normal);
1813         
1814         if (zh->reg)
1815         {
1816             resultSetInvalidate (zh);
1817             zebra_register_close(zh->service, zh->reg);
1818         }
1819         zh->reg = zebra_register_open(zh->service, zh->reg_name,
1820                                       0, val == 'c' ? 1 : 0,
1821                                       zh->res, zh->path_reg);
1822         if (!zh->reg)
1823         {
1824             zebra_unlock (zh->lock_normal);
1825             zebra_unlock (zh->lock_shadow);
1826             zh->trans_no--;
1827             zh->errCode = YAZ_BIB1_DATABASE_UNAVAILABLE;
1828             return ZEBRA_FAIL;
1829         }
1830         zh->reg->last_val = val;
1831         zh->reg->seqno = seqno;
1832     }
1833     read_res_for_transaction(zh);
1834     return ZEBRA_OK;
1835 }
1836
1837 ZEBRA_RES zebra_end_trans (ZebraHandle zh)
1838 {
1839     ZebraTransactionStatus dummy;
1840
1841     yaz_log(log_level, "zebra_end_trans");
1842     ZEBRA_CHECK_HANDLE(zh);
1843     return zebra_end_transaction(zh, &dummy);
1844 }
1845
1846 ZEBRA_RES zebra_end_transaction (ZebraHandle zh, ZebraTransactionStatus *status)
1847 {
1848     char val;
1849     int seqno;
1850     const char *rval;
1851
1852     ZEBRA_CHECK_HANDLE(zh);
1853
1854     assert(status);
1855     yaz_log(log_level, "zebra_end_transaction");
1856
1857     status->processed = 0;
1858     status->inserted  = 0;
1859     status->updated   = 0;
1860     status->deleted   = 0;
1861     status->utime     = 0;
1862     status->stime     = 0;
1863
1864     if (!zh->res || !zh->reg)
1865     {
1866         zebra_setError(zh, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
1867                        "zebra_end_trans: no open transaction");
1868         return ZEBRA_FAIL;
1869     }
1870     if (zh->trans_no != zh->trans_w_no)
1871     {
1872         zh->trans_no--;
1873         if (zh->trans_no != 0)
1874             return ZEBRA_OK;
1875
1876         /* release read lock */
1877
1878         zebra_unlock (zh->lock_normal);
1879         zebra_unlock (zh->lock_shadow);
1880     }
1881     else
1882     {   /* release write lock */
1883         zh->trans_no--;
1884         zh->trans_w_no = 0;
1885         
1886         yaz_log (YLOG_DEBUG, "zebra_end_trans");
1887         rval = res_get (zh->res, "shadow");
1888         
1889         zebraExplain_runNumberIncrement (zh->reg->zei, 1);
1890         
1891         zebra_flush_reg (zh);
1892         
1893         resultSetInvalidate (zh);
1894
1895         zebra_register_close(zh->service, zh->reg);
1896         zh->reg = 0;
1897         
1898         yaz_log (YLOG_LOG, "Records: "ZINT_FORMAT" i/u/d "
1899                         ZINT_FORMAT"/"ZINT_FORMAT"/"ZINT_FORMAT, 
1900                  zh->records_processed, zh->records_inserted,
1901                  zh->records_updated, zh->records_deleted);
1902         
1903         status->processed = zh->records_processed;
1904         status->inserted = zh->records_inserted;
1905         status->updated = zh->records_updated;
1906         status->deleted = zh->records_deleted;
1907         
1908         zebra_get_state (zh, &val, &seqno);
1909         if (val != 'd')
1910         {
1911             BFiles bfs = bfs_create (rval, zh->path_reg);
1912             yaz_log (YLOG_DEBUG, "deleting shadow val=%c", val);
1913             bf_commitClean (bfs, rval);
1914             bfs_destroy (bfs);
1915         }
1916         if (!rval)
1917             seqno++;
1918         zebra_set_state (zh, 'o', seqno);
1919         
1920         zebra_unlock (zh->lock_shadow);
1921         zebra_unlock (zh->lock_normal);
1922         
1923     }
1924 #if HAVE_SYS_TIMES_H
1925     times (&zh->tms2);
1926     yaz_log (log_level, "user/system: %ld/%ld",
1927           (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1928           (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1929     
1930     status->utime = (long) (zh->tms2.tms_utime - zh->tms1.tms_utime);
1931     status->stime = (long) (zh->tms2.tms_stime - zh->tms1.tms_stime);
1932 #endif
1933     return ZEBRA_OK;
1934 }
1935
1936 ZEBRA_RES zebra_repository_update(ZebraHandle zh, const char *path)
1937 {
1938     ASSERTZH;
1939     assert(path);
1940     yaz_log (log_level, "updating %s", path);
1941
1942     if (zh->m_record_id && !strcmp (zh->m_record_id, "file"))
1943         return zebra_update_file_match(zh, path);
1944     else
1945         return zebra_update_from_path(zh, path);
1946 }
1947
1948 ZEBRA_RES zebra_repository_delete(ZebraHandle zh, const char *path)
1949 {
1950     ASSERTZH;
1951     assert(path);
1952     yaz_log (log_level, "deleting %s", path);
1953     return zebra_delete_from_path(zh, path);
1954 }
1955
1956 ZEBRA_RES zebra_repository_show(ZebraHandle zh, const char *path)
1957 {
1958     ASSERTZH;
1959     assert(path);
1960     yaz_log(log_level, "zebra_repository_show");
1961     repositoryShow (zh, path);
1962     return ZEBRA_OK;
1963 }
1964
1965 static ZEBRA_RES zebra_commit_ex(ZebraHandle zh, int clean_only)
1966 {
1967     int seqno;
1968     char val;
1969     const char *rval;
1970     BFiles bfs;
1971     ZEBRA_RES res = ZEBRA_OK;
1972
1973     ASSERTZH;
1974
1975     zebra_select_default_database(zh);
1976     if (!zh->res)
1977     {
1978         zh->errCode = YAZ_BIB1_DATABASE_UNAVAILABLE;
1979         return ZEBRA_FAIL;
1980     }
1981     rval = res_get(zh->res, "shadow");    
1982     if (!rval)
1983     {
1984         yaz_log (YLOG_WARN, "Cannot perform commit - No shadow area defined");
1985         return ZEBRA_OK;
1986     }
1987
1988     zebra_lock_w(zh->lock_normal);
1989     zebra_lock_r(zh->lock_shadow);
1990
1991     bfs = bfs_create(res_get (zh->res, "register"), zh->path_reg);
1992     if (!bfs)
1993     {
1994         zebra_unlock(zh->lock_shadow);
1995         zebra_unlock(zh->lock_normal);
1996         return ZEBRA_FAIL;
1997     }
1998     zebra_get_state(zh, &val, &seqno);
1999
2000     if (val == 'd')
2001     {
2002         /* shadow area is dirty and so we must throw it away */
2003         yaz_log(YLOG_WARN, "previous transaction didn't reach commit");
2004         clean_only = 1;
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(YLOG_DEBUG, "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