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