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