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