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