For estimated hit counts, Zebra returns resultSetStatus=estimtate as
[idzebra-moved-to-github.git] / index / zebraapi.c
1 /* $Id: zebraapi.c,v 1.243 2007-01-16 15:01:15 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 ZEBRA_RES zebra_search_RPN_x(ZebraHandle zh, ODR o, Z_RPNQuery *query,
1019                              const char *setname, zint *hits,
1020                              int *estimated_hit_count,
1021                              int *partial_resultset)
1022 {
1023     ZEBRA_RES r;
1024     
1025     ZEBRA_CHECK_HANDLE(zh);
1026
1027     assert(o);
1028     assert(query);
1029     assert(hits);
1030     assert(setname);
1031     yaz_log(log_level, "zebra_search_rpn");
1032
1033     if (zebra_begin_read(zh) == ZEBRA_FAIL)
1034         return ZEBRA_FAIL;
1035
1036     r = resultSetAddRPN(zh, odr_extract_mem(o), query, 
1037                         zh->num_basenames, zh->basenames, setname,
1038                         hits, estimated_hit_count, partial_resultset);
1039     zebra_end_read(zh);
1040     return r;
1041 }
1042
1043 ZEBRA_RES zebra_search_RPN(ZebraHandle zh, ODR o, Z_RPNQuery *query,
1044                            const char *setname, zint *hits)
1045 {
1046     int estimated_hit_count;
1047     int partial_resultset;
1048     return zebra_search_RPN_x(zh, o, query, setname, hits,
1049                               &estimated_hit_count,
1050                               &partial_resultset);
1051 }
1052
1053 ZEBRA_RES zebra_records_retrieve(ZebraHandle zh, ODR stream,
1054                                  const char *setname,
1055                                  Z_RecordComposition *comp,
1056                                  oid_value input_format, int num_recs,
1057                                  ZebraRetrievalRecord *recs)
1058 {
1059     ZebraMetaRecord *poset;
1060     int i;
1061     ZEBRA_RES ret = ZEBRA_OK;
1062     zint *pos_array;
1063
1064     ZEBRA_CHECK_HANDLE(zh);
1065     assert(stream);
1066     assert(setname);
1067     assert(recs);
1068     assert(num_recs>0);
1069
1070     yaz_log(log_level, "zebra_records_retrieve n=%d", num_recs);
1071
1072     if (!zh->res)
1073     {
1074         zebra_setError(zh, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST,
1075                        setname);
1076         return ZEBRA_FAIL;
1077     }
1078     
1079     if (zebra_begin_read (zh) == ZEBRA_FAIL)
1080         return ZEBRA_FAIL;
1081
1082     pos_array = (zint *) xmalloc(num_recs * sizeof(*pos_array));
1083     for (i = 0; i<num_recs; i++)
1084         pos_array[i] = recs[i].position;
1085     poset = zebra_meta_records_create(zh, setname, num_recs, pos_array);
1086     if (!poset)
1087     {
1088         yaz_log (YLOG_DEBUG, "zebraPosSetCreate error");
1089         zebra_setError(zh, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST,
1090                        setname);
1091         ret = ZEBRA_FAIL;
1092     }
1093     else
1094     {
1095         for (i = 0; i<num_recs; i++)
1096         {
1097             if (poset[i].term)
1098             {
1099                 recs[i].errCode = 0;
1100                 recs[i].format = VAL_SUTRS;
1101                 recs[i].len = strlen(poset[i].term);
1102                 recs[i].buf = poset[i].term;
1103                 recs[i].base = poset[i].db;
1104             }
1105             else if (poset[i].sysno)
1106             {
1107                 char *buf;
1108                 int len = 0;
1109                 zebra_snippets *hit_snippet = zebra_snippets_create();
1110
1111                 /* we disable hit snippets for now. It does not work well
1112                  and it slows retrieval down a lot */
1113 #if 0
1114                 zebra_snippets_hit_vector(zh, setname, poset[i].sysno, 
1115                                           hit_snippet);
1116 #endif
1117                 recs[i].errCode =
1118                     zebra_record_fetch(zh, poset[i].sysno, poset[i].score,
1119                                        hit_snippet,
1120                                        stream, input_format, comp,
1121                                        &recs[i].format, &buf, &len,
1122                                        &recs[i].base, &recs[i].errString);
1123                 
1124                 recs[i].len = len;
1125                 if (len > 0)
1126                 {
1127                     recs[i].buf = (char*) odr_malloc(stream, len);
1128                     memcpy(recs[i].buf, buf, len);
1129                 }
1130                 else
1131                     recs[i].buf = buf;
1132                 recs[i].score = poset[i].score;
1133                 recs[i].sysno = poset[i].sysno;
1134                 zebra_snippets_destroy(hit_snippet);
1135             }
1136             else
1137             {
1138                 /* only need to set it once */
1139                 if (pos_array[i] < zh->approx_limit && ret == ZEBRA_OK)
1140                 {
1141                     zebra_setError_zint(zh,
1142                                         YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE,
1143                                         pos_array[i]);
1144                     ret = ZEBRA_FAIL;
1145                     break;
1146                 }
1147                 recs[i].buf = 0;  /* no record and no error issued */
1148                 recs[i].len = 0;
1149                 recs[i].errCode = 0;
1150                 recs[i].format = VAL_NONE;
1151                 recs[i].sysno = 0;
1152             }
1153         }
1154         zebra_meta_records_destroy(zh, poset, num_recs);
1155     }
1156     zebra_end_read (zh);
1157     xfree(pos_array);
1158     return ret;
1159 }
1160
1161 ZEBRA_RES zebra_scan_PQF(ZebraHandle zh, ODR stream, const char *query,
1162                          int *position,
1163                          int *num_entries, ZebraScanEntry **entries,
1164                          int *is_partial,
1165                          const char *setname)
1166 {
1167     YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
1168     Z_AttributesPlusTerm *zapt;
1169     int *attributeSet;
1170     ZEBRA_RES res;
1171     
1172     if (!(zapt = yaz_pqf_scan(pqf_parser, stream, &attributeSet, query)))
1173     {
1174         res = ZEBRA_FAIL;
1175         zh->errCode = YAZ_BIB1_SCAN_MALFORMED_SCAN;
1176     }
1177     else
1178         res = zebra_scan(zh, stream, zapt, VAL_BIB1,
1179                          position, num_entries, entries, is_partial,
1180                          setname);
1181     yaz_pqf_destroy (pqf_parser);
1182     return res;
1183 }
1184
1185 ZEBRA_RES zebra_scan(ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
1186                      oid_value attributeset,
1187                      int *position,
1188                      int *num_entries, ZebraScanEntry **entries,
1189                      int *is_partial,
1190                      const char *setname)
1191 {
1192     ZEBRA_RES res;
1193     RSET limit_rset = 0;
1194
1195     ZEBRA_CHECK_HANDLE(zh);
1196
1197     assert(stream);
1198     assert(zapt);
1199     assert(position);
1200     assert(num_entries);
1201     assert(is_partial);
1202     assert(entries);
1203     yaz_log(log_level, "zebra_scan");
1204
1205     if (zebra_begin_read (zh) == ZEBRA_FAIL)
1206     {
1207         *entries = 0;
1208         *num_entries = 0;
1209         return ZEBRA_FAIL;
1210     }
1211     if (setname)
1212     {
1213         limit_rset = resultSetRef(zh, setname);
1214         if (!limit_rset)
1215         {
1216             zebra_setError(zh, 
1217                            YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST,
1218                            setname);
1219             zebra_end_read (zh);
1220             return ZEBRA_FAIL;
1221         }
1222     }
1223     res = rpn_scan(zh, stream, zapt, attributeset,
1224                    zh->num_basenames, zh->basenames, position,
1225                    num_entries, entries, is_partial, limit_rset);
1226     zebra_end_read(zh);
1227     return res;
1228 }
1229
1230 ZEBRA_RES zebra_sort (ZebraHandle zh, ODR stream,
1231                       int num_input_setnames, const char **input_setnames,
1232                       const char *output_setname,
1233                       Z_SortKeySpecList *sort_sequence,
1234                       int *sort_status)
1235 {
1236     ZEBRA_RES res;
1237     ZEBRA_CHECK_HANDLE(zh);
1238     assert(stream);
1239     assert(num_input_setnames>0);
1240     assert(input_setnames);
1241     assert(sort_sequence);
1242     assert(sort_status);
1243     yaz_log(log_level, "zebra_sort");
1244
1245     if (zebra_begin_read(zh) == ZEBRA_FAIL)
1246         return ZEBRA_FAIL;
1247     res = resultSetSort(zh, stream->mem, num_input_setnames, input_setnames,
1248                         output_setname, sort_sequence, sort_status);
1249     zebra_end_read(zh);
1250     return res;
1251 }
1252
1253 int zebra_deleteResultSet(ZebraHandle zh, int function,
1254                           int num_setnames, char **setnames,
1255                           int *statuses)
1256 {
1257     int i, status;
1258     ASSERTZH;
1259     assert(statuses);
1260     yaz_log(log_level, "zebra_deleteResultSet n=%d",num_setnames);
1261
1262     if (zebra_begin_read(zh))
1263         return Z_DeleteStatus_systemProblemAtTarget;
1264     switch (function)
1265     {
1266     case Z_DeleteResultSetRequest_list:
1267         assert(num_setnames>0);
1268         assert(setnames);
1269         resultSetDestroy (zh, num_setnames, setnames, statuses);
1270         break;
1271     case Z_DeleteResultSetRequest_all:
1272         resultSetDestroy (zh, -1, 0, statuses);
1273         break;
1274     }
1275     zebra_end_read (zh);
1276     status = Z_DeleteStatus_success;
1277     for (i = 0; i<num_setnames; i++)
1278         if (statuses[i] == Z_DeleteStatus_resultSetDidNotExist)
1279             status = statuses[i];
1280     return status;
1281 }
1282
1283 int zebra_errCode (ZebraHandle zh)
1284 {
1285     if (zh)
1286     {
1287         yaz_log(log_level, "zebra_errCode: %d",zh->errCode);
1288         return zh->errCode;
1289     }
1290     yaz_log(log_level, "zebra_errCode: o");
1291     return 0; 
1292 }
1293
1294 const char *zebra_errString (ZebraHandle zh)
1295 {
1296     const char *e = 0;
1297     if (zh)
1298         e= diagbib1_str (zh->errCode);
1299     yaz_log(log_level, "zebra_errString: %s",e);
1300     return e;
1301 }
1302
1303 char *zebra_errAdd (ZebraHandle zh)
1304 {
1305     char *a = 0;
1306     if (zh)
1307         a= zh->errString;
1308     yaz_log(log_level, "zebra_errAdd: %s",a);
1309     return a;
1310 }
1311
1312 ZEBRA_RES zebra_auth (ZebraHandle zh, const char *user, const char *pass)
1313 {
1314     const char *p;
1315     const char *astring;
1316     char u[40];
1317     ZebraService zs;
1318
1319     ZEBRA_CHECK_HANDLE(zh);
1320
1321     zs = zh->service;
1322     
1323     sprintf(u, "perm.%.30s", user ? user : "anonymous");
1324     p = res_get(zs->global_res, u);
1325     xfree(zh->user_perm);
1326     zh->user_perm = xstrdup(p ? p : "r");
1327
1328     /* Determine database access list */
1329     astring = res_get(zs->dbaccess, user ? user : "anonymous");
1330     if (astring)
1331         zh->dbaccesslist = xstrdup(astring);
1332     else
1333         zh->dbaccesslist = 0;
1334
1335     /* users that don't require a password .. */
1336     if (zh->user_perm && strchr(zh->user_perm, 'a'))
1337         return ZEBRA_OK;
1338     
1339     if (!zs->passwd_db || !passwd_db_auth (zs->passwd_db, user, pass))
1340         return ZEBRA_OK;
1341     return ZEBRA_FAIL;
1342 }
1343
1344 ZEBRA_RES zebra_admin_import_begin (ZebraHandle zh, const char *database,
1345                                const char *record_type)
1346 {
1347     yaz_log(log_level, "zebra_admin_import_begin db=%s rt=%s", 
1348                      database, record_type);
1349     if (zebra_select_database(zh, database) == ZEBRA_FAIL)
1350         return ZEBRA_FAIL;
1351     return zebra_begin_trans(zh, 1);
1352 }
1353
1354 ZEBRA_RES zebra_admin_import_end (ZebraHandle zh)
1355 {
1356     ZEBRA_CHECK_HANDLE(zh);
1357     yaz_log(log_level, "zebra_admin_import_end");
1358     return zebra_end_trans(zh);
1359 }
1360
1361 ZEBRA_RES zebra_admin_import_segment (ZebraHandle zh, Z_Segment *segment)
1362 {
1363     ZEBRA_RES res = ZEBRA_OK;
1364     zint sysno;
1365     int i;
1366     ZEBRA_CHECK_HANDLE(zh);
1367     yaz_log(log_level, "zebra_admin_import_segment");
1368
1369     for (i = 0; i<segment->num_segmentRecords; i++)
1370     {
1371         Z_NamePlusRecord *npr = segment->segmentRecords[i];
1372
1373         if (npr->which == Z_NamePlusRecord_intermediateFragment)
1374         {
1375             Z_FragmentSyntax *fragment = npr->u.intermediateFragment;
1376             if (fragment->which == Z_FragmentSyntax_notExternallyTagged)
1377             {
1378                 Odr_oct *oct = fragment->u.notExternallyTagged;
1379                 sysno = 0;
1380                 
1381                 if (zebra_update_record(zh, 
1382                                         0, /* record Type */
1383                                         &sysno,
1384                                         0, /* match */
1385                                         0, /* fname */
1386                                         (const char *) oct->buf, oct->len,
1387                                         0) == ZEBRA_FAIL)
1388                     res = ZEBRA_FAIL;
1389             }
1390         }
1391     }
1392     return res;
1393 }
1394
1395 ZEBRA_RES zebra_admin_exchange_record(ZebraHandle zh,
1396                                       const char *rec_buf,
1397                                       size_t rec_len,
1398                                       const char *recid_buf, size_t recid_len,
1399                                       int action)
1400     /* 1 = insert. Fail it already exists */
1401     /* 2 = replace. Fail it does not exist */
1402     /* 3 = delete. Fail if does not exist */
1403     /* 4 = update. Insert/replace */
1404 {
1405     ZEBRA_RES res;
1406     zint sysno = 0;
1407     char *rinfo = 0;
1408     char recid_z[256];
1409     int db_ord;
1410     ZEBRA_CHECK_HANDLE(zh);
1411     assert(action>0 && action <=4);
1412     assert(rec_buf);
1413
1414     yaz_log(log_level, "zebra_admin_exchange_record ac=%d", action);
1415
1416     if (!recid_buf || recid_len <= 0 || recid_len >= sizeof(recid_z))
1417     {
1418         zebra_setError(zh, YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED,
1419                        "no record ID or empty record ID");
1420         return ZEBRA_FAIL;
1421     }
1422
1423     memcpy (recid_z, recid_buf, recid_len);
1424     recid_z[recid_len] = 0;
1425
1426     if (zebra_begin_trans(zh, 1) == ZEBRA_FAIL)
1427         return ZEBRA_FAIL;
1428
1429     db_ord = zebraExplain_get_database_ord(zh->reg->zei);
1430     rinfo = dict_lookup_ord(zh->reg->matchDict, db_ord, recid_z);
1431     if (rinfo)
1432     {
1433         if (action == 1)  /* fail if insert */
1434         {
1435             if (zebra_end_trans(zh) != ZEBRA_OK)
1436                 yaz_log(YLOG_WARN, "zebra_end_trans failed");
1437             zebra_setError(zh, YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED,
1438                            "Cannot insert record: already exist");
1439             return ZEBRA_FAIL;
1440         }
1441
1442         memcpy (&sysno, rinfo+1, sizeof(sysno));
1443     }
1444     else
1445     {
1446         if (action == 2 || action == 3) /* fail if delete or update */
1447         {
1448             if (zebra_end_trans(zh) != ZEBRA_OK)
1449                 yaz_log(YLOG_WARN, "zebra_end_trans failed");
1450             zebra_setError(zh, YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED,
1451                            "Cannot delete/update record: does not exist");
1452             return ZEBRA_FAIL;
1453         }
1454         action = 1;  /* make it an insert (if it's an update).. */
1455     }
1456     res = zebra_buffer_extract_record(zh, rec_buf, rec_len,
1457                                       action == 3 ? 1 : 0 /* delete flag */,
1458                                       0, /* test mode */
1459                                       0, /* recordType */
1460                                       &sysno, 
1461                                       0, /* match */
1462                                       0, /* fname */
1463                                       0, /* force update */
1464                                       1  /* allow update */
1465         );
1466     if (res == ZEBRA_FAIL)
1467     {
1468         zebra_setError(zh, YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED,
1469                        "Unable to parse record");
1470     }
1471     if (action == 1)
1472     {
1473         dict_insert_ord(zh->reg->matchDict, db_ord, recid_z,
1474                         sizeof(sysno), &sysno);
1475     }
1476     else if (action == 3)
1477     {
1478         dict_delete_ord(zh->reg->matchDict, db_ord, recid_z);
1479     }
1480     if (zebra_end_trans(zh) != ZEBRA_OK)
1481     {
1482         yaz_log(YLOG_WARN, "zebra_end_trans failed");
1483         res = ZEBRA_FAIL;
1484     }
1485     return res;
1486 }
1487
1488 int delete_w_handle(const char *info, void *handle)
1489 {
1490     ZebraHandle zh = (ZebraHandle) handle;
1491     ISAM_P pos;
1492     ASSERTZH;
1493
1494     if (*info == sizeof(pos))
1495     {
1496         memcpy (&pos, info+1, sizeof(pos));
1497         isamb_unlink(zh->reg->isamb, pos);
1498     }
1499     return 0;
1500 }
1501
1502 static int delete_SU_handle(void *handle, int ord)
1503 {
1504     ZebraHandle zh = (ZebraHandle) handle;
1505     char ord_buf[20];
1506     int ord_len;
1507
1508     ord_len = key_SU_encode (ord, ord_buf);
1509     ord_buf[ord_len] = '\0';
1510
1511     assert (zh->reg->isamb);
1512     dict_delete_subtree(zh->reg->dict, ord_buf,
1513                         zh, delete_w_handle);
1514     return 0;
1515 }
1516
1517 ZEBRA_RES zebra_drop_database(ZebraHandle zh, const char *db)
1518 {
1519     ZEBRA_RES ret = ZEBRA_OK;
1520
1521     yaz_log(log_level, "zebra_drop_database %s", db);
1522     ZEBRA_CHECK_HANDLE(zh);
1523
1524     if (zebra_select_database (zh, db) == ZEBRA_FAIL)
1525         return ZEBRA_FAIL;
1526     if (zebra_begin_trans (zh, 1) == ZEBRA_FAIL)
1527         return ZEBRA_FAIL;
1528     if (zh->reg->isamb)
1529     {
1530         int db_ord;
1531         if (zebraExplain_curDatabase (zh->reg->zei, db))
1532         {
1533             zebra_setError(zh, YAZ_BIB1_DATABASE_DOES_NOT_EXIST, db);
1534             ret = ZEBRA_FAIL;
1535         }
1536         else
1537         {
1538             db_ord = zebraExplain_get_database_ord(zh->reg->zei);
1539             dict_delete_subtree_ord(zh->reg->matchDict, db_ord,
1540                                     0 /* handle */, 0 /* func */);
1541             zebraExplain_trav_ord(zh->reg->zei, zh, delete_SU_handle);
1542             zebraExplain_removeDatabase(zh->reg->zei, zh);
1543             zebra_remove_file_match(zh);
1544         }
1545     }
1546     else
1547     {
1548         yaz_log(YLOG_WARN, "drop database only supported for isam:b");
1549         zebra_setError(zh, YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED,
1550                        "drop database only supported for isam:b");
1551         ret = ZEBRA_FAIL;
1552     }
1553     if (zebra_end_trans (zh) != ZEBRA_OK)
1554     {
1555         yaz_log(YLOG_WARN, "zebra_end_trans failed");
1556         ret = ZEBRA_FAIL;
1557     }
1558     return ret;
1559 }
1560
1561 ZEBRA_RES zebra_create_database (ZebraHandle zh, const char *db)
1562 {
1563     yaz_log(log_level, "zebra_create_database %s", db);
1564     ZEBRA_CHECK_HANDLE(zh);
1565     assert(db);
1566
1567     if (zebra_select_database (zh, db) == ZEBRA_FAIL)
1568         return ZEBRA_FAIL;
1569     if (zebra_begin_trans (zh, 1))
1570         return ZEBRA_FAIL;
1571
1572     /* announce database */
1573     if (zebraExplain_newDatabase (zh->reg->zei, db, 0 
1574                                   /* explainDatabase */))
1575     {
1576         if (zebra_end_trans (zh) != ZEBRA_OK)
1577         {
1578             yaz_log(YLOG_WARN, "zebra_end_trans failed");
1579         }
1580         zebra_setError(zh, YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED, db);
1581         return ZEBRA_FAIL;
1582     }
1583     return zebra_end_trans (zh);
1584 }
1585
1586 int zebra_string_norm (ZebraHandle zh, unsigned reg_id,
1587                        const char *input_str, int input_len,
1588                        char *output_str, int output_len)
1589 {
1590     WRBUF wrbuf;
1591     ASSERTZH;
1592     assert(input_str);
1593     assert(output_str);
1594     yaz_log(log_level, "zebra_string_norm ");
1595
1596     if (!zh->reg->zebra_maps)
1597         return -1;
1598     wrbuf = zebra_replace(zh->reg->zebra_maps, reg_id, "",
1599                           input_str, input_len);
1600     if (!wrbuf)
1601         return -2;
1602     if (wrbuf_len(wrbuf) >= output_len)
1603         return -3;
1604     if (wrbuf_len(wrbuf))
1605         memcpy (output_str, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
1606     output_str[wrbuf_len(wrbuf)] = '\0';
1607     return wrbuf_len(wrbuf);
1608 }
1609
1610 /** \brief set register state (state*.LCK)
1611     \param zh Zebra handle
1612     \param val state
1613     \param seqno sequence number
1614     
1615     val is one of:
1616     d=writing to shadow(dirty)
1617     o=no writing, 
1618     c=commit
1619 */
1620 static void zebra_set_state (ZebraHandle zh, int val, int seqno)
1621 {
1622     char state_fname[256];
1623     char *fname;
1624     long p = getpid();
1625     FILE *f;
1626     ASSERTZH;
1627     yaz_log(log_level, "zebra_set_state v=%d seq=%d", val, seqno);
1628
1629     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1630     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1631     f = fopen (fname, "w");
1632
1633     yaz_log (YLOG_DEBUG, "zebra_set_state: %c %d %ld", val, seqno, p);
1634     fprintf (f, "%c %d %ld\n", val, seqno, p);
1635     fclose (f);
1636     xfree(fname);
1637 }
1638
1639 static void zebra_get_state (ZebraHandle zh, char *val, int *seqno)
1640 {
1641     char state_fname[256];
1642     char *fname;
1643     FILE *f;
1644
1645     ASSERTZH;
1646     yaz_log(log_level, "zebra_get_state ");
1647
1648     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1649     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1650     f = fopen (fname, "r");
1651     *val = 'o';
1652     *seqno = 0;
1653
1654     if (f)
1655     {
1656         fscanf (f, "%c %d", val, seqno);
1657         fclose (f);
1658     }
1659     xfree(fname);
1660 }
1661
1662 ZEBRA_RES zebra_begin_read (ZebraHandle zh)
1663 {
1664     return zebra_begin_trans(zh, 0);
1665 }
1666
1667 ZEBRA_RES zebra_end_read (ZebraHandle zh)
1668 {
1669     return zebra_end_trans(zh);
1670 }
1671
1672 static void read_res_for_transaction(ZebraHandle zh)
1673 {
1674     const char *group = res_get(zh->res, "group");
1675     const char *v;
1676     /* FIXME - do we still use groups ?? */
1677     
1678     zh->m_group = group;
1679     v = res_get_prefix(zh->res, "followLinks", group, "1");
1680     zh->m_follow_links = atoi(v);
1681
1682     zh->m_record_id = res_get_prefix(zh->res, "recordId", group, 0);
1683     zh->m_record_type = res_get_prefix(zh->res, "recordType", group, 0);
1684
1685     v = res_get_prefix(zh->res, "storeKeys", group, "1");
1686     zh->m_store_keys = atoi(v);
1687
1688     v = res_get_prefix(zh->res, "storeData", group, "1");
1689     zh->m_store_data = atoi(v);
1690
1691     v = res_get_prefix(zh->res, "explainDatabase", group, "0");
1692     zh->m_explain_database = atoi(v);
1693
1694     v = res_get_prefix(zh->res, "openRW", group, "1");
1695     zh->m_flag_rw = atoi(v);
1696
1697     v = res_get_prefix(zh->res, "fileVerboseLimit", group, "100000");
1698     zh->m_file_verbose_limit = atoi(v);
1699 }
1700
1701 ZEBRA_RES zebra_begin_trans(ZebraHandle zh, int rw)
1702 {
1703     ZEBRA_CHECK_HANDLE(zh);
1704     zebra_select_default_database(zh);
1705     if (!zh->res)
1706     {
1707         zebra_setError(zh, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
1708                        "zebra_begin_trans: no database selected");
1709         return ZEBRA_FAIL;
1710     }
1711     ASSERTZHRES;
1712     yaz_log(log_level, "zebra_begin_trans rw=%d",rw);
1713
1714     if (zh->user_perm)
1715     {
1716         if (rw && !strchr(zh->user_perm, 'w'))
1717         {
1718             zebra_setError(
1719                 zh,
1720                 YAZ_BIB1_ES_PERMISSION_DENIED_ON_ES_CANNOT_MODIFY_OR_DELETE,
1721                 0);
1722             return ZEBRA_FAIL;
1723         }
1724     }
1725
1726     assert (zh->res);
1727     if (rw)
1728     {
1729         int seqno = 0;
1730         char val = '?';
1731         const char *rval = 0;
1732         
1733         (zh->trans_no++);
1734         if (zh->trans_w_no)
1735         {
1736             read_res_for_transaction(zh);
1737             return 0;
1738         }
1739         if (zh->trans_no != 1)
1740         {
1741             zebra_setError(zh, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
1742                            "zebra_begin_trans: no write trans within read");
1743             return ZEBRA_FAIL;
1744         }
1745         if (zh->reg)
1746         {
1747             resultSetInvalidate (zh);
1748             zebra_register_close(zh->service, zh->reg);
1749         }
1750         zh->trans_w_no = zh->trans_no;
1751
1752         zh->records_inserted = 0;
1753         zh->records_updated = 0;
1754         zh->records_deleted = 0;
1755         zh->records_processed = 0;
1756         
1757 #if HAVE_SYS_TIMES_H
1758         times (&zh->tms1);
1759 #endif
1760         /* lock */
1761         if (zh->shadow_enable)
1762             rval = res_get (zh->res, "shadow");
1763         
1764         if (rval)
1765         {
1766             zebra_lock_r(zh->lock_normal);
1767             zebra_lock_w(zh->lock_shadow);
1768         }
1769         else
1770         {
1771             zebra_lock_w(zh->lock_normal);
1772             zebra_lock_w(zh->lock_shadow);
1773         }
1774         zebra_get_state (zh, &val, &seqno);
1775         if (val != 'o')
1776         {
1777             /* either we didn't finish commit or shadow is dirty */
1778             zebra_unlock (zh->lock_shadow);
1779             zebra_unlock (zh->lock_normal);
1780             if (zebra_commit (zh))
1781             {
1782                 zh->trans_no--;
1783                 zh->trans_w_no = 0;
1784                 return ZEBRA_FAIL;
1785             }
1786             if (rval)
1787             {
1788                 zebra_lock_r(zh->lock_normal);
1789                 zebra_lock_w(zh->lock_shadow);
1790             }
1791             else
1792             {
1793                 zebra_lock_w(zh->lock_normal);
1794                 zebra_lock_w(zh->lock_shadow);
1795             }
1796         }
1797
1798         zebra_set_state (zh, 'd', seqno);
1799         
1800         zh->reg = zebra_register_open(zh->service, zh->reg_name,
1801                                       1, rval ? 1 : 0, zh->res,
1802                                       zh->path_reg);
1803         if (zh->reg)
1804             zh->reg->seqno = seqno;
1805         else
1806         {
1807             zebra_set_state (zh, 'o', seqno);
1808             
1809             zebra_unlock (zh->lock_shadow);
1810             zebra_unlock (zh->lock_normal);
1811
1812             zh->trans_no--;
1813             zh->trans_w_no = 0;
1814
1815             zebra_setError(zh, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
1816                            "zebra_begin_trans: cannot open register");
1817             yaz_log(YLOG_FATAL, "%s", zh->errString);
1818             return ZEBRA_FAIL;
1819         }
1820         zebraExplain_curDatabase(zh->reg->zei, zh->basenames[0]);
1821     }
1822     else
1823     {
1824         int dirty = 0;
1825         char val;
1826         int seqno;
1827         
1828         (zh->trans_no)++;
1829         
1830         if (zh->trans_no != 1)
1831         {
1832             return zebra_flush_reg (zh);
1833         }
1834 #if HAVE_SYS_TIMES_H
1835         times (&zh->tms1);
1836 #endif
1837         if (!zh->res)
1838         {
1839             (zh->trans_no)--;
1840             zh->errCode = YAZ_BIB1_DATABASE_UNAVAILABLE;
1841             return ZEBRA_FAIL;
1842         }
1843         if (!zh->lock_normal || !zh->lock_shadow)
1844         {
1845             (zh->trans_no)--;
1846             zh->errCode = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1847             return ZEBRA_FAIL;
1848         }
1849         zebra_get_state (zh, &val, &seqno);
1850         if (val == 'd')
1851             val = 'o';
1852         
1853         if (!zh->reg)
1854             dirty = 1;
1855         else if (seqno != zh->reg->seqno)
1856         {
1857             yaz_log (YLOG_DEBUG, "reopen seqno cur/old %d/%d",
1858                      seqno, zh->reg->seqno);
1859             dirty = 1;
1860         }
1861         else if (zh->reg->last_val != val)
1862         {
1863             yaz_log (YLOG_DEBUG, "reopen last cur/old %d/%d",
1864                      val, zh->reg->last_val);
1865             dirty = 1;
1866         }
1867         if (!dirty)
1868             return ZEBRA_OK;
1869         
1870         if (val == 'c')
1871             zebra_lock_r (zh->lock_shadow);
1872         else
1873             zebra_lock_r (zh->lock_normal);
1874         
1875         if (zh->reg)
1876         {
1877             resultSetInvalidate (zh);
1878             zebra_register_close(zh->service, zh->reg);
1879         }
1880         zh->reg = zebra_register_open(zh->service, zh->reg_name,
1881                                       0, val == 'c' ? 1 : 0,
1882                                       zh->res, zh->path_reg);
1883         if (!zh->reg)
1884         {
1885             zebra_unlock (zh->lock_normal);
1886             zebra_unlock (zh->lock_shadow);
1887             zh->trans_no--;
1888             zh->errCode = YAZ_BIB1_DATABASE_UNAVAILABLE;
1889             return ZEBRA_FAIL;
1890         }
1891         zh->reg->last_val = val;
1892         zh->reg->seqno = seqno;
1893     }
1894     read_res_for_transaction(zh);
1895     return ZEBRA_OK;
1896 }
1897
1898 ZEBRA_RES zebra_end_trans (ZebraHandle zh)
1899 {
1900     ZebraTransactionStatus dummy;
1901
1902     yaz_log(log_level, "zebra_end_trans");
1903     ZEBRA_CHECK_HANDLE(zh);
1904     return zebra_end_transaction(zh, &dummy);
1905 }
1906
1907 ZEBRA_RES zebra_end_transaction (ZebraHandle zh, ZebraTransactionStatus *status)
1908 {
1909     char val;
1910     int seqno;
1911     const char *rval;
1912
1913     ZEBRA_CHECK_HANDLE(zh);
1914
1915     assert(status);
1916     yaz_log(log_level, "zebra_end_transaction");
1917
1918     status->processed = 0;
1919     status->inserted  = 0;
1920     status->updated   = 0;
1921     status->deleted   = 0;
1922     status->utime     = 0;
1923     status->stime     = 0;
1924
1925     if (!zh->res || !zh->reg)
1926     {
1927         zebra_setError(zh, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
1928                        "zebra_end_trans: no open transaction");
1929         return ZEBRA_FAIL;
1930     }
1931     if (zh->trans_no != zh->trans_w_no)
1932     {
1933         zh->trans_no--;
1934         if (zh->trans_no != 0)
1935             return ZEBRA_OK;
1936
1937         /* release read lock */
1938
1939         zebra_unlock (zh->lock_normal);
1940         zebra_unlock (zh->lock_shadow);
1941     }
1942     else
1943     {   /* release write lock */
1944         zh->trans_no--;
1945         zh->trans_w_no = 0;
1946         
1947         yaz_log (YLOG_DEBUG, "zebra_end_trans");
1948         rval = res_get (zh->res, "shadow");
1949         
1950         zebraExplain_runNumberIncrement (zh->reg->zei, 1);
1951         
1952         zebra_flush_reg (zh);
1953         
1954         resultSetInvalidate (zh);
1955
1956         zebra_register_close(zh->service, zh->reg);
1957         zh->reg = 0;
1958         
1959         yaz_log (YLOG_LOG, "Records: "ZINT_FORMAT" i/u/d "
1960                         ZINT_FORMAT"/"ZINT_FORMAT"/"ZINT_FORMAT, 
1961                  zh->records_processed, zh->records_inserted,
1962                  zh->records_updated, zh->records_deleted);
1963         
1964         status->processed = zh->records_processed;
1965         status->inserted = zh->records_inserted;
1966         status->updated = zh->records_updated;
1967         status->deleted = zh->records_deleted;
1968         
1969         zebra_get_state (zh, &val, &seqno);
1970         if (val != 'd')
1971         {
1972             BFiles bfs = bfs_create (rval, zh->path_reg);
1973             yaz_log (YLOG_DEBUG, "deleting shadow val=%c", val);
1974             bf_commitClean (bfs, rval);
1975             bfs_destroy (bfs);
1976         }
1977         if (!rval)
1978             seqno++;
1979         zebra_set_state (zh, 'o', seqno);
1980         
1981         zebra_unlock (zh->lock_shadow);
1982         zebra_unlock (zh->lock_normal);
1983         
1984     }
1985 #if HAVE_SYS_TIMES_H
1986     times (&zh->tms2);
1987     yaz_log (log_level, "user/system: %ld/%ld",
1988           (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1989           (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1990     
1991     status->utime = (long) (zh->tms2.tms_utime - zh->tms1.tms_utime);
1992     status->stime = (long) (zh->tms2.tms_stime - zh->tms1.tms_stime);
1993 #endif
1994     return ZEBRA_OK;
1995 }
1996
1997 ZEBRA_RES zebra_repository_update(ZebraHandle zh, const char *path)
1998 {
1999     ASSERTZH;
2000     assert(path);
2001     yaz_log (log_level, "updating %s", path);
2002
2003     if (zh->m_record_id && !strcmp (zh->m_record_id, "file"))
2004         return zebra_update_file_match(zh, path);
2005     else
2006         return zebra_update_from_path(zh, path);
2007 }
2008
2009 ZEBRA_RES zebra_repository_delete(ZebraHandle zh, const char *path)
2010 {
2011     ASSERTZH;
2012     assert(path);
2013     yaz_log (log_level, "deleting %s", path);
2014     return zebra_delete_from_path(zh, path);
2015 }
2016
2017 ZEBRA_RES zebra_repository_show(ZebraHandle zh, const char *path)
2018 {
2019     ASSERTZH;
2020     assert(path);
2021     yaz_log(log_level, "zebra_repository_show");
2022     repositoryShow (zh, path);
2023     return ZEBRA_OK;
2024 }
2025
2026 static ZEBRA_RES zebra_commit_ex(ZebraHandle zh, int clean_only)
2027 {
2028     int seqno;
2029     char val;
2030     const char *rval;
2031     BFiles bfs;
2032     ZEBRA_RES res = ZEBRA_OK;
2033
2034     ASSERTZH;
2035
2036     zebra_select_default_database(zh);
2037     if (!zh->res)
2038     {
2039         zh->errCode = YAZ_BIB1_DATABASE_UNAVAILABLE;
2040         return ZEBRA_FAIL;
2041     }
2042     rval = res_get(zh->res, "shadow");    
2043     if (!rval)
2044     {
2045         yaz_log (YLOG_WARN, "Cannot perform commit - No shadow area defined");
2046         return ZEBRA_OK;
2047     }
2048
2049     zebra_lock_w(zh->lock_normal);
2050     zebra_lock_r(zh->lock_shadow);
2051
2052     bfs = bfs_create(res_get (zh->res, "register"), zh->path_reg);
2053     if (!bfs)
2054     {
2055         zebra_unlock(zh->lock_shadow);
2056         zebra_unlock(zh->lock_normal);
2057         return ZEBRA_FAIL;
2058     }
2059     zebra_get_state(zh, &val, &seqno);
2060
2061     if (val == 'd')
2062     {
2063         yaz_log(YLOG_WARN, "previous transaction didn't reach commit");
2064         clean_only = 1;
2065     }
2066
2067     if (rval && *rval)
2068         bf_cache (bfs, rval);
2069     if (bf_commitExists (bfs))
2070     {
2071         if (clean_only)
2072             zebra_set_state(zh, 'd', seqno);
2073         else
2074         {
2075             zebra_set_state(zh, 'c', seqno);
2076             
2077             yaz_log(YLOG_DEBUG, "commit start");
2078             if (bf_commitExec (bfs))
2079                 res = ZEBRA_FAIL;
2080         }
2081         if (res == ZEBRA_OK)
2082         {
2083             seqno++;
2084             zebra_set_state(zh, 'o', seqno);
2085             
2086             zebra_unlock(zh->lock_shadow);
2087             zebra_unlock(zh->lock_normal);
2088             
2089             zebra_lock_w(zh->lock_shadow);
2090             bf_commitClean(bfs, rval);
2091             zebra_unlock(zh->lock_shadow);
2092         }
2093         else
2094         {
2095             zebra_unlock(zh->lock_shadow);
2096             zebra_unlock(zh->lock_normal);
2097             yaz_log(YLOG_WARN, "zebra_commit: failed");
2098         }
2099     }
2100     else
2101     {
2102         zebra_unlock(zh->lock_shadow);
2103         zebra_unlock(zh->lock_normal);
2104         yaz_log(log_level, "nothing to commit");
2105     }
2106     bfs_destroy(bfs);
2107
2108     return res;
2109 }
2110
2111 ZEBRA_RES zebra_clean(ZebraHandle zh)
2112 {
2113     yaz_log(log_level, "zebra_clean");
2114     ZEBRA_CHECK_HANDLE(zh);
2115     return zebra_commit_ex(zh, 1);
2116 }
2117
2118 ZEBRA_RES zebra_commit(ZebraHandle zh)
2119 {
2120     yaz_log(log_level, "zebra_commit");
2121     ZEBRA_CHECK_HANDLE(zh);
2122     return zebra_commit_ex(zh, 0);
2123 }
2124
2125
2126 ZEBRA_RES zebra_init(ZebraHandle zh)
2127 {
2128     const char *rval;
2129     BFiles bfs = 0;
2130
2131     yaz_log(log_level, "zebra_init");
2132
2133     ZEBRA_CHECK_HANDLE(zh);
2134
2135     zebra_select_default_database(zh);
2136     if (!zh->res)
2137     {
2138         zebra_setError(zh, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
2139                        "cannot select default database");
2140         return ZEBRA_FAIL;
2141     }
2142     rval = res_get (zh->res, "shadow");
2143
2144     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
2145     if (!bfs)
2146     {
2147         zebra_setError(zh, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR, "bfs_create");
2148         return ZEBRA_FAIL;
2149     }
2150     if (rval && *rval)
2151         bf_cache (bfs, rval);
2152     
2153     bf_reset (bfs);
2154     bfs_destroy (bfs);
2155     zebra_set_state (zh, 'o', 0);
2156     return ZEBRA_OK;
2157 }
2158
2159 ZEBRA_RES zebra_compact(ZebraHandle zh)
2160 {
2161     BFiles bfs;
2162
2163     yaz_log(log_level, "zebra_compact");
2164     ZEBRA_CHECK_HANDLE(zh);
2165     if (!zh->res)
2166     {
2167         zh->errCode = YAZ_BIB1_DATABASE_UNAVAILABLE;
2168         return ZEBRA_FAIL;
2169     }
2170     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
2171     inv_compact (bfs);
2172     bfs_destroy (bfs);
2173     return ZEBRA_OK;
2174 }
2175
2176 void zebra_result(ZebraHandle zh, int *code, char **addinfo)
2177 {
2178     yaz_log(log_level, "zebra_result");
2179     if (zh)
2180     {
2181         *code = zh->errCode;
2182         *addinfo = zh->errString;
2183     }
2184     else
2185     {
2186         *code = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
2187         *addinfo ="ZebraHandle is NULL";
2188     }
2189 }
2190
2191 void zebra_shadow_enable(ZebraHandle zh, int value)
2192 {
2193     ASSERTZH;
2194     yaz_log(log_level, "zebra_shadow_enable");
2195     zh->shadow_enable = value;
2196 }
2197
2198 ZEBRA_RES zebra_octet_term_encoding(ZebraHandle zh, const char *encoding)
2199 {
2200     yaz_log(log_level, "zebra_octet_term_encoding %s", encoding);
2201     ZEBRA_CHECK_HANDLE(zh);
2202     assert(encoding);
2203
2204     if (zh->iconv_to_utf8 != 0)
2205         yaz_iconv_close(zh->iconv_to_utf8);
2206     if (zh->iconv_from_utf8 != 0)
2207         yaz_iconv_close(zh->iconv_from_utf8);
2208     
2209     zh->iconv_to_utf8 =
2210         yaz_iconv_open ("UTF-8", encoding);
2211     if (zh->iconv_to_utf8 == 0)
2212         yaz_log (YLOG_WARN, "iconv: %s to UTF-8 unsupported", encoding);
2213     zh->iconv_from_utf8 =
2214         yaz_iconv_open (encoding, "UTF-8");
2215     if (zh->iconv_to_utf8 == 0)
2216         yaz_log (YLOG_WARN, "iconv: UTF-8 to %s unsupported", encoding);
2217
2218     return ZEBRA_OK;
2219 }
2220
2221 ZEBRA_RES zebra_record_encoding (ZebraHandle zh, const char *encoding)
2222 {
2223     yaz_log(log_level, "zebra_record_encoding");
2224     ZEBRA_CHECK_HANDLE(zh);
2225     xfree(zh->record_encoding);
2226     zh->record_encoding = 0;
2227     if (encoding)
2228         zh->record_encoding = xstrdup (encoding);
2229     return ZEBRA_OK;
2230 }
2231
2232 void zebra_set_resource(ZebraHandle zh, const char *name, const char *value)
2233 {
2234     assert(name);
2235     assert(value);
2236     yaz_log(log_level, "zebra_set_resource %s:%s", name, value);
2237     ASSERTZH;
2238     res_set(zh->res, name, value);
2239 }
2240
2241 const char *zebra_get_resource(ZebraHandle zh,
2242                                const char *name, const char *defaultvalue)
2243 {
2244     const char *v;
2245     ASSERTZH;
2246     assert(name);
2247     v = res_get_def (zh->res, name, (char *)defaultvalue);
2248     yaz_log(log_level, "zebra_get_resource %s:%s", name, v);
2249     return v;
2250 }
2251
2252 /* moved from zebra_api_ext.c by pop */
2253 /* FIXME: Should this really be public??? -Heikki */
2254
2255 int zebra_trans_no (ZebraHandle zh)
2256 {
2257     yaz_log(log_level, "zebra_trans_no");
2258     ASSERTZH;
2259     return zh->trans_no;
2260 }
2261
2262 int zebra_get_shadow_enable (ZebraHandle zh)
2263 {
2264     yaz_log(log_level, "zebra_get_shadow_enable");
2265     ASSERTZH;
2266     return zh->shadow_enable;
2267 }
2268
2269 void zebra_set_shadow_enable (ZebraHandle zh, int value)
2270 {
2271     yaz_log(log_level, "zebra_set_shadow_enable %d",value);
2272     ASSERTZH;
2273     zh->shadow_enable = value;
2274 }
2275
2276 ZEBRA_RES zebra_add_record(ZebraHandle zh,
2277                            const char *buf, int buf_size)
2278 {
2279     return zebra_update_record(zh, 0, 0 /* sysno */, 0, 0, buf, buf_size, 0);
2280 }
2281
2282 ZEBRA_RES zebra_insert_record(ZebraHandle zh, 
2283                               const char *recordType,
2284                               zint *sysno, const char *match,
2285                               const char *fname,
2286                               const char *buf, int buf_size, int force_update)
2287 {
2288     ZEBRA_RES res;
2289     ASSERTZH;
2290     assert(sysno);
2291     assert(buf);
2292     yaz_log(log_level, "zebra_insert_record sysno=" ZINT_FORMAT, *sysno);
2293
2294     if (buf_size < 1)
2295         buf_size = strlen(buf);
2296
2297     if (zebra_begin_trans(zh, 1) == ZEBRA_FAIL)
2298         return ZEBRA_FAIL;
2299     res = zebra_buffer_extract_record(zh, buf, buf_size, 
2300                                       0, /* delete_flag  */
2301                                       0, /* test_mode */
2302                                       recordType,
2303                                       sysno,   
2304                                       match, fname,
2305                                       0, 
2306                                       0); /* allow_update */
2307     if (zebra_end_trans(zh) != ZEBRA_OK)
2308     {
2309         yaz_log(YLOG_WARN, "zebra_end_trans failed");
2310         res = ZEBRA_FAIL;
2311     }
2312     return res; 
2313 }
2314
2315 ZEBRA_RES zebra_update_record(ZebraHandle zh, 
2316                               const char *recordType,
2317                               zint *sysno, const char *match,
2318                               const char *fname,
2319                               const char *buf, int buf_size,
2320                               int force_update)
2321 {
2322     ZEBRA_RES res;
2323
2324     ZEBRA_CHECK_HANDLE(zh);
2325
2326     assert(buf);
2327
2328     yaz_log(log_level, "zebra_update_record");
2329     if (sysno)
2330         yaz_log(log_level, " sysno=" ZINT_FORMAT, *sysno);
2331
2332     if (buf_size < 1) buf_size = strlen(buf);
2333
2334     if (zebra_begin_trans(zh, 1) == ZEBRA_FAIL)
2335         return ZEBRA_FAIL;
2336     res = zebra_buffer_extract_record(zh, buf, buf_size, 
2337                                       0, /* delete_flag */
2338                                       0, /* test_mode */
2339                                       recordType,
2340                                       sysno,   
2341                                       match, fname,
2342                                       force_update, 
2343                                       1); /* allow_update */
2344     if (zebra_end_trans(zh) != ZEBRA_OK)
2345     {
2346         yaz_log(YLOG_WARN, "zebra_end_trans failed");
2347         res = ZEBRA_FAIL;
2348     }
2349     return res; 
2350 }
2351
2352 ZEBRA_RES zebra_delete_record(ZebraHandle zh, 
2353                               const char *recordType,
2354                               zint *sysno, const char *match,
2355                               const char *fname,
2356                               const char *buf, int buf_size,
2357                               int force_update) 
2358 {
2359     ZEBRA_RES res;
2360
2361     ZEBRA_CHECK_HANDLE(zh);
2362
2363     assert(buf);
2364     yaz_log(log_level, "zebra_delete_record");
2365     if (sysno)
2366         yaz_log(log_level, " sysno=" ZINT_FORMAT, *sysno);
2367
2368     if (buf_size < 1) buf_size = strlen(buf);
2369
2370     if (zebra_begin_trans(zh, 1) == ZEBRA_FAIL)
2371         return ZEBRA_FAIL;
2372     res = zebra_buffer_extract_record(zh, buf, buf_size,
2373                                       1, /* delete_flag */
2374                                       0, /* test_mode */
2375                                       recordType,
2376                                       sysno,
2377                                       match,fname,
2378                                       force_update,
2379                                       1); /* allow_update */
2380     if (zebra_end_trans(zh) != ZEBRA_OK)
2381     {
2382         yaz_log(YLOG_WARN, "zebra_end_trans failed");
2383         res = ZEBRA_FAIL;
2384     }
2385     return res;
2386 }
2387
2388 /* ---------------------------------------------------------------------------
2389   Searching 
2390 */
2391
2392 ZEBRA_RES zebra_search_PQF(ZebraHandle zh, const char *pqf_query,
2393                            const char *setname, zint *hits)
2394 {
2395     zint lhits = 0;
2396     ZEBRA_RES res = ZEBRA_OK;
2397     Z_RPNQuery *query;
2398     ODR odr;
2399
2400
2401     ZEBRA_CHECK_HANDLE(zh);
2402
2403     odr = odr_createmem(ODR_ENCODE);
2404
2405     assert(pqf_query);
2406     assert(setname);
2407
2408     yaz_log(log_level, "zebra_search_PQF s=%s q=%s", setname, pqf_query);
2409     
2410     query = p_query_rpn (odr, PROTO_Z3950, pqf_query);
2411     
2412     if (!query)
2413     {
2414         yaz_log (YLOG_WARN, "bad query %s\n", pqf_query);
2415         zh->errCode = YAZ_BIB1_MALFORMED_QUERY;
2416         res = ZEBRA_FAIL;
2417     }
2418     else
2419         res = zebra_search_RPN(zh, odr, query, setname, &lhits);
2420     
2421     odr_destroy(odr);
2422
2423     yaz_log(log_level, "Hits: " ZINT_FORMAT, lhits);
2424
2425     if (hits)
2426         *hits = lhits;
2427
2428     return res;
2429 }
2430
2431 /* ---------------------------------------------------------------------------
2432   Sort - a simplified interface, with optional read locks.
2433 */
2434 int zebra_sort_by_specstr (ZebraHandle zh, ODR stream,
2435                            const char *sort_spec,
2436                            const char *output_setname,
2437                            const char **input_setnames) 
2438 {
2439     int num_input_setnames = 0;
2440     int sort_status = 0;
2441     Z_SortKeySpecList *sort_sequence;
2442
2443     ZEBRA_CHECK_HANDLE(zh);
2444     assert(stream);
2445     assert(sort_spec);
2446     assert(output_setname);
2447     assert(input_setnames);
2448     sort_sequence = yaz_sort_spec (stream, sort_spec);
2449     yaz_log(log_level, "sort (FIXME) ");
2450     if (!sort_sequence)
2451     {
2452         yaz_log(YLOG_WARN, "invalid sort specs '%s'", sort_spec);
2453         zh->errCode = YAZ_BIB1_CANNOT_SORT_ACCORDING_TO_SEQUENCE;
2454         return -1;
2455     }
2456     
2457     /* we can do this, since the perl typemap code for char** will 
2458        put a NULL at the end of list */
2459     while (input_setnames[num_input_setnames]) num_input_setnames++;
2460
2461     if (zebra_begin_read (zh))
2462         return -1;
2463     
2464     resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
2465                    output_setname, sort_sequence, &sort_status);
2466     
2467     zebra_end_read(zh);
2468     return sort_status;
2469 }
2470
2471 /* ---------------------------------------------------------------------------
2472   Get BFS for Zebra system (to make alternative storage methods)
2473 */
2474 struct BFiles_struct *zebra_get_bfs(ZebraHandle zh)
2475 {
2476     if (zh && zh->reg)
2477         return zh->reg->bfs;
2478     return 0;
2479 }
2480
2481
2482 /* ---------------------------------------------------------------------------
2483   Set limit for search/scan
2484 */
2485 ZEBRA_RES zebra_set_limit(ZebraHandle zh, int complement_flag, zint *ids)
2486 {
2487     ZEBRA_CHECK_HANDLE(zh);
2488     zebra_limit_destroy(zh->m_limit);
2489     zh->m_limit = zebra_limit_create(complement_flag, ids);
2490     return ZEBRA_OK;
2491 }
2492
2493 /*
2494   Set Error code + addinfo
2495 */
2496 void zebra_setError(ZebraHandle zh, int code, const char *addinfo)
2497 {
2498     if (!zh)
2499         return;
2500     zh->errCode = code;
2501     nmem_reset(zh->nmem_error);
2502     zh->errString = addinfo ? nmem_strdup(zh->nmem_error, addinfo) : 0;
2503 }
2504
2505 void zebra_setError_zint(ZebraHandle zh, int code, zint i)
2506 {
2507     char vstr[60];
2508     sprintf(vstr, ZINT_FORMAT, i);
2509
2510     zh->errCode = code;
2511     nmem_reset(zh->nmem_error);
2512     zh->errString = nmem_strdup(zh->nmem_error, vstr);
2513 }
2514
2515 void zebra_lock_prefix(Res res, char *path)
2516 {
2517     const char *lock_dir = res_get_def (res, "lockDir", "");
2518     
2519     strcpy(path, lock_dir);
2520     if (*path && path[strlen(path)-1] != '/')
2521         strcat (path, "/");
2522 }
2523
2524 /*
2525  * Local variables:
2526  * c-basic-offset: 4
2527  * indent-tabs-mode: nil
2528  * End:
2529  * vim: shiftwidth=4 tabstop=8 expandtab
2530  */
2531