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