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