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