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