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