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