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