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