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