1 /* $Id: zebraapi.c,v 1.137 2004-10-26 15:32:11 heikki Exp $
2 Copyright (C) 1995,1996,1997,1998,1999,2000,2001,2002,2003,2004
5 This file is part of the Zebra server.
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
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
17 You should have received a copy of the GNU General Public License
18 along with Zebra; see the file LICENSE.zebra. If not, write to the
19 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
34 #include <yaz/diagbib1.h>
35 #include <yaz/pquery.h>
36 #include <yaz/sortspec.h>
39 #include <idzebra/api.h>
41 /* simple asserts to validate the most essential input args */
42 #define ASSERTZH assert(zh && zh->service)
43 #define ASSERTZHRES assert(zh && zh->service && zh->res)
44 #define ASSERTZS assert(zs)
46 #define LOG_API LOG_APP2
48 static Res zebra_open_res (ZebraHandle zh);
49 static void zebra_close_res (ZebraHandle zh);
52 static void zebra_chdir (ZebraService zs)
56 yaz_log(LOG_API,"zebra_chdir");
57 dir = res_get (zs->global_res, "chdir");
60 logf (LOG_DEBUG, "chdir %s", dir);
68 static void zebra_flush_reg (ZebraHandle zh)
71 yaz_log(LOG_API,"zebra_flush_reg");
73 zebraExplain_flush (zh->reg->zei, zh);
75 extract_flushWriteKeys (zh,1 /* final */);
76 zebra_index_merge (zh );
79 static struct zebra_register *zebra_register_open (ZebraService zs,
81 int rw, int useshadow,
83 const char *reg_path);
84 static void zebra_register_close (ZebraService zs, struct zebra_register *reg);
86 ZebraHandle zebra_open (ZebraService zs)
89 const char *default_encoding;
90 yaz_log(LOG_API,"zebra_open");
95 zh = (ZebraHandle) xmalloc (sizeof(*zh));
96 yaz_log (LOG_DEBUG, "zebra_open zs=%p returns %p", zs, zh);
99 zh->reg = 0; /* no register attached yet */
107 zh->reg_name = xstrdup ("");
109 zh->num_basenames = 0;
118 zh->shadow_enable = 1;
120 default_encoding = res_get_def(zs->global_res, "encoding", "ISO-8859-1");
121 zh->record_encoding = xstrdup (default_encoding);
124 yaz_iconv_open ("UTF-8", default_encoding);
125 if (zh->iconv_to_utf8 == 0)
126 yaz_log (LOG_WARN, "iconv: %s to UTF-8 unsupported",
128 zh->iconv_from_utf8 =
129 yaz_iconv_open (default_encoding, "UTF-8");
130 if (zh->iconv_to_utf8 == 0)
131 yaz_log (LOG_WARN, "iconv: UTF-8 to %s unsupported",
134 zebra_mutex_cond_lock (&zs->session_lock);
136 zh->next = zs->sessions;
139 zebra_mutex_cond_unlock (&zs->session_lock);
144 ZebraService zebra_start (const char *configName)
146 return zebra_start_res(configName, 0, 0);
149 ZebraService zebra_start_res (const char *configName, Res def_res, Res over_res)
153 yaz_log(LOG_API,"zebra_start %s",configName);
156 if ((res = res_open (configName, def_res, over_res)))
158 ZebraService zh = xmalloc (sizeof(*zh));
160 yaz_log (LOG_DEBUG, "Read resources `%s'", configName);
162 zh->global_res = res;
163 zh->configName = xstrdup(configName);
168 zebra_mutex_cond_init (&zh->session_lock);
169 if (!res_get (zh->global_res, "passwd"))
170 zh->passwd_db = NULL;
173 zh->passwd_db = passwd_db_open ();
175 logf (LOG_WARN|LOG_ERRNO, "passwd_db_open failed");
177 passwd_db_file (zh->passwd_db,
178 res_get (zh->global_res, "passwd"));
180 zh->path_root = res_get (zh->global_res, "root");
181 zh->nmem = nmem_create();
182 zh->record_classes = recTypeClass_create (zh->global_res, zh->nmem);
188 void zebra_filter_info(ZebraService zs, void *cd,
189 void (*cb)(void *cd, const char *name))
193 recTypeClass_info(zs->record_classes, cd, cb);
196 void zebra_pidfname(ZebraService zs, char *path)
199 zebra_lock_prefix (zs->global_res, path);
200 strcat(path, "zebrasrv.pid");
203 Dict dict_open_res (BFiles bfs, const char *name, int cache, int rw,
204 int compact_flag, Res res)
206 int page_size = 4096;
207 char resource_str[200];
209 sprintf (resource_str, "dict.%.100s.pagesize", name);
213 v = res_get(res, resource_str);
217 yaz_log(LOG_LOG, "Using custom dictionary page size %d for %s",
220 return dict_open(bfs, name, cache, rw, compact_flag, page_size);
225 struct zebra_register *zebra_register_open (ZebraService zs, const char *name,
226 int rw, int useshadow, Res res,
227 const char *reg_path)
229 struct zebra_register *reg;
230 int record_compression = REC_COMPRESS_NONE;
231 const char *recordCompression = 0;
232 const char *profilePath;
237 reg = xmalloc (sizeof(*reg));
240 reg->name = xstrdup (name);
247 yaz_log (LOG_DEBUG, "zebra_register_open rw=%d useshadow=%d p=%p n=%s rp=%s",
248 rw, useshadow, reg, name, reg_path ? reg_path : "(none)");
250 reg->dh = data1_createx (DATA1_FLAG_XML);
253 reg->bfs = bfs_create (res_get (res, "register"), reg_path);
256 data1_destroy(reg->dh);
260 bf_cache (reg->bfs, res_get (res, "shadow"));
262 getcwd(cwd, sizeof(cwd)-1);
263 profilePath = res_get_def(res, "profilePath", DEFAULT_PROFILE_PATH);
264 yaz_log(LOG_DEBUG, "profilePath=%s cwd=%s", profilePath, cwd);
266 data1_set_tabpath (reg->dh, profilePath);
267 data1_set_tabroot (reg->dh, reg_path);
268 reg->recTypes = recTypes_init (zs->record_classes, reg->dh);
270 reg->zebra_maps = zebra_maps_open (res, reg_path);
271 reg->rank_classes = NULL;
275 reg->keys.buf_max = 0;
277 reg->keys.codec_handle = iscz1_start();
279 reg->sortKeys.buf = 0;
280 reg->sortKeys.buf_max = 0;
291 reg->key_file_no = 0;
294 zebraRankInstall (reg, rank1_class);
295 #ifdef SKIPTHIS /* FIXME - those ranks not yet converted to new interface */
296 zebraRankInstall (reg, rankzv_class);
297 zebraRankInstall (reg, rankliv_class);
300 recordCompression = res_get_def (res, "recordCompression", "none");
301 if (!strcmp (recordCompression, "none"))
302 record_compression = REC_COMPRESS_NONE;
303 if (!strcmp (recordCompression, "bzip2"))
304 record_compression = REC_COMPRESS_BZIP2;
306 if (!(reg->records = rec_open (reg->bfs, rw, record_compression)))
308 logf (LOG_WARN, "rec_open");
313 reg->matchDict = dict_open_res (reg->bfs, GMATCH_DICT, 20, 1, 0, res);
315 if (!(reg->dict = dict_open_res (reg->bfs, FNAME_DICT, 40, rw, 0, res)))
317 logf (LOG_WARN, "dict_open");
320 if (!(reg->sortIdx = sortIdx_open (reg->bfs, rw)))
322 logf (LOG_WARN, "sortIdx_open");
325 if (res_get_match (res, "isam", "s", ISAM_DEFAULT))
327 struct ISAMS_M_s isams_m;
328 if (!(reg->isams = isams_open (reg->bfs, FNAME_ISAMS, rw,
329 key_isams_m(res, &isams_m))))
331 logf (LOG_WARN, "isams_open");
335 if (res_get_match (res, "isam", "c", ISAM_DEFAULT))
337 struct ISAMC_M_s isamc_m;
338 if (!(reg->isamc = isc_open (reg->bfs, FNAME_ISAMC,
339 rw, key_isamc_m(res, &isamc_m))))
341 logf (LOG_WARN, "isc_open");
345 if (res_get_match (res, "isam", "b", ISAM_DEFAULT))
347 struct ISAMC_M_s isamc_m;
349 if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
350 rw, key_isamc_m(res, &isamc_m), 0)))
352 logf (LOG_WARN, "isamb_open");
356 if (res_get_match (res, "isam", "bc", ISAM_DEFAULT))
358 struct ISAMC_M_s isamc_m;
360 if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
361 rw, key_isamc_m(res, &isamc_m), 1)))
363 logf (LOG_WARN, "isamb_open");
367 if (res_get_match (res, "isam", "null", ISAM_DEFAULT))
369 struct ISAMC_M_s isamc_m;
371 if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
372 rw, key_isamc_m(res, &isamc_m), -1)))
374 logf (LOG_WARN, "isamb_open");
378 reg->zei = zebraExplain_open (reg->records, reg->dh,
383 logf (LOG_WARN, "Cannot obtain EXPLAIN information");
387 yaz_log (LOG_DEBUG, "zebra_register_open ok p=%p", reg);
391 int zebra_admin_shutdown (ZebraHandle zh)
394 yaz_log(LOG_API,"zebra_admin_shutdown");
397 zebra_mutex_cond_lock (&zh->service->session_lock);
398 zh->service->stop_flag = 1;
399 zebra_mutex_cond_unlock (&zh->service->session_lock);
403 int zebra_admin_start (ZebraHandle zh)
407 yaz_log(LOG_API,"zebra_admin_start");
410 zebra_mutex_cond_lock (&zs->session_lock);
411 zebra_mutex_cond_unlock (&zs->session_lock);
415 static void zebra_register_close (ZebraService zs, struct zebra_register *reg)
419 yaz_log(LOG_DEBUG, "zebra_register_close p=%p", reg);
424 zebraExplain_close (reg->zei);
425 dict_close (reg->dict);
427 dict_close (reg->matchDict);
428 sortIdx_close (reg->sortIdx);
430 isams_close (reg->isams);
432 isc_close (reg->isamc);
434 isamb_close (reg->isamb);
435 rec_close (®->records);
438 recTypes_destroy (reg->recTypes);
439 zebra_maps_close (reg->zebra_maps);
440 zebraRankDestroy (reg);
441 bfs_destroy (reg->bfs);
442 data1_destroy (reg->dh);
444 xfree (reg->sortKeys.buf);
445 xfree (reg->keys.buf);
446 if (reg->keys.codec_handle)
447 iscz1_stop(reg->keys.codec_handle);
448 xfree (reg->key_buf);
453 int zebra_stop(ZebraService zs)
457 yaz_log (LOG_API, "zebra_stop");
461 zebra_close (zs->sessions);
464 zebra_mutex_cond_destroy (&zs->session_lock);
467 passwd_db_close (zs->passwd_db);
469 recTypeClass_destroy(zs->record_classes);
470 nmem_destroy(zs->nmem);
471 res_close (zs->global_res);
472 xfree (zs->configName);
477 int zebra_close (ZebraHandle zh)
480 struct zebra_session **sp;
483 yaz_log(LOG_API,"zebra_close");
490 yaz_log (LOG_DEBUG, "zebra_close zh=%p", zh);
491 resultSetDestroy (zh, -1, 0, 0);
494 zebra_register_close (zh->service, zh->reg);
495 zebra_close_res (zh);
497 xfree (zh->record_encoding);
499 for (i = 0; i < zh->num_basenames; i++)
500 xfree (zh->basenames[i]);
501 xfree (zh->basenames);
503 if (zh->iconv_to_utf8 != 0)
504 yaz_iconv_close (zh->iconv_to_utf8);
505 if (zh->iconv_from_utf8 != 0)
506 yaz_iconv_close (zh->iconv_from_utf8);
508 zebra_mutex_cond_lock (&zs->session_lock);
509 zebra_lock_destroy (zh->lock_normal);
510 zebra_lock_destroy (zh->lock_shadow);
522 zebra_mutex_cond_unlock (&zs->session_lock);
523 xfree (zh->reg_name);
524 xfree (zh->user_perm);
525 zh->service=0; /* more likely to trigger an assert */
526 xfree (zh->path_reg);
531 struct map_baseinfo {
537 char **new_basenames;
541 static Res zebra_open_res (ZebraHandle zh)
550 sprintf (fname, "%.200s/zebra.cfg", zh->path_reg);
551 res = res_open (fname, zh->service->global_res, 0);
553 res = zh->service->global_res;
555 else if (*zh->reg_name == 0)
557 res = zh->service->global_res;
561 yaz_log (LOG_WARN, "no register root specified");
562 return 0; /* no path for register - fail! */
567 static void zebra_close_res (ZebraHandle zh)
571 if (zh->res != zh->service->global_res)
576 static int zebra_select_register (ZebraHandle zh, const char *new_reg)
580 if (zh->res && strcmp (zh->reg_name, new_reg) == 0)
584 assert (zh->reg == 0);
585 assert (*zh->reg_name == 0);
591 resultSetInvalidate (zh);
592 zebra_register_close (zh->service, zh->reg);
597 xfree (zh->reg_name);
598 zh->reg_name = xstrdup (new_reg);
600 xfree (zh->path_reg);
602 if (zh->service->path_root)
604 zh->path_reg = xmalloc (strlen(zh->service->path_root) +
605 strlen(zh->reg_name) + 3);
606 strcpy (zh->path_reg, zh->service->path_root);
609 strcat (zh->path_reg, "/");
610 strcat (zh->path_reg, zh->reg_name);
613 zh->res = zebra_open_res (zh);
616 zebra_lock_destroy (zh->lock_normal);
620 zebra_lock_destroy (zh->lock_shadow);
626 const char *lock_area =res_get (zh->res, "lockDir");
628 if (!lock_area && zh->path_reg)
629 res_set (zh->res, "lockDir", zh->path_reg);
630 sprintf (fname, "norm.%s.LCK", zh->reg_name);
632 zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
634 sprintf (fname, "shadow.%s.LCK", zh->reg_name);
636 zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
642 void map_basenames_func (void *vp, const char *name, const char *value)
644 struct map_baseinfo *p = (struct map_baseinfo *) vp;
646 char fromdb[128], todb[8][128];
653 sscanf (value, "%127s %127s %127s %127s %127s %127s %127s %127s %127s",
654 fromdb, todb[0], todb[1], todb[2], todb[3], todb[4],
655 todb[5], todb[6], todb[7]);
659 for (i = 0; i<p->num_bases; i++)
660 if (p->basenames[i] && !STRCASECMP (p->basenames[i], fromdb))
663 for (i = 0; i < no; i++)
665 if (p->new_num_bases == p->new_num_max)
667 p->new_basenames[(p->new_num_bases)++] =
668 nmem_strdup (p->mem, todb[i]);
674 void map_basenames (ZebraHandle zh, ODR stream,
675 int *num_bases, char ***basenames)
677 struct map_baseinfo info;
678 struct map_baseinfo *p = &info;
681 yaz_log(LOG_API,"map_basenames ");
687 info.num_bases = *num_bases;
688 info.basenames = *basenames;
689 info.new_num_max = 128;
690 info.new_num_bases = 0;
691 info.new_basenames = (char **)
692 odr_malloc (stream, sizeof(*info.new_basenames) * info.new_num_max);
693 info.mem = stream->mem;
695 res_trav (zh->service->global_res, "mapdb", &info, map_basenames_func);
697 for (i = 0; i<p->num_bases; i++)
698 if (p->basenames[i] && p->new_num_bases < p->new_num_max)
700 p->new_basenames[(p->new_num_bases)++] =
701 nmem_strdup (p->mem, p->basenames[i]);
703 *num_bases = info.new_num_bases;
704 *basenames = info.new_basenames;
705 for (i = 0; i<*num_bases; i++)
706 logf (LOG_DEBUG, "base %s", (*basenames)[i]);
709 int zebra_select_database (ZebraHandle zh, const char *basename)
712 yaz_log(LOG_API,"zebra_select_database %s",basename);
715 return zebra_select_databases (zh, 1, &basename);
718 int zebra_select_databases (ZebraHandle zh, int num_bases,
719 const char **basenames)
728 yaz_log(LOG_API,"zebra_select_databases n=%d [0]=%s",
729 num_bases,basenames[0]);
737 for (i = 0; i < zh->num_basenames; i++)
738 xfree (zh->basenames[i]);
739 xfree (zh->basenames);
741 zh->num_basenames = num_bases;
742 zh->basenames = xmalloc (zh->num_basenames * sizeof(*zh->basenames));
743 for (i = 0; i < zh->num_basenames; i++)
744 zh->basenames[i] = xstrdup (basenames[i]);
746 cp = strrchr(basenames[0], '/');
749 len = cp - basenames[0];
750 new_reg = xmalloc (len + 1);
751 memcpy (new_reg, basenames[0], len);
755 new_reg = xstrdup ("");
756 for (i = 1; i<num_bases; i++)
760 cp1 = strrchr (basenames[i], '/');
768 if (len != cp1 - basenames[i] ||
769 memcmp (basenames[i], new_reg, len))
784 zebra_select_register (zh, new_reg);
791 if (!zh->lock_normal || !zh->lock_shadow)
799 int zebra_search_RPN (ZebraHandle zh, ODR o,
800 Z_RPNQuery *query, const char *setname, int *hits)
809 yaz_log(LOG_API,"zebra_search_rpn");
814 if (zebra_begin_read (zh))
817 #ifdef SKIPTHIS /* FIXME - livcode rank not yet available */
818 zebra_livcode_transform(zh, query);
821 resultSetAddRPN (zh, odr_extract_mem(o), query,
822 zh->num_basenames, zh->basenames, setname);
825 max = res_get (zh->res, "maxhits");
830 maxhits=INT_MAX; /* properly rounded, to make it look like a limit*/
831 while (maxhits>100) { maxhits/=10; i++;}
832 while (i--) maxhits *= 10;
834 if (zh->hits > maxhits) { /* too large for yaz to handle */
835 logf(LOG_DEBUG,"limiting hits to "ZINT_FORMAT, maxhits);
843 int zebra_records_retrieve (ZebraHandle zh, ODR stream,
844 const char *setname, Z_RecordComposition *comp,
845 oid_value input_format, int num_recs,
846 ZebraRetrievalRecord *recs)
849 int i, *pos_array, ret = 0;
856 yaz_log(LOG_API,"zebra_records_retrieve n=%d",num_recs);
862 zh->errString = odr_strdup (stream, setname);
868 if (zebra_begin_read (zh))
871 pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
872 for (i = 0; i<num_recs; i++)
873 pos_array[i] = recs[i].position;
874 poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
877 logf (LOG_DEBUG, "zebraPosSetCreate error");
879 zh->errString = nmem_strdup (stream->mem, setname);
884 for (i = 0; i<num_recs; i++)
889 recs[i].format = VAL_SUTRS;
890 recs[i].len = strlen(poset[i].term);
891 recs[i].buf = poset[i].term;
892 recs[i].base = poset[i].db;
894 else if (poset[i].sysno)
897 zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
898 stream, input_format, comp,
899 &recs[i].format, &recs[i].buf,
902 recs[i].errString = NULL;
908 sprintf (num_str, "%d", pos_array[i]);
910 zh->errString = odr_strdup (stream, num_str);
915 zebraPosSetDestroy (zh, poset, num_recs);
922 int zebra_scan (ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
923 oid_value attributeset,
924 int *position, int *num_entries, ZebraScanEntry **entries,
934 yaz_log(LOG_API,"zebra_scan");
936 if (zebra_begin_read (zh))
942 rpn_scan (zh, stream, zapt, attributeset,
943 zh->num_basenames, zh->basenames, position,
944 num_entries, entries, is_partial, 0, 0);
949 int zebra_sort (ZebraHandle zh, ODR stream,
950 int num_input_setnames, const char **input_setnames,
951 const char *output_setname, Z_SortKeySpecList *sort_sequence,
956 assert(num_input_setnames>0);
957 assert(input_setnames);
958 assert(sort_sequence);
960 yaz_log(LOG_API,"zebra_sort");
962 if (zebra_begin_read (zh))
964 resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
965 output_setname, sort_sequence, sort_status);
970 int zebra_deleleResultSet(ZebraHandle zh, int function,
971 int num_setnames, char **setnames,
976 assert(num_setnames>0);
979 yaz_log(LOG_API,"zebra_deleleResultSet n=%d",num_setnames);
981 if (zebra_begin_read(zh))
982 return Z_DeleteStatus_systemProblemAtTarget;
985 case Z_DeleteResultSetRequest_list:
986 resultSetDestroy (zh, num_setnames, setnames, statuses);
988 case Z_DeleteResultSetRequest_all:
989 resultSetDestroy (zh, -1, 0, statuses);
993 status = Z_DeleteStatus_success;
994 for (i = 0; i<num_setnames; i++)
995 if (statuses[i] == Z_DeleteStatus_resultSetDidNotExist)
996 status = statuses[i];
1000 int zebra_errCode (ZebraHandle zh)
1004 yaz_log(LOG_API,"zebra_errCode: %d",zh->errCode);
1007 yaz_log(LOG_API,"zebra_errCode: o");
1011 const char *zebra_errString (ZebraHandle zh)
1015 e= diagbib1_str (zh->errCode);
1016 yaz_log(LOG_API,"zebra_errString: %s",e);
1020 char *zebra_errAdd (ZebraHandle zh)
1025 yaz_log(LOG_API,"zebra_errAdd: %s",a);
1029 void zebra_clearError(ZebraHandle zh)
1038 int zebra_auth (ZebraHandle zh, const char *user, const char *pass)
1048 sprintf(u, "perm.%.30s", user ? user : "anonymous");
1049 p = res_get(zs->global_res, u);
1050 xfree (zh->user_perm);
1051 zh->user_perm = xstrdup(p ? p : "r");
1053 /* users that don't require a password .. */
1054 if (zh->user_perm && strchr(zh->user_perm, 'a'))
1057 if (!zs->passwd_db || !passwd_db_auth (zs->passwd_db, user, pass))
1062 int zebra_admin_import_begin (ZebraHandle zh, const char *database,
1063 const char *record_type)
1066 yaz_log(LOG_API,"zebra_admin_import_begin db=%s rt=%s",
1067 database, record_type);
1069 if (zebra_select_database(zh, database))
1071 if (zebra_begin_trans (zh, 1))
1076 int zebra_admin_import_end (ZebraHandle zh)
1079 yaz_log(LOG_API,"zebra_admin_import_end");
1081 zebra_end_trans (zh);
1085 int zebra_admin_import_segment (ZebraHandle zh, Z_Segment *segment)
1090 yaz_log(LOG_API,"zebra_admin_import_segment");
1092 for (i = 0; i<segment->num_segmentRecords; i++)
1094 Z_NamePlusRecord *npr = segment->segmentRecords[i];
1096 printf ("--------------%d--------------------\n", i);
1097 /* FIXME - What! printing on stdout ??? */
1098 if (npr->which == Z_NamePlusRecord_intermediateFragment)
1100 Z_FragmentSyntax *fragment = npr->u.intermediateFragment;
1101 if (fragment->which == Z_FragmentSyntax_notExternallyTagged)
1103 Odr_oct *oct = fragment->u.notExternallyTagged;
1104 printf ("%.*s", (oct->len > 100 ? 100 : oct->len) ,
1109 zebra_update_record(zh,
1110 0, /* record Type */
1122 int zebra_admin_exchange_record (ZebraHandle zh,
1123 const char *rec_buf,
1125 const char *recid_buf, size_t recid_len,
1127 /* 1 = insert. Fail it already exists */
1128 /* 2 = replace. Fail it does not exist */
1129 /* 3 = delete. Fail if does not exist */
1130 /* 4 = update. Insert/replace */
1136 assert(action>0 && action <=4);
1139 yaz_log(LOG_API,"zebra_admin_exchange_record ac=%d", action);
1142 if (!recid_buf || recid_len <= 0 || recid_len >= sizeof(recid_z))
1144 memcpy (recid_z, recid_buf, recid_len);
1145 recid_z[recid_len] = 0;
1147 if (zebra_begin_trans(zh, 1))
1150 rinfo = dict_lookup (zh->reg->matchDict, recid_z);
1153 if (action == 1) /* fail if insert */
1155 zebra_end_trans(zh);
1159 memcpy (&sysno, rinfo+1, sizeof(sysno));
1163 if (action == 2 || action == 3) /* fail if delete or update */
1165 zebra_end_trans(zh);
1168 action = 1; /* make it an insert (if it's an update).. */
1170 buffer_extract_record (zh, rec_buf, rec_len,
1171 action == 3 ? 1 : 0 /* delete flag */,
1177 0, /* force update */
1178 1 /* allow update */
1182 dict_insert (zh->reg->matchDict, recid_z, sizeof(sysno), &sysno);
1184 else if (action == 3)
1186 dict_delete (zh->reg->matchDict, recid_z);
1188 zebra_end_trans(zh);
1192 int delete_w_handle(const char *info, void *handle)
1194 ZebraHandle zh = (ZebraHandle) handle;
1198 if (*info == sizeof(pos))
1200 memcpy (&pos, info+1, sizeof(pos));
1201 isamb_unlink(zh->reg->isamb, pos);
1206 static int delete_SU_handle(void *handle, int ord)
1208 ZebraHandle zh = (ZebraHandle) handle;
1212 ord_len = key_SU_encode (ord, ord_buf);
1213 ord_buf[ord_len] = '\0';
1215 assert (zh->reg->isamb);
1216 dict_delete_subtree(zh->reg->dict, ord_buf,
1217 zh, delete_w_handle);
1221 int zebra_drop_database (ZebraHandle zh, const char *database)
1225 yaz_log(LOG_API,"zebra_drop_database");
1228 if (zebra_select_database (zh, database))
1230 if (zebra_begin_trans (zh, 1))
1234 zebraExplain_curDatabase (zh->reg->zei, database);
1236 zebraExplain_trav_ord(zh->reg->zei, zh, delete_SU_handle);
1237 zebraExplain_removeDatabase(zh->reg->zei, zh);
1241 yaz_log(LOG_WARN, "drop database only supported for isam:b");
1244 zebra_end_trans (zh);
1248 int zebra_create_database (ZebraHandle zh, const char *database)
1251 yaz_log(LOG_API,"zebra_create_database %s",database);
1255 if (zebra_select_database (zh, database))
1257 if (zebra_begin_trans (zh, 1))
1260 /* announce database */
1261 if (zebraExplain_newDatabase (zh->reg->zei, database, 0
1262 /* explainDatabase */))
1264 zebra_end_trans (zh);
1266 zh->errString = "database already exist";
1269 zebra_end_trans (zh);
1273 int zebra_string_norm (ZebraHandle zh, unsigned reg_id,
1274 const char *input_str, int input_len,
1275 char *output_str, int output_len)
1281 yaz_log(LOG_API,"zebra_string_norm ");
1283 if (!zh->reg->zebra_maps)
1285 wrbuf = zebra_replace(zh->reg->zebra_maps, reg_id, "",
1286 input_str, input_len);
1289 if (wrbuf_len(wrbuf) >= output_len)
1291 if (wrbuf_len(wrbuf))
1292 memcpy (output_str, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
1293 output_str[wrbuf_len(wrbuf)] = '\0';
1294 return wrbuf_len(wrbuf);
1298 int zebra_set_state (ZebraHandle zh, int val, int seqno)
1299 /* FIXME - zint seqno ?? */
1301 char state_fname[256];
1306 yaz_log(LOG_API,"zebra_set_state v=%d seq=%d", val, seqno);
1309 sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1310 fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1311 f = fopen (fname, "w");
1313 yaz_log (LOG_DEBUG, "zebra_set_state: %c %d %ld", val, seqno, p);
1314 fprintf (f, "%c %d %ld\n", val, seqno, p);
1320 int zebra_get_state (ZebraHandle zh, char *val, int *seqno)
1322 char state_fname[256];
1327 yaz_log(LOG_API,"zebra_get_state ");
1329 sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1330 fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1331 f = fopen (fname, "r");
1337 fscanf (f, "%c %d", val, seqno);
1344 int zebra_begin_read (ZebraHandle zh)
1346 return zebra_begin_trans(zh, 0);
1349 int zebra_end_read (ZebraHandle zh)
1351 return zebra_end_trans(zh);
1354 static void read_res_for_transaction(ZebraHandle zh)
1356 const char *group = res_get(zh->res, "group");
1358 /* FIXME - do we still use groups ?? */
1360 zh->m_group = group;
1361 v = res_get_prefix(zh->res, "followLinks", group, "1");
1362 zh->m_follow_links = atoi(v);
1364 zh->m_record_id = res_get_prefix(zh->res, "recordId", group, 0);
1365 zh->m_record_type = res_get_prefix(zh->res, "recordType", group, 0);
1367 v = res_get_prefix(zh->res, "storeKeys", group, "1");
1368 zh->m_store_keys = atoi(v);
1370 v = res_get_prefix(zh->res, "storeData", group, "1");
1371 zh->m_store_data = atoi(v);
1373 v = res_get_prefix(zh->res, "explainDatabase", group, "0");
1374 zh->m_explain_database = atoi(v);
1376 v = res_get_prefix(zh->res, "openRW", group, "1");
1377 zh->m_flag_rw = atoi(v);
1379 v = res_get_prefix(zh->res, "fileVerboseLimit", group, "100000");
1380 zh->m_file_verbose_limit = atoi(v);
1383 int zebra_begin_trans (ZebraHandle zh, int rw)
1389 zh->errString = "zebra_begin_trans: no database selected";
1393 yaz_log(LOG_API,"zebra_begin_trans rw=%d",rw);
1397 if (rw && !strchr(zh->user_perm, 'w'))
1411 const char *rval = 0;
1416 read_res_for_transaction(zh);
1419 if (zh->trans_no != 1)
1422 zh->errString = "zebra_begin_trans: write trans not allowed within read trans";
1427 resultSetInvalidate (zh);
1428 zebra_register_close (zh->service, zh->reg);
1430 zh->trans_w_no = zh->trans_no;
1434 zh->records_inserted = 0;
1435 zh->records_updated = 0;
1436 zh->records_deleted = 0;
1437 zh->records_processed = 0;
1439 #if HAVE_SYS_TIMES_H
1443 if (zh->shadow_enable)
1444 rval = res_get (zh->res, "shadow");
1446 for (pass = 0; pass < 2; pass++)
1450 zebra_lock_r (zh->lock_normal);
1451 zebra_lock_w (zh->lock_shadow);
1455 zebra_lock_w (zh->lock_normal);
1456 zebra_lock_w (zh->lock_shadow);
1459 zebra_get_state (zh, &val, &seqno);
1462 yaz_log (LOG_WARN, "previous transaction didn't finish commit");
1463 zebra_unlock (zh->lock_shadow);
1464 zebra_unlock (zh->lock_normal);
1468 else if (val == 'd')
1472 BFiles bfs = bfs_create (res_get (zh->res, "shadow"),
1474 yaz_log (LOG_WARN, "previous transaction didn't reach commit");
1475 bf_commitClean (bfs, rval);
1480 yaz_log (LOG_WARN, "your previous transaction didn't finish");
1487 yaz_log (LOG_FATAL, "zebra_begin_trans couldn't finish commit");
1491 zebra_set_state (zh, 'd', seqno);
1493 zh->reg = zebra_register_open (zh->service, zh->reg_name,
1494 1, rval ? 1 : 0, zh->res,
1497 zh->reg->seqno = seqno;
1500 zebra_set_state (zh, 'o', seqno);
1502 zebra_unlock (zh->lock_shadow);
1503 zebra_unlock (zh->lock_normal);
1509 zh->errString = "zebra_begin_trans: cannot open register";
1510 yaz_log(LOG_FATAL, zh->errString);
1522 if (zh->trans_no != 1)
1524 zebra_flush_reg (zh);
1528 #if HAVE_SYS_TIMES_H
1537 if (!zh->lock_normal || !zh->lock_shadow)
1543 zebra_get_state (zh, &val, &seqno);
1549 else if (seqno != zh->reg->seqno)
1551 yaz_log (LOG_DEBUG, "reopen seqno cur/old %d/%d",
1552 seqno, zh->reg->seqno);
1555 else if (zh->reg->last_val != val)
1557 yaz_log (LOG_DEBUG, "reopen last cur/old %d/%d",
1558 val, zh->reg->last_val);
1565 zebra_lock_r (zh->lock_shadow);
1567 zebra_lock_r (zh->lock_normal);
1571 resultSetInvalidate (zh);
1572 zebra_register_close (zh->service, zh->reg);
1574 zh->reg = zebra_register_open (zh->service, zh->reg_name,
1575 0, val == 'c' ? 1 : 0,
1576 zh->res, zh->path_reg);
1579 zebra_unlock (zh->lock_normal);
1580 zebra_unlock (zh->lock_shadow);
1585 zh->reg->last_val = val;
1586 zh->reg->seqno = seqno;
1588 read_res_for_transaction(zh);
1592 int zebra_end_trans (ZebraHandle zh)
1595 ZebraTransactionStatus dummy;
1596 yaz_log(LOG_API,"zebra_end_trans");
1597 return zebra_end_transaction(zh, &dummy);
1600 int zebra_end_transaction (ZebraHandle zh, ZebraTransactionStatus *status)
1608 yaz_log(LOG_API,"zebra_end_transaction");
1610 status->processed = 0;
1611 status->inserted = 0;
1612 status->updated = 0;
1613 status->deleted = 0;
1617 if (!zh->res || !zh->reg)
1620 zh->errString = "zebra_end_trans: no open transaction";
1623 if (zh->trans_no != zh->trans_w_no)
1626 if (zh->trans_no != 0)
1629 /* release read lock */
1631 zebra_unlock (zh->lock_normal);
1632 zebra_unlock (zh->lock_shadow);
1635 { /* release write lock */
1639 yaz_log (LOG_DEBUG, "zebra_end_trans");
1640 rval = res_get (zh->res, "shadow");
1642 zebraExplain_runNumberIncrement (zh->reg->zei, 1);
1644 zebra_flush_reg (zh);
1646 resultSetInvalidate (zh);
1648 zebra_register_close (zh->service, zh->reg);
1651 yaz_log (LOG_LOG, "Records: "ZINT_FORMAT" i/u/d "
1652 ZINT_FORMAT"/"ZINT_FORMAT"/"ZINT_FORMAT,
1653 zh->records_processed, zh->records_inserted,
1654 zh->records_updated, zh->records_deleted);
1656 status->processed = zh->records_processed;
1657 status->inserted = zh->records_inserted;
1658 status->updated = zh->records_updated;
1659 status->deleted = zh->records_deleted;
1661 zebra_get_state (zh, &val, &seqno);
1664 BFiles bfs = bfs_create (rval, zh->path_reg);
1665 yaz_log (LOG_DEBUG, "deleting shadow val=%c", val);
1666 bf_commitClean (bfs, rval);
1671 zebra_set_state (zh, 'o', seqno);
1673 zebra_unlock (zh->lock_shadow);
1674 zebra_unlock (zh->lock_normal);
1677 #if HAVE_SYS_TIMES_H
1679 logf (LOG_LOG, "user/system: %ld/%ld",
1680 (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1681 (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1683 status->utime = (long) (zh->tms2.tms_utime - zh->tms1.tms_utime);
1684 status->stime = (long) (zh->tms2.tms_stime - zh->tms1.tms_stime);
1689 int zebra_repository_update (ZebraHandle zh, const char *path)
1694 logf (LOG_API, "updating %s", path);
1695 repositoryUpdate (zh, path);
1699 int zebra_repository_delete (ZebraHandle zh, const char *path)
1704 logf (LOG_API, "deleting %s", path);
1705 repositoryDelete (zh, path);
1709 int zebra_repository_show (ZebraHandle zh, const char *path)
1713 yaz_log(LOG_API,"zebra_repository_show");
1715 repositoryShow (zh, path);
1719 static int zebra_commit_ex (ZebraHandle zh, int clean_only)
1733 rval = res_get (zh->res, "shadow");
1736 logf (LOG_WARN, "Cannot perform commit");
1737 logf (LOG_WARN, "No shadow area defined");
1741 zebra_lock_w (zh->lock_normal);
1742 zebra_lock_r (zh->lock_shadow);
1744 bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1746 zebra_get_state (zh, &val, &seqno);
1749 bf_cache (bfs, rval);
1750 if (bf_commitExists (bfs))
1753 zebra_set_state (zh, 'd', seqno);
1756 zebra_set_state (zh, 'c', seqno);
1758 logf (LOG_DEBUG, "commit start");
1759 bf_commitExec (bfs);
1764 logf (LOG_DEBUG, "commit clean");
1765 bf_commitClean (bfs, rval);
1767 zebra_set_state (zh, 'o', seqno);
1771 logf (LOG_LOG, "nothing to commit");
1775 zebra_unlock (zh->lock_shadow);
1776 zebra_unlock (zh->lock_normal);
1780 int zebra_clean (ZebraHandle zh)
1783 yaz_log(LOG_API,"zebra_clean");
1784 return zebra_commit_ex(zh, 1);
1787 int zebra_commit (ZebraHandle zh)
1790 yaz_log(LOG_API,"zebra_commit");
1791 return zebra_commit_ex(zh, 0);
1794 int zebra_init (ZebraHandle zh)
1799 yaz_log(LOG_API,"zebra_init");
1807 rval = res_get (zh->res, "shadow");
1809 bfs = bfs_create (res_get (zh->service->global_res, "register"),
1814 bf_cache (bfs, rval);
1818 zebra_set_state (zh, 'o', 0);
1822 int zebra_compact (ZebraHandle zh)
1826 yaz_log(LOG_API,"zebra_compact");
1833 bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1839 int zebra_result (ZebraHandle zh, int *code, char **addinfo)
1842 yaz_log(LOG_API,"zebra_result");
1843 *code = zh->errCode;
1844 *addinfo = zh->errString;
1848 int zebra_shadow_enable (ZebraHandle zh, int value)
1851 yaz_log(LOG_API,"zebra_shadow_enable");
1853 zh->shadow_enable = value;
1857 int zebra_record_encoding (ZebraHandle zh, const char *encoding)
1861 yaz_log(LOG_API,"zebra_record_encoding");
1863 xfree (zh->record_encoding);
1867 * Something about charset aliases. Oleg???
1870 if (zh->iconv_to_utf8 != 0)
1871 yaz_iconv_close(zh->iconv_to_utf8);
1872 if (zh->iconv_from_utf8 != 0)
1873 yaz_iconv_close(zh->iconv_from_utf8);
1875 zh->record_encoding = xstrdup (encoding);
1877 logf(LOG_DEBUG, "Reset record encoding: %s", encoding);
1880 yaz_iconv_open ("UTF-8", encoding);
1881 if (zh->iconv_to_utf8 == 0)
1882 yaz_log (LOG_WARN, "iconv: %s to UTF-8 unsupported", encoding);
1883 zh->iconv_from_utf8 =
1884 yaz_iconv_open (encoding, "UTF-8");
1885 if (zh->iconv_to_utf8 == 0)
1886 yaz_log (LOG_WARN, "iconv: UTF-8 to %s unsupported", encoding);
1891 int zebra_set_resource(ZebraHandle zh, const char *name, const char *value)
1896 yaz_log(LOG_API,"zebra_set_resource %s:%s",name,value);
1898 res_set(zh->res, name, value);
1902 const char *zebra_get_resource(ZebraHandle zh,
1903 const char *name, const char *defaultvalue)
1908 assert(defaultvalue);
1909 v= res_get_def( zh->res, name, (char *)defaultvalue);
1911 yaz_log(LOG_API,"zebra_get_resource %s:%s",name,v);
1915 /* moved from zebra_api_ext.c by pop */
1916 /* FIXME: Should this really be public??? -Heikki */
1918 int zebra_trans_no (ZebraHandle zh)
1921 yaz_log(LOG_API,"zebra_trans_no");
1922 return zh->trans_no;
1925 int zebra_get_shadow_enable (ZebraHandle zh)
1928 yaz_log(LOG_API,"zebra_get_shadow_enable");
1929 return (zh->shadow_enable);
1932 int zebra_set_shadow_enable (ZebraHandle zh, int value)
1935 yaz_log(LOG_API,"zebra_set_shadow_enable %d",value);
1936 zh->shadow_enable = value;
1940 /* almost the same as zebra_records_retrieve ... but how did it work?
1941 I mean for multiple records ??? CHECK ??? */
1942 void api_records_retrieve (ZebraHandle zh, ODR stream,
1943 const char *setname, Z_RecordComposition *comp,
1944 oid_value input_format, int num_recs,
1945 ZebraRetrievalRecord *recs)
1955 yaz_log(LOG_API,"api_records_retrieve s=%s n=%d",setname,num_recs);
1960 zh->errString = odr_strdup (stream, setname);
1966 if (zebra_begin_read (zh))
1969 pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
1970 for (i = 0; i<num_recs; i++)
1971 pos_array[i] = recs[i].position;
1972 poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
1975 logf (LOG_DEBUG, "zebraPosSetCreate error");
1977 zh->errString = nmem_strdup (stream->mem, setname);
1981 for (i = 0; i<num_recs; i++)
1985 recs[i].errCode = 0;
1986 recs[i].format = VAL_SUTRS;
1987 recs[i].len = strlen(poset[i].term);
1988 recs[i].buf = poset[i].term;
1989 recs[i].base = poset[i].db;
1993 else if (poset[i].sysno)
1995 /* changed here ??? CHECK ??? */
1998 zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
1999 stream, input_format, comp,
2004 recs[i].buf = (char *) odr_malloc(stream,recs[i].len);
2005 memcpy(recs[i].buf, b, recs[i].len);
2006 recs[i].errString = 0; /* Hmmm !!! we should get this */
2007 recs[i].sysno = poset[i].sysno;
2008 recs[i].score = poset[i].score;
2014 sprintf (num_str, "%d", pos_array[i]);
2016 zh->errString = odr_strdup (stream, num_str);
2021 zebraPosSetDestroy (zh, poset, num_recs);
2023 zebra_end_read (zh);
2028 /* ---------------------------------------------------------------------------
2029 Record insert(=update), delete
2031 If sysno is provided, then it's used to identify the record.
2032 If not, and match_criteria is provided, then sysno is guessed
2033 If not, and a record is provided, then sysno is got from there
2034 NOTE: Now returns 0 at success and updates sysno, which is an int*
2038 int zebra_add_record(ZebraHandle zh,
2039 const char *buf, int buf_size)
2042 return zebra_update_record(zh, 0, &sysno, 0, 0, buf, buf_size, 0);
2045 int zebra_insert_record (ZebraHandle zh,
2046 const char *recordType,
2047 SYSNO *sysno, const char *match, const char *fname,
2048 const char *buf, int buf_size, int force_update)
2054 yaz_log(LOG_API, "zebra_insert_record sysno=" ZINT_FORMAT, *sysno);
2056 if (buf_size < 1) buf_size = strlen(buf);
2058 if (zebra_begin_trans(zh, 1))
2060 res = buffer_extract_record (zh, buf, buf_size,
2061 0, /* delete_flag */
2067 0); /* allow_update */
2068 zebra_end_trans(zh);
2072 int zebra_update_record (ZebraHandle zh,
2073 const char *recordType,
2074 SYSNO* sysno, const char *match, const char *fname,
2075 const char *buf, int buf_size,
2083 yaz_log(LOG_API, "zebra_update_record sysno=" ZINT_FORMAT, *sysno);
2085 if (buf_size < 1) buf_size = strlen(buf);
2087 if (zebra_begin_trans(zh, 1))
2089 res = buffer_extract_record (zh, buf, buf_size,
2090 0, /* delete_flag */
2096 1); /* allow_update */
2097 zebra_end_trans(zh);
2101 int zebra_delete_record (ZebraHandle zh,
2102 const char *recordType,
2103 SYSNO *sysno, const char *match, const char *fname,
2104 const char *buf, int buf_size,
2111 yaz_log(LOG_API, "zebra_delete_record sysno=" ZINT_FORMAT, *sysno);
2113 if (buf_size < 1) buf_size = strlen(buf);
2115 if (zebra_begin_trans(zh, 1))
2117 res = buffer_extract_record (zh, buf, buf_size,
2118 1, /* delete_flag */
2124 1); /* allow_update */
2125 zebra_end_trans(zh);
2129 /* ---------------------------------------------------------------------------
2133 int zebra_search_PQF (ZebraHandle zh, const char *pqf_query,
2134 const char *setname, int *numhits)
2139 ODR odr = odr_createmem(ODR_ENCODE);
2144 yaz_log(LOG_API,"zebra_search_PQF s=%s q=%s",setname, pqf_query);
2146 query = p_query_rpn (odr, PROTO_Z3950, pqf_query);
2149 yaz_log (LOG_WARN, "bad query %s\n", pqf_query);
2151 res=zebra_search_RPN (zh, odr, query, setname, &hits);
2155 yaz_log(LOG_API,"Hits: %d",hits);
2163 /* ---------------------------------------------------------------------------
2164 Sort - a simplified interface, with optional read locks.
2166 int zebra_sort_by_specstr (ZebraHandle zh,
2168 const char *sort_spec,
2169 const char *output_setname,
2170 const char **input_setnames)
2172 int num_input_setnames = 0;
2173 int sort_status = 0;
2174 Z_SortKeySpecList *sort_sequence;
2178 assert(output_setname);
2179 assert(input_setnames);
2180 sort_sequence = yaz_sort_spec (stream, sort_spec);
2181 yaz_log(LOG_API,"sort (FIXME) ");
2184 logf(LOG_WARN,"invalid sort specs '%s'", sort_spec);
2189 /* we can do this, since the perl typemap code for char** will
2190 put a NULL at the end of list */
2191 while (input_setnames[num_input_setnames]) num_input_setnames++;
2193 if (zebra_begin_read (zh))
2196 resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
2197 output_setname, sort_sequence, &sort_status);