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