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