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