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