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