Align Zebra API more so that ZEBRA_RES is used to signal error/OK.
[idzebra-moved-to-github.git] / index / zebraapi.c
1 /* $Id: zebraapi.c,v 1.168 2005-05-11 12:39:37 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     zebra_clearError(zh);
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     zh->nmem_error = nmem_create();
153
154     return zh;
155 }
156
157 ZebraService zebra_start (const char *configName)
158 {
159     return zebra_start_res(configName, 0, 0);
160 }
161
162 ZebraService zebra_start_res (const char *configName, Res def_res, Res over_res)
163 {
164     Res res;
165
166     if (!log_level_initialized)
167     {
168         log_level = yaz_log_module_level("zebraapi");
169         log_level_initialized = 1;
170     }
171
172     yaz_log(log_level, "zebra_start %s",configName);
173     assert(configName);
174
175     if ((res = res_open (configName, def_res, over_res)))
176     {
177         ZebraService zh = xmalloc(sizeof(*zh));
178
179         yaz_log (YLOG_DEBUG, "Read resources `%s'", configName);
180         
181         zh->global_res = res;
182         zh->configName = xstrdup(configName);
183         zh->sessions = 0;
184         
185         zebra_chdir (zh);
186         
187         zebra_mutex_cond_init (&zh->session_lock);
188         if (!res_get (zh->global_res, "passwd"))
189             zh->passwd_db = NULL;
190         else
191         {
192             zh->passwd_db = passwd_db_open ();
193             if (!zh->passwd_db)
194                 yaz_log (YLOG_WARN|YLOG_ERRNO, "passwd_db_open failed");
195             else
196                 passwd_db_file (zh->passwd_db,
197                                 res_get (zh->global_res, "passwd"));
198         }
199         zh->path_root = res_get (zh->global_res, "root");
200         zh->nmem = nmem_create();
201         zh->record_classes = recTypeClass_create (zh->global_res, zh->nmem);
202         return zh;
203     }
204     return 0;
205 }
206
207 void zebra_filter_info(ZebraService zs, void *cd,
208                         void (*cb)(void *cd, const char *name))
209 {
210     ASSERTZS;
211     assert(cb);
212     recTypeClass_info(zs->record_classes, cd, cb);
213 }
214
215 void zebra_pidfname(ZebraService zs, char *path)
216 {
217     ASSERTZS;
218     zebra_lock_prefix (zs->global_res, path);
219     strcat(path, "zebrasrv.pid");
220 }
221
222 Dict dict_open_res (BFiles bfs, const char *name, int cache, int rw,
223                     int compact_flag, Res res)
224 {
225     int page_size = 4096;
226     char resource_str[200];
227     const char *v;
228     sprintf (resource_str, "dict.%.100s.pagesize", name);
229     assert(bfs);
230     assert(name);
231
232     v = res_get(res, resource_str);
233     if (v)
234     {
235         page_size = atoi(v);
236         yaz_log(YLOG_LOG, "Using custom dictionary page size %d for %s",
237                 page_size, name);
238     }
239     return dict_open(bfs, name, cache, rw, compact_flag, page_size);
240 }
241
242
243 static
244 struct zebra_register *zebra_register_open (ZebraService zs, const char *name,
245                                             int rw, int useshadow, Res res,
246                                             const char *reg_path)
247 {
248     struct zebra_register *reg;
249     int record_compression = REC_COMPRESS_NONE;
250     const char *recordCompression = 0;
251     const char *profilePath;
252     char cwd[1024];
253
254     ASSERTZS;
255     
256     reg = xmalloc(sizeof(*reg));
257
258     assert (name);
259     reg->name = xstrdup (name);
260
261     reg->seqno = 0;
262     reg->last_val = 0;
263
264     assert (res);
265
266     yaz_log (YLOG_DEBUG, "zebra_register_open rw=%d useshadow=%d p=%p n=%s rp=%s",
267              rw, useshadow, reg, name, reg_path ? reg_path : "(none)");
268     
269     reg->dh = data1_createx (DATA1_FLAG_XML);
270     if (!reg->dh)
271         return 0;
272     reg->bfs = bfs_create (res_get (res, "register"), reg_path);
273     if (!reg->bfs)
274     {
275         data1_destroy(reg->dh);
276         return 0;
277     }
278     if (useshadow)
279         bf_cache (reg->bfs, res_get (res, "shadow"));
280
281     getcwd(cwd, sizeof(cwd)-1);
282     profilePath = res_get_def(res, "profilePath", DEFAULT_PROFILE_PATH);
283     yaz_log(YLOG_DEBUG, "profilePath=%s cwd=%s", profilePath, cwd);
284
285     data1_set_tabpath (reg->dh, profilePath);
286     data1_set_tabroot (reg->dh, reg_path);
287     reg->recTypes = recTypes_init (zs->record_classes, reg->dh);
288
289     reg->zebra_maps = zebra_maps_open (res, reg_path);
290     reg->rank_classes = NULL;
291
292     reg->key_buf = 0;
293
294     reg->keys.buf_max = 0;
295     reg->keys.buf = 0;
296     reg->keys.codec_handle = iscz1_start();
297
298     reg->sortKeys.buf = 0;
299     reg->sortKeys.buf_max = 0;
300
301     reg->records = 0;
302     reg->dict = 0;
303     reg->sortIdx = 0;
304     reg->isams = 0;
305     reg->matchDict = 0;
306     reg->isamc = 0;
307     reg->isamb = 0;
308     reg->zei = 0;
309     reg->matchDict = 0;
310     reg->key_file_no = 0;
311     reg->ptr_i = 0;
312     
313     zebraRankInstall (reg, rank1_class);
314     zebraRankInstall (reg, rankzv_class);
315
316     recordCompression = res_get_def (res, "recordCompression", "none");
317     if (!strcmp (recordCompression, "none"))
318         record_compression = REC_COMPRESS_NONE;
319     if (!strcmp (recordCompression, "bzip2"))
320         record_compression = REC_COMPRESS_BZIP2;
321
322     if (!(reg->records = rec_open (reg->bfs, rw, record_compression)))
323     {
324         yaz_log (YLOG_WARN, "rec_open failed");
325         return 0;
326     }
327     if (rw)
328     {
329         reg->matchDict = dict_open_res (reg->bfs, GMATCH_DICT, 20, 1, 0, res);
330     }
331     if (!(reg->dict = dict_open_res (reg->bfs, FNAME_DICT, 40, rw, 0, res)))
332     {
333         yaz_log (YLOG_WARN, "dict_open failed");
334         return 0;
335     }
336     if (!(reg->sortIdx = sortIdx_open (reg->bfs, rw)))
337     {
338         yaz_log (YLOG_WARN, "sortIdx_open failed");
339         return 0;
340     }
341     if (res_get_match (res, "isam", "s", ISAM_DEFAULT))
342     {
343         struct ISAMS_M_s isams_m;
344         if (!(reg->isams = isams_open (reg->bfs, FNAME_ISAMS, rw,
345                                       key_isams_m(res, &isams_m))))
346         {
347             yaz_log (YLOG_WARN, "isams_open failed");
348             return 0;
349         }
350     }
351     if (res_get_match (res, "isam", "c", ISAM_DEFAULT))
352     {
353         struct ISAMC_M_s isamc_m;
354         if (!(reg->isamc = isamc_open (reg->bfs, FNAME_ISAMC,
355                                     rw, key_isamc_m(res, &isamc_m))))
356         {
357             yaz_log (YLOG_WARN, "isamc_open failed");
358             return 0;
359         }
360     }
361     if (res_get_match (res, "isam", "b", ISAM_DEFAULT))
362     {
363         struct ISAMC_M_s isamc_m;
364         
365         if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
366                                        rw, key_isamc_m(res, &isamc_m), 0)))
367         {
368             yaz_log (YLOG_WARN, "isamb_open failed");
369             return 0;
370         }
371     }
372     if (res_get_match (res, "isam", "bc", ISAM_DEFAULT))
373     {
374         struct ISAMC_M_s isamc_m;
375         
376         if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
377                                        rw, key_isamc_m(res, &isamc_m), 1)))
378         {
379             yaz_log (YLOG_WARN, "isamb_open failed");
380             return 0;
381         }
382     }
383     if (res_get_match (res, "isam", "null", ISAM_DEFAULT))
384     {
385         struct ISAMC_M_s isamc_m;
386         
387         if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
388                                        rw, key_isamc_m(res, &isamc_m), -1)))
389         {
390             yaz_log (YLOG_WARN, "isamb_open failed");
391             return 0;
392         }
393     }
394     reg->zei = zebraExplain_open (reg->records, reg->dh,
395                                   res, rw, reg,
396                                   explain_extract);
397     if (!reg->zei)
398     {
399         yaz_log (YLOG_WARN, "Cannot obtain EXPLAIN information");
400         return 0;
401     }
402     reg->active = 2;
403     yaz_log (YLOG_DEBUG, "zebra_register_open ok p=%p", reg);
404     return reg;
405 }
406
407 ZEBRA_RES zebra_admin_shutdown (ZebraHandle zh)
408 {
409     ASSERTZH;
410     yaz_log(log_level, "zebra_admin_shutdown");
411     zebra_clearError(zh);
412
413     zebra_mutex_cond_lock (&zh->service->session_lock);
414     zh->service->stop_flag = 1;
415     zebra_mutex_cond_unlock (&zh->service->session_lock);
416     return ZEBRA_OK;
417 }
418
419 ZEBRA_RES zebra_admin_start (ZebraHandle zh)
420 {
421     ZebraService zs;
422     ASSERTZH;
423     yaz_log(log_level, "zebra_admin_start");
424     zebra_clearError(zh);
425     zs = zh->service;
426     zebra_mutex_cond_lock (&zs->session_lock);
427     zebra_mutex_cond_unlock (&zs->session_lock);
428     return ZEBRA_OK;
429 }
430
431 static void zebra_register_close (ZebraService zs, struct zebra_register *reg)
432 {
433     ASSERTZS;
434     assert(reg);
435     yaz_log(YLOG_DEBUG, "zebra_register_close p=%p", reg);
436     reg->stop_flag = 0;
437     zebra_chdir (zs);
438     if (reg->records)
439     {
440         zebraExplain_close (reg->zei);
441         dict_close (reg->dict);
442         if (reg->matchDict)
443             dict_close (reg->matchDict);
444         sortIdx_close (reg->sortIdx);
445         if (reg->isams)
446             isams_close (reg->isams);
447         if (reg->isamc)
448             isamc_close (reg->isamc);
449         if (reg->isamb)
450             isamb_close (reg->isamb);
451         rec_close (&reg->records);
452     }
453
454     recTypes_destroy (reg->recTypes);
455     zebra_maps_close (reg->zebra_maps);
456     zebraRankDestroy (reg);
457     bfs_destroy (reg->bfs);
458     data1_destroy (reg->dh);
459
460     xfree(reg->sortKeys.buf);
461     xfree(reg->keys.buf);
462     if (reg->keys.codec_handle)
463         iscz1_stop(reg->keys.codec_handle);
464     xfree(reg->key_buf);
465     xfree(reg->name);
466     xfree(reg);
467 }
468
469 ZEBRA_RES zebra_stop(ZebraService zs)
470 {
471     if (!zs)
472         return ZEBRA_OK;
473     yaz_log (log_level, "zebra_stop");
474
475     while (zs->sessions)
476     {
477         zebra_close (zs->sessions);
478     }
479         
480     zebra_mutex_cond_destroy (&zs->session_lock);
481
482     if (zs->passwd_db)
483         passwd_db_close (zs->passwd_db);
484
485     recTypeClass_destroy(zs->record_classes);
486     nmem_destroy(zs->nmem);
487     res_close (zs->global_res);
488     xfree(zs->configName);
489     xfree(zs);
490     return ZEBRA_OK;
491 }
492
493 ZEBRA_RES zebra_close (ZebraHandle zh)
494 {
495     ZebraService zs;
496     struct zebra_session **sp;
497     int i;
498
499     yaz_log(log_level, "zebra_close");
500     if (!zh)
501         return ZEBRA_OK;
502     ASSERTZH;
503     zh->errCode = 0;
504     
505     zs = zh->service;
506     yaz_log (YLOG_DEBUG, "zebra_close zh=%p", zh);
507     resultSetDestroy (zh, -1, 0, 0);
508
509     if (zh->reg)
510         zebra_register_close (zh->service, zh->reg);
511     zebra_close_res (zh);
512
513     xfree(zh->record_encoding);
514
515     for (i = 0; i < zh->num_basenames; i++)
516         xfree(zh->basenames[i]);
517     xfree(zh->basenames);
518
519     if (zh->iconv_to_utf8 != 0)
520         yaz_iconv_close (zh->iconv_to_utf8);
521     if (zh->iconv_from_utf8 != 0)
522         yaz_iconv_close (zh->iconv_from_utf8);
523
524     zebra_mutex_cond_lock (&zs->session_lock);
525     zebra_lock_destroy (zh->lock_normal);
526     zebra_lock_destroy (zh->lock_shadow);
527     sp = &zs->sessions;
528     while (1)
529     {
530         assert (*sp);
531         if (*sp == zh)
532         {
533             *sp = (*sp)->next;
534             break;
535         }
536         sp = &(*sp)->next;
537     }
538     zebra_mutex_cond_unlock (&zs->session_lock);
539     xfree(zh->reg_name);
540     xfree(zh->user_perm);
541     zh->service = 0; /* more likely to trigger an assert */
542
543     zebra_limit_destroy(zh->m_limit);
544
545     nmem_destroy(zh->nmem_error);
546
547     xfree(zh->path_reg);
548     xfree(zh);
549     return ZEBRA_OK;
550 }
551
552 struct map_baseinfo {
553     ZebraHandle zh;
554     NMEM mem;
555     int num_bases;
556     char **basenames;
557     int new_num_bases;
558     char **new_basenames;
559     int new_num_max;
560 };
561
562 static Res zebra_open_res (ZebraHandle zh)
563 {
564     Res res = 0;
565     char fname[512];
566     ASSERTZH;
567     zh->errCode = 0;
568
569     if (zh->path_reg)
570     {
571         sprintf (fname, "%.200s/zebra.cfg", zh->path_reg);
572         res = res_open (fname, zh->service->global_res, 0);
573         if (!res)
574             res = zh->service->global_res;
575     }
576     else if (*zh->reg_name == 0)
577     {
578         res = zh->service->global_res;
579     }
580     else
581     {
582         yaz_log (YLOG_WARN, "no register root specified");
583         return 0;  /* no path for register - fail! */
584     }
585     return res;
586 }
587
588 static void zebra_close_res (ZebraHandle zh)
589 {
590     ASSERTZH;
591     zh->errCode = 0;
592     if (zh->res != zh->service->global_res)
593         res_close (zh->res);
594     zh->res = 0;
595 }
596
597 static void zebra_select_register (ZebraHandle zh, const char *new_reg)
598 {
599     ASSERTZH;
600     zh->errCode = 0;
601     if (zh->res && strcmp (zh->reg_name, new_reg) == 0)
602         return;
603     if (!zh->res)
604     {
605         assert (zh->reg == 0);
606         assert (*zh->reg_name == 0);
607     }
608     else
609     {
610         if (zh->reg)
611         {
612             resultSetInvalidate (zh);
613             zebra_register_close (zh->service, zh->reg);
614             zh->reg = 0;
615         }
616         zebra_close_res(zh);
617     }
618     xfree(zh->reg_name);
619     zh->reg_name = xstrdup (new_reg);
620
621     xfree(zh->path_reg);
622     zh->path_reg = 0;
623     if (zh->service->path_root)
624     {
625         zh->path_reg = xmalloc(strlen(zh->service->path_root) + 
626                                 strlen(zh->reg_name) + 3);
627         strcpy (zh->path_reg, zh->service->path_root);
628         if (*zh->reg_name)
629         {
630             strcat (zh->path_reg, "/");
631             strcat (zh->path_reg, zh->reg_name);
632         }
633     }
634     zh->res = zebra_open_res (zh);
635     
636     if (zh->lock_normal)
637         zebra_lock_destroy (zh->lock_normal);
638     zh->lock_normal = 0;
639
640     if (zh->lock_shadow)
641         zebra_lock_destroy (zh->lock_shadow);
642     zh->lock_shadow = 0;
643
644     if (zh->res)
645     {
646         char fname[512];
647         const char *lock_area  =res_get (zh->res, "lockDir");
648         
649         if (!lock_area && zh->path_reg)
650             res_set (zh->res, "lockDir", zh->path_reg);
651         sprintf (fname, "norm.%s.LCK", zh->reg_name);
652         zh->lock_normal =
653             zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
654         
655         sprintf (fname, "shadow.%s.LCK", zh->reg_name);
656         zh->lock_shadow =
657             zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
658
659         if (!zh->lock_normal || !zh->lock_shadow)
660         {
661             if (zh->lock_normal)
662             {
663                 zebra_lock_destroy(zh->lock_normal);
664                 zh->lock_normal = 0;
665             }
666             if (zh->lock_shadow)
667             {
668                 zebra_lock_destroy(zh->lock_shadow);
669                 zh->lock_shadow = 0;
670             }
671             zebra_close_res(zh);
672         }
673     }
674 }
675
676 void map_basenames_func (void *vp, const char *name, const char *value)
677 {
678     struct map_baseinfo *p = (struct map_baseinfo *) vp;
679     int i, no;
680     char fromdb[128], todb[8][128];
681
682     assert(value);
683     assert(name);
684     assert(vp);
685     
686     no =
687         sscanf (value, "%127s %127s %127s %127s %127s %127s %127s %127s %127s",
688                 fromdb, todb[0], todb[1], todb[2], todb[3], todb[4],
689                 todb[5], todb[6], todb[7]);
690     if (no < 2)
691         return ;
692     no--;
693     for (i = 0; i<p->num_bases; i++)
694         if (p->basenames[i] && !STRCASECMP (p->basenames[i], fromdb))
695         {
696             p->basenames[i] = 0;
697             for (i = 0; i < no; i++)
698             {
699                 if (p->new_num_bases == p->new_num_max)
700                     return;
701                 p->new_basenames[(p->new_num_bases)++] = 
702                     nmem_strdup (p->mem, todb[i]);
703             }
704             return;
705         }
706 }
707
708 int zebra_select_default_database(ZebraHandle zh)
709 {
710     if (!zh->res)
711     {
712         /* no database has been selected - so we select based on
713            resource setting (including group)
714         */
715         const char *group = res_get(zh->service->global_res, "group");
716         const char *v = res_get_prefix(zh->service->global_res,
717                                        "database", group, "Default");
718         return zebra_select_database(zh, v);
719     }
720     return 0;
721 }
722
723 void map_basenames (ZebraHandle zh, ODR stream,
724                     int *num_bases, char ***basenames)
725 {
726     struct map_baseinfo info;
727     struct map_baseinfo *p = &info;
728     int i;
729     ASSERTZH;
730     yaz_log(log_level, "map_basenames ");
731     assert(stream);
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     return zebra_select_databases (zh, 1, &basename);
763 }
764
765 ZEBRA_RES zebra_select_databases (ZebraHandle zh, int num_bases,
766                                   const char **basenames)
767 {
768     int i;
769     const char *cp;
770     int len = 0;
771     char *new_reg = 0;
772     ASSERTZH;
773     assert(basenames);
774
775     yaz_log(log_level, "zebra_select_databases n=%d [0]=%s",
776                     num_bases,basenames[0]);
777     zh->errCode = 0;
778     
779     if (num_bases < 1)
780     {
781         zh->errCode = YAZ_BIB1_COMBI_OF_SPECIFIED_DATABASES_UNSUPP;
782         return ZEBRA_FAIL;
783     }
784     for (i = 0; i < zh->num_basenames; i++)
785         xfree(zh->basenames[i]);
786     xfree(zh->basenames);
787     
788     zh->num_basenames = num_bases;
789     zh->basenames = xmalloc(zh->num_basenames * sizeof(*zh->basenames));
790     for (i = 0; i < zh->num_basenames; i++)
791         zh->basenames[i] = xstrdup (basenames[i]);
792
793     cp = strrchr(basenames[0], '/');
794     if (cp)
795     {
796         len = cp - basenames[0];
797         new_reg = xmalloc(len + 1);
798         memcpy (new_reg, basenames[0], len);
799         new_reg[len] = '\0';
800     }
801     else
802         new_reg = xstrdup ("");
803     for (i = 1; i<num_bases; i++)
804     {
805         const char *cp1;
806
807         cp1 = strrchr (basenames[i], '/');
808         if (cp)
809         {
810             if (!cp1)
811             {
812                 zh->errCode = YAZ_BIB1_COMBI_OF_SPECIFIED_DATABASES_UNSUPP;
813                 return -1;
814             }
815             if (len != cp1 - basenames[i] ||
816                 memcmp (basenames[i], new_reg, len))
817             {
818                 zh->errCode = YAZ_BIB1_COMBI_OF_SPECIFIED_DATABASES_UNSUPP;
819                 return -1;
820             }
821         }
822         else
823         {
824             if (cp1)
825             {
826                 zh->errCode = YAZ_BIB1_COMBI_OF_SPECIFIED_DATABASES_UNSUPP;
827                 return ZEBRA_FAIL;
828             }
829         }
830     }
831     zebra_select_register (zh, new_reg);
832     xfree(new_reg);
833     if (!zh->res)
834     {
835         zh->errCode = YAZ_BIB1_DATABASE_UNAVAILABLE;
836         return ZEBRA_FAIL;
837     }
838     if (!zh->lock_normal || !zh->lock_shadow)
839     {
840         zh->errCode = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
841         return ZEBRA_FAIL;
842     }
843     return ZEBRA_OK;
844 }
845
846 ZEBRA_RES zebra_search_RPN(ZebraHandle zh, ODR o, Z_RPNQuery *query,
847                            const char *setname, zint *hits)
848 {
849     ZEBRA_RES r;
850     ASSERTZH;
851     assert(o);
852     assert(query);
853     assert(hits);
854     assert(setname);
855     yaz_log(log_level, "zebra_search_rpn");
856     zebra_clearError(zh);
857     zh->hits = 0;
858     *hits = 0;
859
860     if (zebra_begin_read(zh) == ZEBRA_FAIL)
861         return ZEBRA_FAIL;
862
863     r = resultSetAddRPN(zh, odr_extract_mem(o), query, 
864                         zh->num_basenames, zh->basenames, setname);
865     zebra_end_read(zh);
866     *hits = zh->hits;
867     return r;
868 }
869
870 ZEBRA_RES zebra_records_retrieve(ZebraHandle zh, ODR stream,
871                                  const char *setname,
872                                  Z_RecordComposition *comp,
873                                  oid_value input_format, int num_recs,
874                                  ZebraRetrievalRecord *recs)
875 {
876     ZebraMetaRecord *poset;
877     int i;
878     ZEBRA_RES ret = ZEBRA_OK;
879     zint *pos_array;
880     ASSERTZH;
881     assert(stream);
882     assert(setname);
883     assert(recs);
884     assert(num_recs>0);
885
886     yaz_log(log_level, "zebra_records_retrieve n=%d", num_recs);
887
888     zebra_clearError(zh);
889     if (!zh->res)
890     {
891         zebra_setError(zh, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST,
892                        setname);
893         return ZEBRA_FAIL;
894     }
895     
896     if (zebra_begin_read (zh) == ZEBRA_FAIL)
897         return ZEBRA_FAIL;
898
899     pos_array = (zint *) xmalloc(num_recs * sizeof(*pos_array));
900     for (i = 0; i<num_recs; i++)
901         pos_array[i] = recs[i].position;
902     poset = zebra_meta_records_create(zh, setname, num_recs, pos_array);
903     if (!poset)
904     {
905         yaz_log (YLOG_DEBUG, "zebraPosSetCreate error");
906         zebra_setError(zh, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST,
907                        setname);
908         ret = ZEBRA_FAIL;
909     }
910     else
911     {
912         for (i = 0; i<num_recs; i++)
913         {
914             if (poset[i].term)
915             {
916                 recs[i].errCode = 0;
917                 recs[i].format = VAL_SUTRS;
918                 recs[i].len = strlen(poset[i].term);
919                 recs[i].buf = poset[i].term;
920                 recs[i].base = poset[i].db;
921             }
922             else if (poset[i].sysno)
923             {
924                 char *buf;
925                 int len;
926                 recs[i].errCode =
927                     zebra_record_fetch(zh, poset[i].sysno, poset[i].score,
928                                        stream, input_format, comp,
929                                        &recs[i].format, &buf, &len,
930                                        &recs[i].base, &recs[i].errString);
931                 recs[i].len = len;
932                 if (len > 0)
933                 {
934                     recs[i].buf = (char*) odr_malloc(stream, len);
935                     memcpy(recs[i].buf, buf, len);
936                 }
937                 else
938                     recs[i].buf = buf;
939                 recs[i].score = poset[i].score;
940                 recs[i].sysno = poset[i].sysno;
941             }
942             else
943             {
944                 if (ret == ZEBRA_OK) /* only need to set it once */
945                     zebra_setError_zint(zh,
946                                         YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE,
947                                         pos_array[i]);
948                 ret = ZEBRA_FAIL;
949                 break;
950             }
951         }
952         zebra_meta_records_destroy(zh, poset, num_recs);
953     }
954     zebra_end_read (zh);
955     xfree(pos_array);
956     return ret;
957 }
958
959 ZEBRA_RES zebra_scan_PQF(ZebraHandle zh, ODR stream, const char *query,
960                          int *position,
961                          int *num_entries, ZebraScanEntry **entries,
962                          int *is_partial)
963 {
964     YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
965     Z_AttributesPlusTerm *zapt;
966     int *attributeSet;
967     ZEBRA_RES res;
968     
969     if (!(zapt = yaz_pqf_scan(pqf_parser, stream, &attributeSet, query)))
970     {
971         res = ZEBRA_FAIL;
972         zh->errCode = YAZ_BIB1_SCAN_MALFORMED_SCAN;
973     }
974     else
975         res = zebra_scan(zh, stream, zapt, VAL_BIB1,
976                          position, num_entries, entries, is_partial);
977     yaz_pqf_destroy (pqf_parser);
978     return res;
979 }
980
981 ZEBRA_RES zebra_scan (ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
982                       oid_value attributeset,
983                       int *position,
984                       int *num_entries, ZebraScanEntry **entries,
985                       int *is_partial)
986 {
987     ZEBRA_RES res;
988     ASSERTZH;
989     assert(stream);
990     assert(zapt);
991     assert(position);
992     assert(num_entries);
993     assert(is_partial);
994     assert(entries);
995     yaz_log(log_level, "zebra_scan");
996     zebra_clearError(zh);
997     if (zebra_begin_read (zh) == ZEBRA_FAIL)
998     {
999         *entries = 0;
1000         *num_entries = 0;
1001         return ZEBRA_FAIL;
1002     }
1003     res = rpn_scan (zh, stream, zapt, attributeset,
1004                     zh->num_basenames, zh->basenames, position,
1005                     num_entries, entries, is_partial, 0, 0);
1006     zebra_end_read (zh);
1007     return res;
1008 }
1009
1010 ZEBRA_RES zebra_sort (ZebraHandle zh, ODR stream,
1011                       int num_input_setnames, const char **input_setnames,
1012                       const char *output_setname,
1013                       Z_SortKeySpecList *sort_sequence,
1014                       int *sort_status)
1015 {
1016     ZEBRA_RES res;
1017     ASSERTZH;
1018     assert(stream);
1019     assert(num_input_setnames>0);
1020     assert(input_setnames);
1021     assert(sort_sequence);
1022     assert(sort_status);
1023     yaz_log(log_level, "zebra_sort");
1024     zebra_clearError(zh);
1025     if (zebra_begin_read(zh) == ZEBRA_FAIL)
1026         return ZEBRA_FAIL;
1027     res = resultSetSort(zh, stream->mem, num_input_setnames, input_setnames,
1028                         output_setname, sort_sequence, sort_status);
1029     zebra_end_read(zh);
1030     return res;
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     zebra_clearError(zh);;
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 = 0;
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 = 0;
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     zebra_clearError(zh);
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     zebra_clearError(zh);
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     zebra_clearError(zh);
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     zebra_clearError(zh);
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     zebra_clearError(zh);
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     zebra_clearError(zh);
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     zebra_clearError(zh);
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         zebra_setError(zh, YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED, database);
1325         return ZEBRA_FAIL;
1326     }
1327     return zebra_end_trans (zh);
1328 }
1329
1330 int zebra_string_norm (ZebraHandle zh, unsigned reg_id,
1331                        const char *input_str, int input_len,
1332                        char *output_str, int output_len)
1333 {
1334     WRBUF wrbuf;
1335     ASSERTZH;
1336     assert(input_str);
1337     assert(output_str);
1338     yaz_log(log_level, "zebra_string_norm ");
1339     zebra_clearError(zh);
1340     if (!zh->reg->zebra_maps)
1341         return -1;
1342     wrbuf = zebra_replace(zh->reg->zebra_maps, reg_id, "",
1343                           input_str, input_len);
1344     if (!wrbuf)
1345         return -2;
1346     if (wrbuf_len(wrbuf) >= output_len)
1347         return -3;
1348     if (wrbuf_len(wrbuf))
1349         memcpy (output_str, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
1350     output_str[wrbuf_len(wrbuf)] = '\0';
1351     return wrbuf_len(wrbuf);
1352 }
1353
1354 static void zebra_set_state (ZebraHandle zh, int val, int seqno)
1355 {
1356     char state_fname[256];
1357     char *fname;
1358     long p = getpid();
1359     FILE *f;
1360     ASSERTZH;
1361     yaz_log(log_level, "zebra_set_state v=%d seq=%d", val, seqno);
1362     zebra_clearError(zh);
1363
1364     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1365     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1366     f = fopen (fname, "w");
1367
1368     yaz_log (YLOG_DEBUG, "zebra_set_state: %c %d %ld", val, seqno, p);
1369     fprintf (f, "%c %d %ld\n", val, seqno, p);
1370     fclose (f);
1371     xfree(fname);
1372 }
1373
1374 static void zebra_get_state (ZebraHandle zh, char *val, int *seqno)
1375 {
1376     char state_fname[256];
1377     char *fname;
1378     FILE *f;
1379
1380     ASSERTZH;
1381     yaz_log(log_level, "zebra_get_state ");
1382     zebra_clearError(zh);
1383     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1384     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1385     f = fopen (fname, "r");
1386     *val = 'o';
1387     *seqno = 0;
1388
1389     if (f)
1390     {
1391         fscanf (f, "%c %d", val, seqno);
1392         fclose (f);
1393     }
1394     xfree(fname);
1395 }
1396
1397 ZEBRA_RES zebra_begin_read (ZebraHandle zh)
1398 {
1399     return zebra_begin_trans(zh, 0);
1400 }
1401
1402 ZEBRA_RES zebra_end_read (ZebraHandle zh)
1403 {
1404     return zebra_end_trans(zh);
1405 }
1406
1407 static void read_res_for_transaction(ZebraHandle zh)
1408 {
1409     const char *group = res_get(zh->res, "group");
1410     const char *v;
1411     /* FIXME - do we still use groups ?? */
1412     
1413     zh->m_group = group;
1414     v = res_get_prefix(zh->res, "followLinks", group, "1");
1415     zh->m_follow_links = atoi(v);
1416
1417     zh->m_record_id = res_get_prefix(zh->res, "recordId", group, 0);
1418     zh->m_record_type = res_get_prefix(zh->res, "recordType", group, 0);
1419
1420     v = res_get_prefix(zh->res, "storeKeys", group, "1");
1421     zh->m_store_keys = atoi(v);
1422
1423     v = res_get_prefix(zh->res, "storeData", group, "1");
1424     zh->m_store_data = atoi(v);
1425
1426     v = res_get_prefix(zh->res, "explainDatabase", group, "0");
1427     zh->m_explain_database = atoi(v);
1428
1429     v = res_get_prefix(zh->res, "openRW", group, "1");
1430     zh->m_flag_rw = atoi(v);
1431
1432     v = res_get_prefix(zh->res, "fileVerboseLimit", group, "100000");
1433     zh->m_file_verbose_limit = atoi(v);
1434 }
1435
1436 ZEBRA_RES zebra_begin_trans(ZebraHandle zh, int rw)
1437 {
1438     ASSERTZH;
1439     zebra_select_default_database(zh);
1440     if (!zh->res)
1441     {
1442         zebra_setError(zh, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
1443                        "zebra_begin_trans: no database selected");
1444         return ZEBRA_FAIL;
1445     }
1446     ASSERTZHRES;
1447     yaz_log(log_level, "zebra_begin_trans rw=%d",rw);
1448
1449     if (zh->user_perm)
1450     {
1451         if (rw && !strchr(zh->user_perm, 'w'))
1452         {
1453             zebra_setError(
1454                 zh,
1455                 YAZ_BIB1_ES_PERMISSION_DENIED_ON_ES_CANNOT_MODIFY_OR_DELETE,
1456                 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             zebra_setError(zh, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
1478                            "zebra_begin_trans: no write trans within read");
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         zebra_clearError(zh);
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             zebra_setError(zh, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
1565                            "zebra_begin_trans: cannot open register");
1566             yaz_log(YLOG_FATAL, "%s", 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         zebra_clearError(zh);
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         zebra_setError(zh, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
1676                        "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     zebra_clearError(zh);
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     zebra_clearError(zh);
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     zebra_clearError(zh);
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     zebra_clearError(zh);
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     zebra_clearError(zh);
1857
1858     zebra_select_default_database(zh);
1859     if (!zh->res)
1860     {
1861         zebra_setError(zh, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
1862                        "cannot select default database");
1863         return ZEBRA_FAIL;
1864     }
1865     rval = res_get (zh->res, "shadow");
1866
1867     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1868     if (!bfs)
1869     {
1870         zebra_setError(zh, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR, "bfs_create");
1871         return ZEBRA_FAIL;
1872     }
1873     if (rval && *rval)
1874         bf_cache (bfs, rval);
1875     
1876     bf_reset (bfs);
1877     bfs_destroy (bfs);
1878     zebra_set_state (zh, 'o', 0);
1879     return ZEBRA_OK;
1880 }
1881
1882 ZEBRA_RES zebra_compact(ZebraHandle zh)
1883 {
1884     BFiles bfs;
1885     ASSERTZH;
1886     yaz_log(log_level, "zebra_compact");
1887     zebra_clearError(zh);
1888     if (!zh->res)
1889     {
1890         zh->errCode = YAZ_BIB1_DATABASE_UNAVAILABLE;
1891         return ZEBRA_FAIL;
1892     }
1893     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1894     inv_compact (bfs);
1895     bfs_destroy (bfs);
1896     return ZEBRA_OK;
1897 }
1898
1899 void zebra_result(ZebraHandle zh, int *code, char **addinfo)
1900 {
1901     ASSERTZH;
1902     yaz_log(log_level, "zebra_result");
1903     *code = zh->errCode;
1904     *addinfo = zh->errString;
1905 }
1906
1907 void zebra_shadow_enable(ZebraHandle zh, int value)
1908 {
1909     ASSERTZH;
1910     yaz_log(log_level, "zebra_shadow_enable");
1911     zebra_clearError(zh);
1912     zh->shadow_enable = value;
1913 }
1914
1915 ZEBRA_RES zebra_octet_term_encoding(ZebraHandle zh, const char *encoding)
1916 {
1917     ASSERTZH;
1918     assert(encoding);
1919     yaz_log(log_level, "zebra_octet_term_encoding");
1920     zebra_clearError(zh);
1921
1922     if (zh->iconv_to_utf8 != 0)
1923         yaz_iconv_close(zh->iconv_to_utf8);
1924     if (zh->iconv_from_utf8 != 0)
1925         yaz_iconv_close(zh->iconv_from_utf8);
1926     
1927     zh->iconv_to_utf8 =
1928         yaz_iconv_open ("UTF-8", encoding);
1929     if (zh->iconv_to_utf8 == 0)
1930         yaz_log (YLOG_WARN, "iconv: %s to UTF-8 unsupported", encoding);
1931     zh->iconv_from_utf8 =
1932         yaz_iconv_open (encoding, "UTF-8");
1933     if (zh->iconv_to_utf8 == 0)
1934         yaz_log (YLOG_WARN, "iconv: UTF-8 to %s unsupported", encoding);
1935
1936     return ZEBRA_OK;
1937 }
1938
1939 ZEBRA_RES zebra_record_encoding (ZebraHandle zh, const char *encoding)
1940 {
1941     ASSERTZH;
1942     yaz_log(log_level, "zebra_record_encoding");
1943     zebra_clearError(zh);
1944     xfree(zh->record_encoding);
1945     zh->record_encoding = 0;
1946     if (encoding)
1947         zh->record_encoding = xstrdup (encoding);
1948     return ZEBRA_OK;
1949 }
1950
1951 void zebra_set_resource(ZebraHandle zh, const char *name, const char *value)
1952 {
1953     ASSERTZH;
1954     assert(name);
1955     assert(value);
1956     yaz_log(log_level, "zebra_set_resource %s:%s", name, value);
1957     zebra_clearError(zh);
1958     res_set(zh->res, name, value);
1959 }
1960
1961 const char *zebra_get_resource(ZebraHandle zh,
1962                                const char *name, const char *defaultvalue)
1963 {
1964     const char *v;
1965     ASSERTZH;
1966     assert(name);
1967     assert(defaultvalue);
1968     v = res_get_def (zh->res, name, (char *)defaultvalue);
1969     zebra_clearError(zh);
1970     yaz_log(log_level, "zebra_get_resource %s:%s", name, v);
1971     return v;
1972 }
1973
1974 /* moved from zebra_api_ext.c by pop */
1975 /* FIXME: Should this really be public??? -Heikki */
1976
1977 int zebra_trans_no (ZebraHandle zh)
1978 {
1979     ASSERTZH;
1980     yaz_log(log_level, "zebra_trans_no");
1981     return zh->trans_no;
1982 }
1983
1984 int zebra_get_shadow_enable (ZebraHandle zh)
1985 {
1986     ASSERTZH;
1987     yaz_log(log_level, "zebra_get_shadow_enable");
1988     return zh->shadow_enable;
1989 }
1990
1991 void zebra_set_shadow_enable (ZebraHandle zh, int value)
1992 {
1993     ASSERTZH;
1994     yaz_log(log_level, "zebra_set_shadow_enable %d",value);
1995     zh->shadow_enable = value;
1996 }
1997
1998 /* Used by Perl API.. Added the record buffer dup to zebra_records_retrieve
1999    so that it's identicical to the original api_records_retrieve */
2000 void api_records_retrieve (ZebraHandle zh, ODR stream,
2001                            const char *setname, Z_RecordComposition *comp,
2002                            oid_value input_format, int num_recs,
2003                            ZebraRetrievalRecord *recs)
2004 {
2005     zebra_records_retrieve(zh, stream, setname, comp, input_format,
2006                            num_recs, recs);
2007 }
2008
2009 /* ---------------------------------------------------------------------------
2010   Record insert(=update), delete 
2011
2012   If sysno is provided, then it's used to identify the record.
2013   If not, and match_criteria is provided, then sysno is guessed
2014   If not, and a record is provided, then sysno is got from there
2015 NOTE: Now returns 0 at success and updates sysno, which is an int*
2016   20-jun-2003 Heikki
2017 */
2018
2019 int zebra_add_record(ZebraHandle zh,
2020                      const char *buf, int buf_size)
2021 {
2022     SYSNO sysno = 0;
2023     return zebra_update_record(zh, 0, &sysno, 0, 0, buf, buf_size, 0);
2024 }
2025
2026 ZEBRA_RES zebra_insert_record (ZebraHandle zh, 
2027                                const char *recordType,
2028                                SYSNO *sysno, const char *match,
2029                                const char *fname,
2030                                const char *buf, int buf_size, int force_update)
2031 {
2032     ZEBRA_RES res;
2033     ASSERTZH;
2034     assert(sysno);
2035     assert(buf);
2036     yaz_log(log_level, "zebra_insert_record sysno=" ZINT_FORMAT, *sysno);
2037
2038     if (buf_size < 1)
2039         buf_size = strlen(buf);
2040
2041     if (zebra_begin_trans(zh, 1) == ZEBRA_FAIL)
2042         return ZEBRA_FAIL;
2043     res = buffer_extract_record (zh, buf, buf_size, 
2044                                  0, /* delete_flag  */
2045                                  0, /* test_mode */
2046                                  recordType,
2047                                  sysno,   
2048                                  match, fname,
2049                                  0, 
2050                                  0); /* allow_update */
2051     zebra_end_trans(zh); 
2052     return res; 
2053 }
2054
2055 ZEBRA_RES zebra_update_record (ZebraHandle zh, 
2056                                const char *recordType,
2057                                SYSNO* sysno, const char *match,
2058                                const char *fname,
2059                                const char *buf, int buf_size,
2060                                int force_update)
2061 {
2062     ZEBRA_RES res;
2063     ASSERTZH;
2064     assert(sysno);
2065     assert(buf);
2066
2067     yaz_log(log_level, "zebra_update_record sysno=" ZINT_FORMAT, *sysno);
2068
2069     if (buf_size < 1) buf_size = strlen(buf);
2070
2071     if (zebra_begin_trans(zh, 1) == ZEBRA_FAIL)
2072         return ZEBRA_FAIL;
2073     res = buffer_extract_record (zh, buf, buf_size, 
2074                                  0, /* delete_flag */
2075                                  0, /* test_mode */
2076                                  recordType,
2077                                  sysno,   
2078                                  match, fname,
2079                                  force_update, 
2080                                  1); /* allow_update */
2081     zebra_end_trans(zh); 
2082     return res; 
2083 }
2084
2085 ZEBRA_RES zebra_delete_record (ZebraHandle zh, 
2086                                const char *recordType,
2087                                SYSNO *sysno, const char *match,
2088                                const char *fname,
2089                                const char *buf, int buf_size,
2090                                int force_update) 
2091 {
2092     ZEBRA_RES res;
2093     ASSERTZH;
2094     assert(sysno);
2095     assert(buf);
2096     yaz_log(log_level, "zebra_delete_record sysno=" ZINT_FORMAT, *sysno);
2097
2098     if (buf_size < 1) buf_size = strlen(buf);
2099
2100     if (zebra_begin_trans(zh, 1) == ZEBRA_FAIL)
2101         return ZEBRA_FAIL;
2102     res = buffer_extract_record (zh, buf, buf_size,
2103                                  1, /* delete_flag */
2104                                  0, /* test_mode */
2105                                  recordType,
2106                                  sysno,
2107                                  match,fname,
2108                                  force_update,
2109                                  1); /* allow_update */
2110     zebra_end_trans(zh);
2111     return res;
2112 }
2113
2114 /* ---------------------------------------------------------------------------
2115   Searching 
2116 */
2117
2118 ZEBRA_RES zebra_search_PQF(ZebraHandle zh, const char *pqf_query,
2119                            const char *setname, zint *numhits)
2120 {
2121     zint hits = 0;
2122     ZEBRA_RES res = ZEBRA_OK;
2123     Z_RPNQuery *query;
2124     ODR odr = odr_createmem(ODR_ENCODE);
2125     ASSERTZH;
2126     assert(pqf_query);
2127     assert(setname);
2128
2129     yaz_log(log_level, "zebra_search_PQF s=%s q=%s", setname, pqf_query);
2130     
2131     query = p_query_rpn (odr, PROTO_Z3950, pqf_query);
2132     
2133     if (!query)
2134     {
2135         yaz_log (YLOG_WARN, "bad query %s\n", pqf_query);
2136         zh->errCode = YAZ_BIB1_MALFORMED_QUERY;
2137         res = ZEBRA_FAIL;
2138     }
2139     else
2140         res = zebra_search_RPN(zh, odr, query, setname, &hits);
2141     
2142     odr_destroy(odr);
2143
2144     yaz_log(log_level, "Hits: " ZINT_FORMAT, hits);
2145
2146     if (numhits)
2147         *numhits = hits;
2148
2149     return res;
2150 }
2151
2152 /* ---------------------------------------------------------------------------
2153   Sort - a simplified interface, with optional read locks.
2154 */
2155 int zebra_sort_by_specstr (ZebraHandle zh, ODR stream,
2156                            const char *sort_spec,
2157                            const char *output_setname,
2158                            const char **input_setnames) 
2159 {
2160     int num_input_setnames = 0;
2161     int sort_status = 0;
2162     Z_SortKeySpecList *sort_sequence;
2163     ASSERTZH;
2164     assert(stream);
2165     assert(sort_spec);
2166     assert(output_setname);
2167     assert(input_setnames);
2168     sort_sequence = yaz_sort_spec (stream, sort_spec);
2169     yaz_log(log_level, "sort (FIXME) ");
2170     if (!sort_sequence)
2171     {
2172         yaz_log(YLOG_WARN, "invalid sort specs '%s'", sort_spec);
2173         zh->errCode = YAZ_BIB1_CANNOT_SORT_ACCORDING_TO_SEQUENCE;
2174         return -1;
2175     }
2176     
2177     /* we can do this, since the perl typemap code for char** will 
2178        put a NULL at the end of list */
2179     while (input_setnames[num_input_setnames]) num_input_setnames++;
2180
2181     if (zebra_begin_read (zh))
2182         return -1;
2183     
2184     resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
2185                    output_setname, sort_sequence, &sort_status);
2186     
2187     zebra_end_read(zh);
2188     return sort_status;
2189 }
2190
2191 /* ---------------------------------------------------------------------------
2192   Get BFS for Zebra system (to make alternative storage methods)
2193 */
2194 struct BFiles_struct *zebra_get_bfs(ZebraHandle zh)
2195 {
2196     if (zh && zh->reg)
2197         return zh->reg->bfs;
2198     return 0;
2199 }
2200
2201
2202 /* ---------------------------------------------------------------------------
2203   Set limit for search/scan
2204 */
2205 ZEBRA_RES zebra_set_limit(ZebraHandle zh, int complement_flag, zint *ids)
2206 {
2207     ASSERTZH;
2208     zebra_limit_destroy(zh->m_limit);
2209     zh->m_limit = zebra_limit_create(complement_flag, ids);
2210     return ZEBRA_OK;
2211 }
2212
2213 /*
2214   Set Error code + addinfo
2215 */
2216 void zebra_setError(ZebraHandle zh, int code, const char *addinfo)
2217 {
2218     zh->errCode = code;
2219     nmem_reset(zh->nmem_error);
2220     zh->errString = addinfo ? nmem_strdup(zh->nmem_error, addinfo) : 0;
2221 }
2222
2223 void zebra_setError_zint(ZebraHandle zh, int code, zint i)
2224 {
2225     char vstr[60];
2226     sprintf(vstr, ZINT_FORMAT, i);
2227
2228     zh->errCode = code;
2229     nmem_reset(zh->nmem_error);
2230     zh->errString = nmem_strdup(zh->nmem_error, vstr);
2231 }
2232