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