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