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