Fixed bug #321: zebra segvs if lock dir does not exist.
[idzebra-moved-to-github.git] / index / zebraapi.c
1 /* $Id: zebraapi.c,v 1.165 2005-05-06 18:59:35 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(0, 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             return -1;
670         }
671     }
672 }
673
674 void map_basenames_func (void *vp, const char *name, const char *value)
675 {
676     struct map_baseinfo *p = (struct map_baseinfo *) vp;
677     int i, no;
678     char fromdb[128], todb[8][128];
679
680     assert(value);
681     assert(name);
682     assert(vp);
683     
684     no =
685         sscanf (value, "%127s %127s %127s %127s %127s %127s %127s %127s %127s",
686                 fromdb, todb[0], todb[1], todb[2], todb[3], todb[4],
687                 todb[5], todb[6], todb[7]);
688     if (no < 2)
689         return ;
690     no--;
691     for (i = 0; i<p->num_bases; i++)
692         if (p->basenames[i] && !STRCASECMP (p->basenames[i], fromdb))
693         {
694             p->basenames[i] = 0;
695             for (i = 0; i < no; i++)
696             {
697                 if (p->new_num_bases == p->new_num_max)
698                     return;
699                 p->new_basenames[(p->new_num_bases)++] = 
700                     nmem_strdup (p->mem, todb[i]);
701             }
702             return;
703         }
704 }
705
706 int zebra_select_default_database(ZebraHandle zh)
707 {
708     if (!zh->res)
709     {
710         /* no database has been selected - so we select based on
711            resource setting (including group)
712         */
713         const char *group = res_get(zh->service->global_res, "group");
714         const char *v = res_get_prefix(zh->service->global_res,
715                                        "database", group, "Default");
716         return zebra_select_database(zh, v);
717     }
718     return 0;
719 }
720
721 void map_basenames (ZebraHandle zh, ODR stream,
722                     int *num_bases, char ***basenames)
723 {
724     struct map_baseinfo info;
725     struct map_baseinfo *p = &info;
726     int i;
727     ASSERTZH;
728     yaz_log(log_level, "map_basenames ");
729     assert(stream);
730
731     zh->errCode = 0;
732
733     info.zh = zh;
734
735     info.num_bases = *num_bases;
736     info.basenames = *basenames;
737     info.new_num_max = 128;
738     info.new_num_bases = 0;
739     info.new_basenames = (char **)
740         odr_malloc (stream, sizeof(*info.new_basenames) * info.new_num_max);
741     info.mem = stream->mem;
742
743     res_trav (zh->service->global_res, "mapdb", &info, map_basenames_func);
744     
745     for (i = 0; i<p->num_bases; i++)
746         if (p->basenames[i] && p->new_num_bases < p->new_num_max)
747         {
748             p->new_basenames[(p->new_num_bases)++] = 
749                 nmem_strdup (p->mem, p->basenames[i]);
750         }
751     *num_bases = info.new_num_bases;
752     *basenames = info.new_basenames;
753     for (i = 0; i<*num_bases; i++)
754         yaz_log (YLOG_DEBUG, "base %s", (*basenames)[i]);
755 }
756
757 ZEBRA_RES zebra_select_database (ZebraHandle zh, const char *basename)
758 {
759     ASSERTZH;
760     yaz_log(log_level, "zebra_select_database %s",basename);
761     assert(basename);
762     zh->errCode = 0;
763     return zebra_select_databases (zh, 1, &basename);
764 }
765
766 ZEBRA_RES zebra_select_databases (ZebraHandle zh, int num_bases,
767                                   const char **basenames)
768 {
769     int i;
770     const char *cp;
771     int len = 0;
772     char *new_reg = 0;
773     ASSERTZH;
774     assert(basenames);
775
776     yaz_log(log_level, "zebra_select_databases n=%d [0]=%s",
777                     num_bases,basenames[0]);
778     zh->errCode = 0;
779     
780     if (num_bases < 1)
781     {
782         zh->errCode = YAZ_BIB1_COMBI_OF_SPECIFIED_DATABASES_UNSUPP;
783         return ZEBRA_FAIL;
784     }
785     for (i = 0; i < zh->num_basenames; i++)
786         xfree(zh->basenames[i]);
787     xfree(zh->basenames);
788     
789     zh->num_basenames = num_bases;
790     zh->basenames = xmalloc(zh->num_basenames * sizeof(*zh->basenames));
791     for (i = 0; i < zh->num_basenames; i++)
792         zh->basenames[i] = xstrdup (basenames[i]);
793
794     cp = strrchr(basenames[0], '/');
795     if (cp)
796     {
797         len = cp - basenames[0];
798         new_reg = xmalloc(len + 1);
799         memcpy (new_reg, basenames[0], len);
800         new_reg[len] = '\0';
801     }
802     else
803         new_reg = xstrdup ("");
804     for (i = 1; i<num_bases; i++)
805     {
806         const char *cp1;
807
808         cp1 = strrchr (basenames[i], '/');
809         if (cp)
810         {
811             if (!cp1)
812             {
813                 zh->errCode = YAZ_BIB1_COMBI_OF_SPECIFIED_DATABASES_UNSUPP;
814                 return -1;
815             }
816             if (len != cp1 - basenames[i] ||
817                 memcmp (basenames[i], new_reg, len))
818             {
819                 zh->errCode = YAZ_BIB1_COMBI_OF_SPECIFIED_DATABASES_UNSUPP;
820                 return -1;
821             }
822         }
823         else
824         {
825             if (cp1)
826             {
827                 zh->errCode = YAZ_BIB1_COMBI_OF_SPECIFIED_DATABASES_UNSUPP;
828                 return ZEBRA_FAIL;
829             }
830         }
831     }
832     zebra_select_register (zh, new_reg);
833     xfree(new_reg);
834     if (!zh->res)
835     {
836         zh->errCode = YAZ_BIB1_DATABASE_UNAVAILABLE;
837         return ZEBRA_FAIL;
838     }
839     if (!zh->lock_normal || !zh->lock_shadow)
840     {
841         zh->errCode = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
842         return ZEBRA_FAIL;
843     }
844     return ZEBRA_OK;
845 }
846
847 ZEBRA_RES zebra_search_RPN(ZebraHandle zh, ODR o, Z_RPNQuery *query,
848                            const char *setname, zint *hits)
849 {
850     ZEBRA_RES r;
851     ASSERTZH;
852     assert(o);
853     assert(query);
854     assert(hits);
855     assert(setname);
856     yaz_log(log_level, "zebra_search_rpn");
857     zh->errCode = 0;
858     zh->hits = 0;
859     *hits = 0;
860
861     if (zebra_begin_read(zh) == ZEBRA_FAIL)
862         return ZEBRA_FAIL;
863
864     r = resultSetAddRPN(zh, odr_extract_mem(o), query, 
865                         zh->num_basenames, zh->basenames, setname);
866     zebra_end_read(zh);
867     *hits = zh->hits;
868     return r;
869 }
870
871 ZEBRA_RES zebra_records_retrieve (ZebraHandle zh, ODR stream,
872                                   const char *setname,
873                                   Z_RecordComposition *comp,
874                                   oid_value input_format, int num_recs,
875                                   ZebraRetrievalRecord *recs)
876 {
877     ZebraMetaRecord *poset;
878     int i;
879     ZEBRA_RES ret = ZEBRA_OK;
880     zint *pos_array;
881     ASSERTZH;
882     assert(stream);
883     assert(setname);
884     assert(recs);
885     assert(num_recs>0);
886
887     yaz_log(log_level, "zebra_records_retrieve n=%d", num_recs);
888     zh->errCode = 0;
889
890     if (!zh->res)
891     {
892         zh->errCode = YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST;
893         zh->errString = odr_strdup(stream, setname);
894         return ZEBRA_FAIL;
895     }
896     
897     zh->errCode = 0;
898
899     if (zebra_begin_read (zh) == ZEBRA_FAIL)
900         return ZEBRA_FAIL;
901
902     pos_array = (zint *) xmalloc(num_recs * sizeof(*pos_array));
903     for (i = 0; i<num_recs; i++)
904         pos_array[i] = recs[i].position;
905     poset = zebra_meta_records_create(zh, setname, num_recs, pos_array);
906     if (!poset)
907     {
908         yaz_log (YLOG_DEBUG, "zebraPosSetCreate error");
909         zh->errCode = YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST;
910         zh->errString = nmem_strdup (stream->mem, setname);
911         ret = ZEBRA_FAIL;
912     }
913     else
914     {
915         for (i = 0; i<num_recs; i++)
916         {
917             if (poset[i].term)
918             {
919                 recs[i].errCode = 0;
920                 recs[i].format = VAL_SUTRS;
921                 recs[i].len = strlen(poset[i].term);
922                 recs[i].buf = poset[i].term;
923                 recs[i].base = poset[i].db;
924             }
925             else if (poset[i].sysno)
926             {
927                 char *buf;
928                 int len;
929                 recs[i].errCode =
930                     zebra_record_fetch(zh, poset[i].sysno, poset[i].score,
931                                        stream, input_format, comp,
932                                        &recs[i].format, &buf, &len,
933                                        &recs[i].base, &recs[i].errString);
934                 recs[i].len = len;
935                 if (len > 0)
936                 {
937                     recs[i].buf = (char*) odr_malloc(stream, len);
938                     memcpy(recs[i].buf, buf, len);
939                 }
940                 else
941                     recs[i].buf = buf;
942                 recs[i].score = poset[i].score;
943                 recs[i].sysno = poset[i].sysno;
944             }
945             else
946             {
947                 char num_str[20];
948
949                 sprintf (num_str, ZINT_FORMAT, pos_array[i]);   
950                 zh->errCode = YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE;
951                 zh->errString = odr_strdup (stream, num_str);
952                 ret = ZEBRA_FAIL;
953                 break;
954             }
955         }
956         zebra_meta_records_destroy(zh, poset, num_recs);
957     }
958     zebra_end_read (zh);
959     xfree(pos_array);
960     return ret;
961 }
962
963 ZEBRA_RES zebra_scan_PQF(ZebraHandle zh, ODR stream, const char *query,
964                          int *position,
965                          int *num_entries, ZebraScanEntry **entries,
966                          int *is_partial)
967 {
968     YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
969     Z_AttributesPlusTerm *zapt;
970     int *attributeSet;
971     ZEBRA_RES res;
972     
973     if (!(zapt = yaz_pqf_scan(pqf_parser, stream, &attributeSet, query)))
974     {
975         res = ZEBRA_FAIL;
976         zh->errCode = YAZ_BIB1_SCAN_MALFORMED_SCAN;
977     }
978     else
979         res = zebra_scan(zh, stream, zapt, VAL_BIB1,
980                          position, num_entries, entries, is_partial);
981     yaz_pqf_destroy (pqf_parser);
982     return res;
983 }
984
985 ZEBRA_RES zebra_scan (ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
986                       oid_value attributeset,
987                       int *position,
988                       int *num_entries, ZebraScanEntry **entries,
989                       int *is_partial)
990 {
991     ZEBRA_RES res;
992     ASSERTZH;
993     assert(stream);
994     assert(zapt);
995     assert(position);
996     assert(num_entries);
997     assert(is_partial);
998     assert(entries);
999     yaz_log(log_level, "zebra_scan");
1000     zh->errCode = 0;
1001     if (zebra_begin_read (zh) == ZEBRA_FAIL)
1002     {
1003         *entries = 0;
1004         *num_entries = 0;
1005         return ZEBRA_FAIL;
1006     }
1007     res = rpn_scan (zh, stream, zapt, attributeset,
1008                     zh->num_basenames, zh->basenames, position,
1009                     num_entries, entries, is_partial, 0, 0);
1010     zebra_end_read (zh);
1011     return res;
1012 }
1013
1014 ZEBRA_RES zebra_sort (ZebraHandle zh, ODR stream,
1015                       int num_input_setnames, const char **input_setnames,
1016                       const char *output_setname,
1017                       Z_SortKeySpecList *sort_sequence,
1018                       int *sort_status)
1019 {
1020     ASSERTZH;
1021     assert(stream);
1022     assert(num_input_setnames>0);
1023     assert(input_setnames);
1024     assert(sort_sequence);
1025     assert(sort_status);
1026     yaz_log(log_level, "zebra_sort");
1027     zh->errCode = 0;
1028     if (zebra_begin_read (zh) == ZEBRA_FAIL)
1029         return ZEBRA_FAIL;
1030     resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
1031                    output_setname, sort_sequence, sort_status);
1032     return zebra_end_read(zh);
1033 }
1034
1035 int zebra_deleteResultSet(ZebraHandle zh, int function,
1036                           int num_setnames, char **setnames,
1037                           int *statuses)
1038 {
1039     int i, status;
1040     ASSERTZH;
1041     assert(statuses);
1042     yaz_log(log_level, "zebra_deleteResultSet n=%d",num_setnames);
1043     zh->errCode = 0;
1044     if (zebra_begin_read(zh))
1045         return Z_DeleteStatus_systemProblemAtTarget;
1046     switch (function)
1047     {
1048     case Z_DeleteResultSetRequest_list:
1049         assert(num_setnames>0);
1050         assert(setnames);
1051         resultSetDestroy (zh, num_setnames, setnames, statuses);
1052         break;
1053     case Z_DeleteResultSetRequest_all:
1054         resultSetDestroy (zh, -1, 0, statuses);
1055         break;
1056     }
1057     zebra_end_read (zh);
1058     status = Z_DeleteStatus_success;
1059     for (i = 0; i<num_setnames; i++)
1060         if (statuses[i] == Z_DeleteStatus_resultSetDidNotExist)
1061             status = statuses[i];
1062     return status;
1063 }
1064
1065 int zebra_errCode (ZebraHandle zh)
1066 {
1067     if (zh)
1068     {
1069         yaz_log(log_level, "zebra_errCode: %d",zh->errCode);
1070         return zh->errCode;
1071     }
1072     yaz_log(log_level, "zebra_errCode: o");
1073     return 0; 
1074 }
1075
1076 const char *zebra_errString (ZebraHandle zh)
1077 {
1078     const char *e="";
1079     if (zh)
1080         e= diagbib1_str (zh->errCode);
1081     yaz_log(log_level, "zebra_errString: %s",e);
1082     return e;
1083 }
1084
1085 char *zebra_errAdd (ZebraHandle zh)
1086 {
1087     char *a="";
1088     if (zh)
1089         a= zh->errString;
1090     yaz_log(log_level, "zebra_errAdd: %s",a);
1091     return a;
1092 }
1093
1094 void zebra_clearError(ZebraHandle zh)
1095 {
1096     if (zh)
1097     {
1098         zh->errCode = 0;
1099         zh->errString = 0;
1100     }
1101 }
1102
1103 ZEBRA_RES zebra_auth (ZebraHandle zh, const char *user, const char *pass)
1104 {
1105     const char *p;
1106     char u[40];
1107     ZebraService zs;
1108
1109     ASSERTZH;
1110     zh->errCode = 0;
1111     zs= zh->service;
1112     
1113     sprintf(u, "perm.%.30s", user ? user : "anonymous");
1114     p = res_get(zs->global_res, u);
1115     xfree(zh->user_perm);
1116     zh->user_perm = xstrdup(p ? p : "r");
1117
1118     /* users that don't require a password .. */
1119     if (zh->user_perm && strchr(zh->user_perm, 'a'))
1120         return ZEBRA_OK;
1121     
1122     if (!zs->passwd_db || !passwd_db_auth (zs->passwd_db, user, pass))
1123         return ZEBRA_OK;
1124     return ZEBRA_FAIL;
1125 }
1126
1127 ZEBRA_RES zebra_admin_import_begin (ZebraHandle zh, const char *database,
1128                                const char *record_type)
1129 {
1130     ASSERTZH;
1131     yaz_log(log_level, "zebra_admin_import_begin db=%s rt=%s", 
1132                      database, record_type);
1133     zh->errCode = 0;
1134     if (zebra_select_database(zh, database) == ZEBRA_FAIL)
1135         return ZEBRA_FAIL;
1136     return zebra_begin_trans(zh, 1);
1137 }
1138
1139 ZEBRA_RES zebra_admin_import_end (ZebraHandle zh)
1140 {
1141     ASSERTZH;
1142     yaz_log(log_level, "zebra_admin_import_end");
1143     zh->errCode = 0;
1144     return zebra_end_trans(zh);
1145 }
1146
1147 ZEBRA_RES zebra_admin_import_segment (ZebraHandle zh, Z_Segment *segment)
1148 {
1149     ZEBRA_RES res = ZEBRA_OK;
1150     SYSNO sysno;
1151     int i;
1152     ASSERTZH;
1153     yaz_log(log_level, "zebra_admin_import_segment");
1154     zh->errCode = 0;
1155     for (i = 0; i<segment->num_segmentRecords; i++)
1156     {
1157         Z_NamePlusRecord *npr = segment->segmentRecords[i];
1158
1159         if (npr->which == Z_NamePlusRecord_intermediateFragment)
1160         {
1161             Z_FragmentSyntax *fragment = npr->u.intermediateFragment;
1162             if (fragment->which == Z_FragmentSyntax_notExternallyTagged)
1163             {
1164                 Odr_oct *oct = fragment->u.notExternallyTagged;
1165                 sysno = 0;
1166                 
1167                 if ( zebra_update_record(zh, 
1168                                          0, /* record Type */
1169                                          &sysno,
1170                                          0, /* match */
1171                                          0, /* fname */
1172                                          oct->buf, oct->len,
1173                                          0) == ZEBRA_FAIL)
1174                     res = ZEBRA_FAIL;
1175             }
1176         }
1177     }
1178     return res;
1179 }
1180
1181 ZEBRA_RES zebra_admin_exchange_record (ZebraHandle zh,
1182                                        const char *rec_buf,
1183                                        size_t rec_len,
1184                                        const char *recid_buf, size_t recid_len,
1185                                        int action)
1186     /* 1 = insert. Fail it already exists */
1187     /* 2 = replace. Fail it does not exist */
1188     /* 3 = delete. Fail if does not exist */
1189     /* 4 = update. Insert/replace */
1190 {
1191     ZEBRA_RES res;
1192     SYSNO sysno = 0;
1193     char *rinfo = 0;
1194     char recid_z[256];
1195     ASSERTZH;
1196     assert(action>0 && action <=4);
1197     assert(rec_buf);
1198
1199     yaz_log(log_level, "zebra_admin_exchange_record ac=%d", action);
1200     zh->errCode = 0;
1201
1202     if (!recid_buf || recid_len <= 0 || recid_len >= sizeof(recid_z))
1203         return ZEBRA_FAIL;
1204
1205     memcpy (recid_z, recid_buf, recid_len);
1206     recid_z[recid_len] = 0;
1207
1208     if (zebra_begin_trans(zh, 1) == ZEBRA_FAIL)
1209         return ZEBRA_FAIL;
1210
1211     rinfo = dict_lookup (zh->reg->matchDict, recid_z);
1212     if (rinfo)
1213     {
1214         if (action == 1)  /* fail if insert */
1215         {
1216              zebra_end_trans(zh);
1217              return ZEBRA_FAIL;
1218         }
1219
1220         memcpy (&sysno, rinfo+1, sizeof(sysno));
1221     }
1222     else
1223     {
1224         if (action == 2 || action == 3) /* fail if delete or update */
1225         {
1226             zebra_end_trans(zh);
1227             return ZEBRA_FAIL;
1228         }
1229         action = 1;  /* make it an insert (if it's an update).. */
1230     }
1231     res = buffer_extract_record (zh, rec_buf, rec_len,
1232                                  action == 3 ? 1 : 0 /* delete flag */,
1233                                  0, /* test mode */
1234                                  0, /* recordType */
1235                                  &sysno, 
1236                                  0, /* match */
1237                                  0, /* fname */
1238                            0, /* force update */
1239                                  1  /* allow update */
1240         );
1241     if (action == 1)
1242     {
1243         dict_insert (zh->reg->matchDict, recid_z, sizeof(sysno), &sysno);
1244     }
1245     else if (action == 3)
1246     {
1247         dict_delete (zh->reg->matchDict, recid_z);
1248     }
1249     zebra_end_trans(zh);
1250     return res;
1251 }
1252
1253 int delete_w_handle(const char *info, void *handle)
1254 {
1255     ZebraHandle zh = (ZebraHandle) handle;
1256     ISAM_P pos;
1257     ASSERTZH;
1258
1259     if (*info == sizeof(pos))
1260     {
1261         memcpy (&pos, info+1, sizeof(pos));
1262         isamb_unlink(zh->reg->isamb, pos);
1263     }
1264     return 0;
1265 }
1266
1267 static int delete_SU_handle(void *handle, int ord)
1268 {
1269     ZebraHandle zh = (ZebraHandle) handle;
1270     char ord_buf[20];
1271     int ord_len;
1272
1273     ord_len = key_SU_encode (ord, ord_buf);
1274     ord_buf[ord_len] = '\0';
1275
1276     assert (zh->reg->isamb);
1277     dict_delete_subtree(zh->reg->dict, ord_buf,
1278                         zh, delete_w_handle);
1279     return 0;
1280 }
1281
1282 ZEBRA_RES zebra_drop_database  (ZebraHandle zh, const char *database)
1283 {
1284     ZEBRA_RES ret = ZEBRA_OK;
1285     ASSERTZH;
1286     yaz_log(log_level, "zebra_drop_database");
1287     zh->errCode = 0;
1288
1289     if (zebra_select_database (zh, database) == ZEBRA_FAIL)
1290         return ZEBRA_FAIL;
1291     if (zebra_begin_trans (zh, 1) == ZEBRA_FAIL)
1292         return ZEBRA_FAIL;
1293     if (zh->reg->isamb)
1294     {
1295         zebraExplain_curDatabase (zh->reg->zei, database);
1296         
1297         zebraExplain_trav_ord(zh->reg->zei, zh, delete_SU_handle);
1298         zebraExplain_removeDatabase(zh->reg->zei, zh);
1299     }
1300     else
1301     {
1302         yaz_log(YLOG_WARN, "drop database only supported for isam:b");
1303         ret = ZEBRA_FAIL;
1304     }
1305     zebra_end_trans (zh);
1306     return ret;
1307 }
1308
1309 ZEBRA_RES zebra_create_database (ZebraHandle zh, const char *database)
1310 {
1311     ASSERTZH;
1312     yaz_log(log_level, "zebra_create_database %s", database);
1313     assert(database);
1314     zh->errCode = 0;
1315
1316     if (zebra_select_database (zh, database) == ZEBRA_FAIL)
1317         return ZEBRA_FAIL;
1318     if (zebra_begin_trans (zh, 1))
1319         return ZEBRA_FAIL;
1320
1321     /* announce database */
1322     if (zebraExplain_newDatabase (zh->reg->zei, database, 0 
1323                                   /* explainDatabase */))
1324     {
1325         zebra_end_trans (zh);
1326         zh->errCode = YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED;
1327         zh->errString = "database already exist";
1328         return ZEBRA_FAIL;
1329     }
1330     return zebra_end_trans (zh);
1331 }
1332
1333 int zebra_string_norm (ZebraHandle zh, unsigned reg_id,
1334                        const char *input_str, int input_len,
1335                        char *output_str, int output_len)
1336 {
1337     WRBUF wrbuf;
1338     ASSERTZH;
1339     assert(input_str);
1340     assert(output_str);
1341     yaz_log(log_level, "zebra_string_norm ");
1342     zh->errCode = 0;
1343     if (!zh->reg->zebra_maps)
1344         return -1;
1345     wrbuf = zebra_replace(zh->reg->zebra_maps, reg_id, "",
1346                           input_str, input_len);
1347     if (!wrbuf)
1348         return -2;
1349     if (wrbuf_len(wrbuf) >= output_len)
1350         return -3;
1351     if (wrbuf_len(wrbuf))
1352         memcpy (output_str, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
1353     output_str[wrbuf_len(wrbuf)] = '\0';
1354     return wrbuf_len(wrbuf);
1355 }
1356
1357 static void zebra_set_state (ZebraHandle zh, int val, int seqno)
1358 {
1359     char state_fname[256];
1360     char *fname;
1361     long p = getpid();
1362     FILE *f;
1363     ASSERTZH;
1364     yaz_log(log_level, "zebra_set_state v=%d seq=%d", val, seqno);
1365     zh->errCode = 0;
1366
1367     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1368     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1369     f = fopen (fname, "w");
1370
1371     yaz_log (YLOG_DEBUG, "zebra_set_state: %c %d %ld", val, seqno, p);
1372     fprintf (f, "%c %d %ld\n", val, seqno, p);
1373     fclose (f);
1374     xfree(fname);
1375 }
1376
1377 static void zebra_get_state (ZebraHandle zh, char *val, int *seqno)
1378 {
1379     char state_fname[256];
1380     char *fname;
1381     FILE *f;
1382
1383     ASSERTZH;
1384     yaz_log(log_level, "zebra_get_state ");
1385     zh->errCode = 0;
1386     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1387     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1388     f = fopen (fname, "r");
1389     *val = 'o';
1390     *seqno = 0;
1391
1392     if (f)
1393     {
1394         fscanf (f, "%c %d", val, seqno);
1395         fclose (f);
1396     }
1397     xfree(fname);
1398 }
1399
1400 ZEBRA_RES zebra_begin_read (ZebraHandle zh)
1401 {
1402     return zebra_begin_trans(zh, 0);
1403 }
1404
1405 ZEBRA_RES zebra_end_read (ZebraHandle zh)
1406 {
1407     return zebra_end_trans(zh);
1408 }
1409
1410 static void read_res_for_transaction(ZebraHandle zh)
1411 {
1412     const char *group = res_get(zh->res, "group");
1413     const char *v;
1414     /* FIXME - do we still use groups ?? */
1415     
1416     zh->m_group = group;
1417     v = res_get_prefix(zh->res, "followLinks", group, "1");
1418     zh->m_follow_links = atoi(v);
1419
1420     zh->m_record_id = res_get_prefix(zh->res, "recordId", group, 0);
1421     zh->m_record_type = res_get_prefix(zh->res, "recordType", group, 0);
1422
1423     v = res_get_prefix(zh->res, "storeKeys", group, "1");
1424     zh->m_store_keys = atoi(v);
1425
1426     v = res_get_prefix(zh->res, "storeData", group, "1");
1427     zh->m_store_data = atoi(v);
1428
1429     v = res_get_prefix(zh->res, "explainDatabase", group, "0");
1430     zh->m_explain_database = atoi(v);
1431
1432     v = res_get_prefix(zh->res, "openRW", group, "1");
1433     zh->m_flag_rw = atoi(v);
1434
1435     v = res_get_prefix(zh->res, "fileVerboseLimit", group, "100000");
1436     zh->m_file_verbose_limit = atoi(v);
1437 }
1438
1439 ZEBRA_RES zebra_begin_trans(ZebraHandle zh, int rw)
1440 {
1441     ASSERTZH;
1442     zebra_select_default_database(zh);
1443     if (!zh->res)
1444     {
1445         zh->errCode = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1446         zh->errString = "zebra_begin_trans: no database selected";
1447         return ZEBRA_FAIL;
1448     }
1449     ASSERTZHRES;
1450     yaz_log(log_level, "zebra_begin_trans rw=%d",rw);
1451
1452     if (zh->user_perm)
1453     {
1454         if (rw && !strchr(zh->user_perm, 'w'))
1455         {
1456             zh->errCode = 
1457                 YAZ_BIB1_ES_PERMISSION_DENIED_ON_ES_CANNOT_MODIFY_OR_DELETE;
1458             zh->errString = 0;
1459             return ZEBRA_FAIL;
1460         }
1461     }
1462
1463     assert (zh->res);
1464     if (rw)
1465     {
1466         int pass;
1467         int seqno = 0;
1468         char val = '?';
1469         const char *rval = 0;
1470         
1471         (zh->trans_no++);
1472         if (zh->trans_w_no)
1473         {
1474             read_res_for_transaction(zh);
1475             return 0;
1476         }
1477         if (zh->trans_no != 1)
1478         {
1479             zh->errCode = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1480             zh->errString = "zebra_begin_trans: write trans not allowed within read trans";
1481             return ZEBRA_FAIL;
1482         }
1483         if (zh->reg)
1484         {
1485             resultSetInvalidate (zh);
1486             zebra_register_close (zh->service, zh->reg);
1487         }
1488         zh->trans_w_no = zh->trans_no;
1489
1490         zh->errCode = 0;
1491         
1492         zh->records_inserted = 0;
1493         zh->records_updated = 0;
1494         zh->records_deleted = 0;
1495         zh->records_processed = 0;
1496         
1497 #if HAVE_SYS_TIMES_H
1498         times (&zh->tms1);
1499 #endif
1500         /* lock */
1501         if (zh->shadow_enable)
1502             rval = res_get (zh->res, "shadow");
1503         
1504         for (pass = 0; pass < 2; pass++)
1505         {
1506             if (rval)
1507             {
1508                 zebra_lock_r (zh->lock_normal);
1509                 zebra_lock_w (zh->lock_shadow);
1510             }
1511             else
1512             {
1513                 zebra_lock_w (zh->lock_normal);
1514                 zebra_lock_w (zh->lock_shadow);
1515             }
1516             
1517             zebra_get_state (zh, &val, &seqno);
1518             if (val == 'c')
1519             {
1520                 yaz_log (YLOG_WARN, "previous transaction didn't finish commit");
1521                 zebra_unlock (zh->lock_shadow);
1522                 zebra_unlock (zh->lock_normal);
1523                 zebra_commit (zh);
1524                 continue;
1525             }
1526             else if (val == 'd')
1527             {
1528                 if (rval)
1529                 {
1530                     BFiles bfs = bfs_create (res_get (zh->res, "shadow"),
1531                                              zh->path_reg);
1532                     yaz_log (YLOG_WARN, "previous transaction didn't reach commit");
1533                     bf_commitClean (bfs, rval);
1534                     bfs_destroy (bfs);
1535             }
1536                 else
1537                 {
1538                     yaz_log (YLOG_WARN, "your previous transaction didn't finish");
1539                 }
1540             }
1541             break;
1542         }
1543         if (pass == 2)
1544         {
1545             yaz_log (YLOG_FATAL, "zebra_begin_trans couldn't finish commit");
1546             abort();
1547             return ZEBRA_FAIL;
1548         }
1549         zebra_set_state (zh, 'd', seqno);
1550         
1551         zh->reg = zebra_register_open (zh->service, zh->reg_name,
1552                                        1, rval ? 1 : 0, zh->res,
1553                                        zh->path_reg);
1554         if (zh->reg)
1555             zh->reg->seqno = seqno;
1556         else
1557         {
1558             zebra_set_state (zh, 'o', seqno);
1559             
1560             zebra_unlock (zh->lock_shadow);
1561             zebra_unlock (zh->lock_normal);
1562
1563             zh->trans_no--;
1564             zh->trans_w_no = 0;
1565
1566             zh->errCode = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1567             zh->errString = "zebra_begin_trans: cannot open register";
1568             yaz_log(YLOG_FATAL, zh->errString);
1569             return ZEBRA_FAIL;
1570         }
1571     }
1572     else
1573     {
1574         int dirty = 0;
1575         char val;
1576         int seqno;
1577         
1578         (zh->trans_no)++;
1579         
1580         if (zh->trans_no != 1)
1581         {
1582             zebra_flush_reg (zh);
1583             return ZEBRA_OK;
1584         }
1585         zh->errCode = 0;
1586 #if HAVE_SYS_TIMES_H
1587         times (&zh->tms1);
1588 #endif
1589         if (!zh->res)
1590         {
1591             (zh->trans_no)--;
1592             zh->errCode = YAZ_BIB1_DATABASE_UNAVAILABLE;
1593             return ZEBRA_FAIL;
1594         }
1595         if (!zh->lock_normal || !zh->lock_shadow)
1596         {
1597             (zh->trans_no)--;
1598             zh->errCode = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1599             return ZEBRA_FAIL;
1600         }
1601         zebra_get_state (zh, &val, &seqno);
1602         if (val == 'd')
1603             val = 'o';
1604         
1605         if (!zh->reg)
1606             dirty = 1;
1607         else if (seqno != zh->reg->seqno)
1608         {
1609             yaz_log (YLOG_DEBUG, "reopen seqno cur/old %d/%d",
1610                      seqno, zh->reg->seqno);
1611             dirty = 1;
1612         }
1613         else if (zh->reg->last_val != val)
1614         {
1615             yaz_log (YLOG_DEBUG, "reopen last cur/old %d/%d",
1616                      val, zh->reg->last_val);
1617             dirty = 1;
1618         }
1619         if (!dirty)
1620             return ZEBRA_OK;
1621         
1622         if (val == 'c')
1623             zebra_lock_r (zh->lock_shadow);
1624         else
1625             zebra_lock_r (zh->lock_normal);
1626         
1627         if (zh->reg)
1628         {
1629             resultSetInvalidate (zh);
1630             zebra_register_close (zh->service, zh->reg);
1631         }
1632         zh->reg = zebra_register_open (zh->service, zh->reg_name,
1633                                        0, val == 'c' ? 1 : 0,
1634                                        zh->res, zh->path_reg);
1635         if (!zh->reg)
1636         {
1637             zebra_unlock (zh->lock_normal);
1638             zebra_unlock (zh->lock_shadow);
1639             zh->trans_no--;
1640             zh->errCode = YAZ_BIB1_DATABASE_UNAVAILABLE;
1641             return ZEBRA_FAIL;
1642         }
1643         zh->reg->last_val = val;
1644         zh->reg->seqno = seqno;
1645     }
1646     read_res_for_transaction(zh);
1647     return ZEBRA_OK;
1648 }
1649
1650 ZEBRA_RES zebra_end_trans (ZebraHandle zh)
1651 {
1652     ZebraTransactionStatus dummy;
1653     ASSERTZH;
1654     yaz_log(log_level, "zebra_end_trans");
1655     return zebra_end_transaction(zh, &dummy);
1656 }
1657
1658 ZEBRA_RES zebra_end_transaction (ZebraHandle zh, ZebraTransactionStatus *status)
1659 {
1660     char val;
1661     int seqno;
1662     const char *rval;
1663
1664     ASSERTZH;
1665     assert(status);
1666     yaz_log(log_level, "zebra_end_transaction");
1667
1668     status->processed = 0;
1669     status->inserted  = 0;
1670     status->updated   = 0;
1671     status->deleted   = 0;
1672     status->utime     = 0;
1673     status->stime     = 0;
1674
1675     if (!zh->res || !zh->reg)
1676     {
1677         zh->errCode = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1678         zh->errString = "zebra_end_trans: no open transaction";
1679         return ZEBRA_FAIL;
1680     }
1681     if (zh->trans_no != zh->trans_w_no)
1682     {
1683         zh->trans_no--;
1684         if (zh->trans_no != 0)
1685             return ZEBRA_OK;
1686
1687         /* release read lock */
1688
1689         zebra_unlock (zh->lock_normal);
1690         zebra_unlock (zh->lock_shadow);
1691     }
1692     else
1693     {   /* release write lock */
1694         zh->trans_no--;
1695         zh->trans_w_no = 0;
1696         
1697         yaz_log (YLOG_DEBUG, "zebra_end_trans");
1698         rval = res_get (zh->res, "shadow");
1699         
1700         zebraExplain_runNumberIncrement (zh->reg->zei, 1);
1701         
1702         zebra_flush_reg (zh);
1703         
1704         resultSetInvalidate (zh);
1705
1706         zebra_register_close (zh->service, zh->reg);
1707         zh->reg = 0;
1708         
1709         yaz_log (YLOG_LOG, "Records: "ZINT_FORMAT" i/u/d "
1710                         ZINT_FORMAT"/"ZINT_FORMAT"/"ZINT_FORMAT, 
1711                  zh->records_processed, zh->records_inserted,
1712                  zh->records_updated, zh->records_deleted);
1713         
1714         status->processed = (int) zh->records_processed;
1715         status->inserted = (int) zh->records_inserted;
1716         status->updated = (int) zh->records_updated;
1717         status->deleted = (int) zh->records_deleted;
1718         
1719         zebra_get_state (zh, &val, &seqno);
1720         if (val != 'd')
1721         {
1722             BFiles bfs = bfs_create (rval, zh->path_reg);
1723             yaz_log (YLOG_DEBUG, "deleting shadow val=%c", val);
1724             bf_commitClean (bfs, rval);
1725             bfs_destroy (bfs);
1726         }
1727         if (!rval)
1728             seqno++;
1729         zebra_set_state (zh, 'o', seqno);
1730         
1731         zebra_unlock (zh->lock_shadow);
1732         zebra_unlock (zh->lock_normal);
1733         
1734     }
1735 #if HAVE_SYS_TIMES_H
1736     times (&zh->tms2);
1737     yaz_log (log_level, "user/system: %ld/%ld",
1738           (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1739           (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1740     
1741     status->utime = (long) (zh->tms2.tms_utime - zh->tms1.tms_utime);
1742     status->stime = (long) (zh->tms2.tms_stime - zh->tms1.tms_stime);
1743 #endif
1744     return ZEBRA_OK;
1745 }
1746
1747 int zebra_repository_update (ZebraHandle zh, const char *path)
1748 {
1749     ASSERTZH;
1750     assert(path);
1751     zh->errCode = 0;
1752     yaz_log (log_level, "updating %s", path);
1753     repositoryUpdate (zh, path);
1754     return zh->errCode;
1755 }
1756
1757 int zebra_repository_delete (ZebraHandle zh, const char *path)
1758 {
1759     ASSERTZH;
1760     assert(path);
1761     zh->errCode = 0;
1762     yaz_log (log_level, "deleting %s", path);
1763     repositoryDelete (zh, path);
1764     return zh->errCode;
1765 }
1766
1767 int zebra_repository_show (ZebraHandle zh, const char *path)
1768 {
1769     ASSERTZH;
1770     assert(path);
1771     yaz_log(log_level, "zebra_repository_show");
1772     zh->errCode = 0;
1773     repositoryShow (zh, path);
1774     return zh->errCode;
1775 }
1776
1777 static int zebra_commit_ex(ZebraHandle zh, int clean_only)
1778 {
1779     int seqno;
1780     char val;
1781     const char *rval;
1782     BFiles bfs;
1783     ASSERTZH;
1784     zh->errCode = 0;
1785
1786     zebra_select_default_database(zh);
1787     if (!zh->res)
1788     {
1789         zh->errCode = YAZ_BIB1_DATABASE_UNAVAILABLE;
1790         return -1;
1791     }
1792     rval = res_get (zh->res, "shadow");    
1793     if (!rval)
1794     {
1795         yaz_log (YLOG_WARN, "Cannot perform commit - No shadow area defined");
1796         return 0;
1797     }
1798
1799     zebra_lock_w (zh->lock_normal);
1800     zebra_lock_r (zh->lock_shadow);
1801
1802     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1803
1804     zebra_get_state (zh, &val, &seqno);
1805
1806     if (rval && *rval)
1807         bf_cache (bfs, rval);
1808     if (bf_commitExists (bfs))
1809     {
1810         if (clean_only)
1811             zebra_set_state (zh, 'd', seqno);
1812         else
1813         {
1814             zebra_set_state (zh, 'c', seqno);
1815             
1816             yaz_log (YLOG_DEBUG, "commit start");
1817             bf_commitExec (bfs);
1818 #ifndef WIN32
1819             sync ();
1820 #endif
1821         }
1822         yaz_log (YLOG_DEBUG, "commit clean");
1823         bf_commitClean (bfs, rval);
1824         seqno++;
1825         zebra_set_state (zh, 'o', seqno);
1826     }
1827     else
1828     {
1829         yaz_log (log_level, "nothing to commit");
1830     }
1831     bfs_destroy (bfs);
1832
1833     zebra_unlock (zh->lock_shadow);
1834     zebra_unlock (zh->lock_normal);
1835     return 0;
1836 }
1837
1838 ZEBRA_RES zebra_clean(ZebraHandle zh)
1839 {
1840     ASSERTZH;
1841     yaz_log(log_level, "zebra_clean");
1842     return zebra_commit_ex(zh, 1);
1843 }
1844
1845 ZEBRA_RES zebra_commit(ZebraHandle zh)
1846 {
1847     ASSERTZH;
1848     yaz_log(log_level, "zebra_commit");
1849     return zebra_commit_ex(zh, 0);
1850 }
1851
1852 ZEBRA_RES zebra_init(ZebraHandle zh)
1853 {
1854     const char *rval;
1855     BFiles bfs = 0;
1856     ASSERTZH;
1857     yaz_log(log_level, "zebra_init");
1858     zh->errCode = 0;
1859
1860     zebra_select_default_database(zh);
1861     if (!zh->res)
1862     {
1863         zh->errCode = YAZ_BIB1_DATABASE_UNAVAILABLE;
1864         return ZEBRA_FAIL;
1865     }
1866     rval = res_get (zh->res, "shadow");
1867
1868     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1869     if (!bfs)
1870         return ZEBRA_FAIL;
1871     if (rval && *rval)
1872         bf_cache (bfs, rval);
1873     
1874     bf_reset (bfs);
1875     bfs_destroy (bfs);
1876     zebra_set_state (zh, 'o', 0);
1877     return ZEBRA_OK;
1878 }
1879
1880 ZEBRA_RES zebra_compact(ZebraHandle zh)
1881 {
1882     BFiles bfs;
1883     ASSERTZH;
1884     yaz_log(log_level, "zebra_compact");
1885     zh->errCode = 0;
1886     if (!zh->res)
1887     {
1888         zh->errCode = YAZ_BIB1_DATABASE_UNAVAILABLE;
1889         return ZEBRA_FAIL;
1890     }
1891     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1892     inv_compact (bfs);
1893     bfs_destroy (bfs);
1894     return ZEBRA_OK;
1895 }
1896
1897 void zebra_result(ZebraHandle zh, int *code, char **addinfo)
1898 {
1899     ASSERTZH;
1900     yaz_log(log_level, "zebra_result");
1901     *code = zh->errCode;
1902     *addinfo = zh->errString;
1903 }
1904
1905 void zebra_shadow_enable(ZebraHandle zh, int value)
1906 {
1907     ASSERTZH;
1908     yaz_log(log_level, "zebra_shadow_enable");
1909     zh->errCode = 0;
1910     zh->shadow_enable = value;
1911 }
1912
1913 ZEBRA_RES zebra_octet_term_encoding(ZebraHandle zh, const char *encoding)
1914 {
1915     ASSERTZH;
1916     assert(encoding);
1917     yaz_log(log_level, "zebra_octet_term_encoding");
1918     zh->errCode = 0;
1919
1920     if (zh->iconv_to_utf8 != 0)
1921         yaz_iconv_close(zh->iconv_to_utf8);
1922     if (zh->iconv_from_utf8 != 0)
1923         yaz_iconv_close(zh->iconv_from_utf8);
1924     
1925     zh->iconv_to_utf8 =
1926         yaz_iconv_open ("UTF-8", encoding);
1927     if (zh->iconv_to_utf8 == 0)
1928         yaz_log (YLOG_WARN, "iconv: %s to UTF-8 unsupported", encoding);
1929     zh->iconv_from_utf8 =
1930         yaz_iconv_open (encoding, "UTF-8");
1931     if (zh->iconv_to_utf8 == 0)
1932         yaz_log (YLOG_WARN, "iconv: UTF-8 to %s unsupported", encoding);
1933
1934     return ZEBRA_OK;
1935 }
1936
1937 ZEBRA_RES zebra_record_encoding (ZebraHandle zh, const char *encoding)
1938 {
1939     ASSERTZH;
1940     yaz_log(log_level, "zebra_record_encoding");
1941     zh->errCode = 0;
1942     xfree(zh->record_encoding);
1943     zh->record_encoding = 0;
1944     if (encoding)
1945         zh->record_encoding = xstrdup (encoding);
1946     return ZEBRA_OK;
1947 }
1948
1949 void zebra_set_resource(ZebraHandle zh, const char *name, const char *value)
1950 {
1951     ASSERTZH;
1952     assert(name);
1953     assert(value);
1954     yaz_log(log_level, "zebra_set_resource %s:%s", name, value);
1955     zh->errCode = 0;
1956     res_set(zh->res, name, value);
1957 }
1958
1959 const char *zebra_get_resource(ZebraHandle zh,
1960                                const char *name, const char *defaultvalue)
1961 {
1962     const char *v;
1963     ASSERTZH;
1964     assert(name);
1965     assert(defaultvalue);
1966     v = res_get_def (zh->res, name, (char *)defaultvalue);
1967     zh->errCode = 0;
1968     yaz_log(log_level, "zebra_get_resource %s:%s", name, v);
1969     return v;
1970 }
1971
1972 /* moved from zebra_api_ext.c by pop */
1973 /* FIXME: Should this really be public??? -Heikki */
1974
1975 int zebra_trans_no (ZebraHandle zh)
1976 {
1977     ASSERTZH;
1978     yaz_log(log_level, "zebra_trans_no");
1979     return zh->trans_no;
1980 }
1981
1982 int zebra_get_shadow_enable (ZebraHandle zh)
1983 {
1984     ASSERTZH;
1985     yaz_log(log_level, "zebra_get_shadow_enable");
1986     return zh->shadow_enable;
1987 }
1988
1989 void zebra_set_shadow_enable (ZebraHandle zh, int value)
1990 {
1991     ASSERTZH;
1992     yaz_log(log_level, "zebra_set_shadow_enable %d",value);
1993     zh->shadow_enable = value;
1994 }
1995
1996 /* Used by Perl API.. Added the record buffer dup to zebra_records_retrieve
1997    so that it's identicical to the original api_records_retrieve */
1998 void api_records_retrieve (ZebraHandle zh, ODR stream,
1999                            const char *setname, Z_RecordComposition *comp,
2000                            oid_value input_format, int num_recs,
2001                            ZebraRetrievalRecord *recs)
2002 {
2003     zebra_records_retrieve(zh, stream, setname, comp, input_format,
2004                            num_recs, recs);
2005 }
2006
2007 /* ---------------------------------------------------------------------------
2008   Record insert(=update), delete 
2009
2010   If sysno is provided, then it's used to identify the record.
2011   If not, and match_criteria is provided, then sysno is guessed
2012   If not, and a record is provided, then sysno is got from there
2013 NOTE: Now returns 0 at success and updates sysno, which is an int*
2014   20-jun-2003 Heikki
2015 */
2016
2017 int zebra_add_record(ZebraHandle zh,
2018                      const char *buf, int buf_size)
2019 {
2020     SYSNO sysno = 0;
2021     return zebra_update_record(zh, 0, &sysno, 0, 0, buf, buf_size, 0);
2022 }
2023
2024 ZEBRA_RES zebra_insert_record (ZebraHandle zh, 
2025                                const char *recordType,
2026                                SYSNO *sysno, const char *match,
2027                                const char *fname,
2028                                const char *buf, int buf_size, int force_update)
2029 {
2030     ZEBRA_RES res;
2031     ASSERTZH;
2032     assert(sysno);
2033     assert(buf);
2034     yaz_log(log_level, "zebra_insert_record sysno=" ZINT_FORMAT, *sysno);
2035
2036     if (buf_size < 1)
2037         buf_size = strlen(buf);
2038
2039     if (zebra_begin_trans(zh, 1) == ZEBRA_FAIL)
2040         return ZEBRA_FAIL;
2041     res = buffer_extract_record (zh, buf, buf_size, 
2042                                  0, /* delete_flag  */
2043                                  0, /* test_mode */
2044                                  recordType,
2045                                  sysno,   
2046                                  match, fname,
2047                                  0, 
2048                                  0); /* allow_update */
2049     zebra_end_trans(zh); 
2050     return res; 
2051 }
2052
2053 ZEBRA_RES zebra_update_record (ZebraHandle zh, 
2054                                const char *recordType,
2055                                SYSNO* sysno, const char *match,
2056                                const char *fname,
2057                                const char *buf, int buf_size,
2058                                int force_update)
2059 {
2060     ZEBRA_RES res;
2061     ASSERTZH;
2062     assert(sysno);
2063     assert(buf);
2064
2065     yaz_log(log_level, "zebra_update_record sysno=" ZINT_FORMAT, *sysno);
2066
2067     if (buf_size < 1) buf_size = strlen(buf);
2068
2069     if (zebra_begin_trans(zh, 1) == ZEBRA_FAIL)
2070         return ZEBRA_FAIL;
2071     res = buffer_extract_record (zh, buf, buf_size, 
2072                                  0, /* delete_flag */
2073                                  0, /* test_mode */
2074                                  recordType,
2075                                  sysno,   
2076                                  match, fname,
2077                                  force_update, 
2078                                  1); /* allow_update */
2079     zebra_end_trans(zh); 
2080     return res; 
2081 }
2082
2083 ZEBRA_RES zebra_delete_record (ZebraHandle zh, 
2084                                const char *recordType,
2085                                SYSNO *sysno, const char *match,
2086                                const char *fname,
2087                                const char *buf, int buf_size,
2088                                int force_update) 
2089 {
2090     ZEBRA_RES res;
2091     ASSERTZH;
2092     assert(sysno);
2093     assert(buf);
2094     yaz_log(log_level, "zebra_delete_record sysno=" ZINT_FORMAT, *sysno);
2095
2096     if (buf_size < 1) buf_size = strlen(buf);
2097
2098     if (zebra_begin_trans(zh, 1) == ZEBRA_FAIL)
2099         return ZEBRA_FAIL;
2100     res = buffer_extract_record (zh, buf, buf_size,
2101                                  1, /* delete_flag */
2102                                  0, /* test_mode */
2103                                  recordType,
2104                                  sysno,
2105                                  match,fname,
2106                                  force_update,
2107                                  1); /* allow_update */
2108     zebra_end_trans(zh);
2109     return res;
2110 }
2111
2112 /* ---------------------------------------------------------------------------
2113   Searching 
2114 */
2115
2116 ZEBRA_RES zebra_search_PQF(ZebraHandle zh, const char *pqf_query,
2117                            const char *setname, zint *numhits)
2118 {
2119     zint hits = 0;
2120     ZEBRA_RES res = ZEBRA_OK;
2121     Z_RPNQuery *query;
2122     ODR odr = odr_createmem(ODR_ENCODE);
2123     ASSERTZH;
2124     assert(pqf_query);
2125     assert(setname);
2126
2127     yaz_log(log_level, "zebra_search_PQF s=%s q=%s", setname, pqf_query);
2128     
2129     query = p_query_rpn (odr, PROTO_Z3950, pqf_query);
2130     
2131     if (!query)
2132     {
2133         yaz_log (YLOG_WARN, "bad query %s\n", pqf_query);
2134         zh->errCode = YAZ_BIB1_MALFORMED_QUERY;
2135         res = ZEBRA_FAIL;
2136     }
2137     else
2138         res = zebra_search_RPN(zh, odr, query, setname, &hits);
2139     
2140     odr_destroy(odr);
2141
2142     yaz_log(log_level, "Hits: " ZINT_FORMAT, hits);
2143
2144     if (numhits)
2145         *numhits = hits;
2146
2147     return res;
2148 }
2149
2150 /* ---------------------------------------------------------------------------
2151   Sort - a simplified interface, with optional read locks.
2152 */
2153 int zebra_sort_by_specstr (ZebraHandle zh, ODR stream,
2154                            const char *sort_spec,
2155                            const char *output_setname,
2156                            const char **input_setnames) 
2157 {
2158     int num_input_setnames = 0;
2159     int sort_status = 0;
2160     Z_SortKeySpecList *sort_sequence;
2161     ASSERTZH;
2162     assert(stream);
2163     assert(sort_spec);
2164     assert(output_setname);
2165     assert(input_setnames);
2166     sort_sequence = yaz_sort_spec (stream, sort_spec);
2167     yaz_log(log_level, "sort (FIXME) ");
2168     if (!sort_sequence)
2169     {
2170         yaz_log(YLOG_WARN, "invalid sort specs '%s'", sort_spec);
2171         zh->errCode = YAZ_BIB1_CANNOT_SORT_ACCORDING_TO_SEQUENCE;
2172         return -1;
2173     }
2174     
2175     /* we can do this, since the perl typemap code for char** will 
2176        put a NULL at the end of list */
2177     while (input_setnames[num_input_setnames]) num_input_setnames++;
2178
2179     if (zebra_begin_read (zh))
2180         return -1;
2181     
2182     resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
2183                    output_setname, sort_sequence, &sort_status);
2184     
2185     zebra_end_read(zh);
2186     return sort_status;
2187 }
2188
2189 /* ---------------------------------------------------------------------------
2190   Get BFS for Zebra system (to make alternative storage methods)
2191 */
2192 struct BFiles_struct *zebra_get_bfs(ZebraHandle zh)
2193 {
2194     if (zh && zh->reg)
2195         return zh->reg->bfs;
2196     return 0;
2197 }
2198
2199
2200 /* ---------------------------------------------------------------------------
2201   Set limit for search/scan
2202 */
2203 ZEBRA_RES zebra_set_limit(ZebraHandle zh, int exclude_flag, zint *ids)
2204 {
2205     ASSERTZH;
2206     zebra_limit_destroy(zh->m_limit);
2207     zh->m_limit = zebra_limit_create(exclude_flag, ids);
2208     return ZEBRA_OK;
2209 }