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