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