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