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