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