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