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