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