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