1 /* $Id: zebraapi.c,v 1.139 2004-10-29 11:23:52 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 zebraRankInstall (reg, rankzv_class);
297 recordCompression = res_get_def (res, "recordCompression", "none");
298 if (!strcmp (recordCompression, "none"))
299 record_compression = REC_COMPRESS_NONE;
300 if (!strcmp (recordCompression, "bzip2"))
301 record_compression = REC_COMPRESS_BZIP2;
303 if (!(reg->records = rec_open (reg->bfs, rw, record_compression)))
305 logf (LOG_WARN, "rec_open");
310 reg->matchDict = dict_open_res (reg->bfs, GMATCH_DICT, 20, 1, 0, res);
312 if (!(reg->dict = dict_open_res (reg->bfs, FNAME_DICT, 40, rw, 0, res)))
314 logf (LOG_WARN, "dict_open");
317 if (!(reg->sortIdx = sortIdx_open (reg->bfs, rw)))
319 logf (LOG_WARN, "sortIdx_open");
322 if (res_get_match (res, "isam", "s", ISAM_DEFAULT))
324 struct ISAMS_M_s isams_m;
325 if (!(reg->isams = isams_open (reg->bfs, FNAME_ISAMS, rw,
326 key_isams_m(res, &isams_m))))
328 logf (LOG_WARN, "isams_open");
332 if (res_get_match (res, "isam", "c", ISAM_DEFAULT))
334 struct ISAMC_M_s isamc_m;
335 if (!(reg->isamc = isc_open (reg->bfs, FNAME_ISAMC,
336 rw, key_isamc_m(res, &isamc_m))))
338 logf (LOG_WARN, "isc_open");
342 if (res_get_match (res, "isam", "b", ISAM_DEFAULT))
344 struct ISAMC_M_s isamc_m;
346 if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
347 rw, key_isamc_m(res, &isamc_m), 0)))
349 logf (LOG_WARN, "isamb_open");
353 if (res_get_match (res, "isam", "bc", ISAM_DEFAULT))
355 struct ISAMC_M_s isamc_m;
357 if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
358 rw, key_isamc_m(res, &isamc_m), 1)))
360 logf (LOG_WARN, "isamb_open");
364 if (res_get_match (res, "isam", "null", ISAM_DEFAULT))
366 struct ISAMC_M_s isamc_m;
368 if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
369 rw, key_isamc_m(res, &isamc_m), -1)))
371 logf (LOG_WARN, "isamb_open");
375 reg->zei = zebraExplain_open (reg->records, reg->dh,
380 logf (LOG_WARN, "Cannot obtain EXPLAIN information");
384 yaz_log (LOG_DEBUG, "zebra_register_open ok p=%p", reg);
388 int zebra_admin_shutdown (ZebraHandle zh)
391 yaz_log(LOG_API,"zebra_admin_shutdown");
394 zebra_mutex_cond_lock (&zh->service->session_lock);
395 zh->service->stop_flag = 1;
396 zebra_mutex_cond_unlock (&zh->service->session_lock);
400 int zebra_admin_start (ZebraHandle zh)
404 yaz_log(LOG_API,"zebra_admin_start");
407 zebra_mutex_cond_lock (&zs->session_lock);
408 zebra_mutex_cond_unlock (&zs->session_lock);
412 static void zebra_register_close (ZebraService zs, struct zebra_register *reg)
416 yaz_log(LOG_DEBUG, "zebra_register_close p=%p", reg);
421 zebraExplain_close (reg->zei);
422 dict_close (reg->dict);
424 dict_close (reg->matchDict);
425 sortIdx_close (reg->sortIdx);
427 isams_close (reg->isams);
429 isc_close (reg->isamc);
431 isamb_close (reg->isamb);
432 rec_close (®->records);
435 recTypes_destroy (reg->recTypes);
436 zebra_maps_close (reg->zebra_maps);
437 zebraRankDestroy (reg);
438 bfs_destroy (reg->bfs);
439 data1_destroy (reg->dh);
441 xfree (reg->sortKeys.buf);
442 xfree (reg->keys.buf);
443 if (reg->keys.codec_handle)
444 iscz1_stop(reg->keys.codec_handle);
445 xfree (reg->key_buf);
450 int zebra_stop(ZebraService zs)
454 yaz_log (LOG_API, "zebra_stop");
458 zebra_close (zs->sessions);
461 zebra_mutex_cond_destroy (&zs->session_lock);
464 passwd_db_close (zs->passwd_db);
466 recTypeClass_destroy(zs->record_classes);
467 nmem_destroy(zs->nmem);
468 res_close (zs->global_res);
469 xfree (zs->configName);
474 int zebra_close (ZebraHandle zh)
477 struct zebra_session **sp;
480 yaz_log(LOG_API,"zebra_close");
487 yaz_log (LOG_DEBUG, "zebra_close zh=%p", zh);
488 resultSetDestroy (zh, -1, 0, 0);
491 zebra_register_close (zh->service, zh->reg);
492 zebra_close_res (zh);
494 xfree (zh->record_encoding);
496 for (i = 0; i < zh->num_basenames; i++)
497 xfree (zh->basenames[i]);
498 xfree (zh->basenames);
500 if (zh->iconv_to_utf8 != 0)
501 yaz_iconv_close (zh->iconv_to_utf8);
502 if (zh->iconv_from_utf8 != 0)
503 yaz_iconv_close (zh->iconv_from_utf8);
505 zebra_mutex_cond_lock (&zs->session_lock);
506 zebra_lock_destroy (zh->lock_normal);
507 zebra_lock_destroy (zh->lock_shadow);
519 zebra_mutex_cond_unlock (&zs->session_lock);
520 xfree (zh->reg_name);
521 xfree (zh->user_perm);
522 zh->service=0; /* more likely to trigger an assert */
523 xfree (zh->path_reg);
528 struct map_baseinfo {
534 char **new_basenames;
538 static Res zebra_open_res (ZebraHandle zh)
547 sprintf (fname, "%.200s/zebra.cfg", zh->path_reg);
548 res = res_open (fname, zh->service->global_res, 0);
550 res = zh->service->global_res;
552 else if (*zh->reg_name == 0)
554 res = zh->service->global_res;
558 yaz_log (LOG_WARN, "no register root specified");
559 return 0; /* no path for register - fail! */
564 static void zebra_close_res (ZebraHandle zh)
568 if (zh->res != zh->service->global_res)
573 static int zebra_select_register (ZebraHandle zh, const char *new_reg)
577 if (zh->res && strcmp (zh->reg_name, new_reg) == 0)
581 assert (zh->reg == 0);
582 assert (*zh->reg_name == 0);
588 resultSetInvalidate (zh);
589 zebra_register_close (zh->service, zh->reg);
594 xfree (zh->reg_name);
595 zh->reg_name = xstrdup (new_reg);
597 xfree (zh->path_reg);
599 if (zh->service->path_root)
601 zh->path_reg = xmalloc (strlen(zh->service->path_root) +
602 strlen(zh->reg_name) + 3);
603 strcpy (zh->path_reg, zh->service->path_root);
606 strcat (zh->path_reg, "/");
607 strcat (zh->path_reg, zh->reg_name);
610 zh->res = zebra_open_res (zh);
613 zebra_lock_destroy (zh->lock_normal);
617 zebra_lock_destroy (zh->lock_shadow);
623 const char *lock_area =res_get (zh->res, "lockDir");
625 if (!lock_area && zh->path_reg)
626 res_set (zh->res, "lockDir", zh->path_reg);
627 sprintf (fname, "norm.%s.LCK", zh->reg_name);
629 zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
631 sprintf (fname, "shadow.%s.LCK", zh->reg_name);
633 zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
639 void map_basenames_func (void *vp, const char *name, const char *value)
641 struct map_baseinfo *p = (struct map_baseinfo *) vp;
643 char fromdb[128], todb[8][128];
650 sscanf (value, "%127s %127s %127s %127s %127s %127s %127s %127s %127s",
651 fromdb, todb[0], todb[1], todb[2], todb[3], todb[4],
652 todb[5], todb[6], todb[7]);
656 for (i = 0; i<p->num_bases; i++)
657 if (p->basenames[i] && !STRCASECMP (p->basenames[i], fromdb))
660 for (i = 0; i < no; i++)
662 if (p->new_num_bases == p->new_num_max)
664 p->new_basenames[(p->new_num_bases)++] =
665 nmem_strdup (p->mem, todb[i]);
671 void map_basenames (ZebraHandle zh, ODR stream,
672 int *num_bases, char ***basenames)
674 struct map_baseinfo info;
675 struct map_baseinfo *p = &info;
678 yaz_log(LOG_API,"map_basenames ");
684 info.num_bases = *num_bases;
685 info.basenames = *basenames;
686 info.new_num_max = 128;
687 info.new_num_bases = 0;
688 info.new_basenames = (char **)
689 odr_malloc (stream, sizeof(*info.new_basenames) * info.new_num_max);
690 info.mem = stream->mem;
692 res_trav (zh->service->global_res, "mapdb", &info, map_basenames_func);
694 for (i = 0; i<p->num_bases; i++)
695 if (p->basenames[i] && p->new_num_bases < p->new_num_max)
697 p->new_basenames[(p->new_num_bases)++] =
698 nmem_strdup (p->mem, p->basenames[i]);
700 *num_bases = info.new_num_bases;
701 *basenames = info.new_basenames;
702 for (i = 0; i<*num_bases; i++)
703 logf (LOG_DEBUG, "base %s", (*basenames)[i]);
706 int zebra_select_database (ZebraHandle zh, const char *basename)
709 yaz_log(LOG_API,"zebra_select_database %s",basename);
712 return zebra_select_databases (zh, 1, &basename);
715 int zebra_select_databases (ZebraHandle zh, int num_bases,
716 const char **basenames)
725 yaz_log(LOG_API,"zebra_select_databases n=%d [0]=%s",
726 num_bases,basenames[0]);
734 for (i = 0; i < zh->num_basenames; i++)
735 xfree (zh->basenames[i]);
736 xfree (zh->basenames);
738 zh->num_basenames = num_bases;
739 zh->basenames = xmalloc (zh->num_basenames * sizeof(*zh->basenames));
740 for (i = 0; i < zh->num_basenames; i++)
741 zh->basenames[i] = xstrdup (basenames[i]);
743 cp = strrchr(basenames[0], '/');
746 len = cp - basenames[0];
747 new_reg = xmalloc (len + 1);
748 memcpy (new_reg, basenames[0], len);
752 new_reg = xstrdup ("");
753 for (i = 1; i<num_bases; i++)
757 cp1 = strrchr (basenames[i], '/');
765 if (len != cp1 - basenames[i] ||
766 memcmp (basenames[i], new_reg, len))
781 zebra_select_register (zh, new_reg);
788 if (!zh->lock_normal || !zh->lock_shadow)
796 int zebra_search_RPN (ZebraHandle zh, ODR o,
797 Z_RPNQuery *query, const char *setname, int *hits)
806 yaz_log(LOG_API,"zebra_search_rpn");
811 if (zebra_begin_read (zh))
814 resultSetAddRPN (zh, odr_extract_mem(o), query,
815 zh->num_basenames, zh->basenames, setname);
818 max = res_get (zh->res, "maxhits");
823 maxhits=INT_MAX; /* properly rounded, to make it look like a limit*/
824 while (maxhits>100) { maxhits/=10; i++;}
825 while (i--) maxhits *= 10;
827 if (zh->hits > maxhits) { /* too large for yaz to handle */
828 logf(LOG_DEBUG,"limiting hits to "ZINT_FORMAT, maxhits);
836 int zebra_records_retrieve (ZebraHandle zh, ODR stream,
837 const char *setname, Z_RecordComposition *comp,
838 oid_value input_format, int num_recs,
839 ZebraRetrievalRecord *recs)
842 int i, *pos_array, ret = 0;
849 yaz_log(LOG_API,"zebra_records_retrieve n=%d",num_recs);
855 zh->errString = odr_strdup (stream, setname);
861 if (zebra_begin_read (zh))
864 pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
865 for (i = 0; i<num_recs; i++)
866 pos_array[i] = recs[i].position;
867 poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
870 logf (LOG_DEBUG, "zebraPosSetCreate error");
872 zh->errString = nmem_strdup (stream->mem, setname);
877 for (i = 0; i<num_recs; i++)
882 recs[i].format = VAL_SUTRS;
883 recs[i].len = strlen(poset[i].term);
884 recs[i].buf = poset[i].term;
885 recs[i].base = poset[i].db;
887 else if (poset[i].sysno)
890 zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
891 stream, input_format, comp,
892 &recs[i].format, &recs[i].buf,
895 recs[i].errString = NULL;
896 recs[i].score=poset[i].score;
897 recs[i].sysno=poset[i].sysno;
903 sprintf (num_str, "%d", pos_array[i]);
905 zh->errString = odr_strdup (stream, num_str);
910 zebraPosSetDestroy (zh, poset, num_recs);
917 int zebra_scan (ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
918 oid_value attributeset,
919 int *position, int *num_entries, ZebraScanEntry **entries,
929 yaz_log(LOG_API,"zebra_scan");
931 if (zebra_begin_read (zh))
937 rpn_scan (zh, stream, zapt, attributeset,
938 zh->num_basenames, zh->basenames, position,
939 num_entries, entries, is_partial, 0, 0);
944 int zebra_sort (ZebraHandle zh, ODR stream,
945 int num_input_setnames, const char **input_setnames,
946 const char *output_setname, Z_SortKeySpecList *sort_sequence,
951 assert(num_input_setnames>0);
952 assert(input_setnames);
953 assert(sort_sequence);
955 yaz_log(LOG_API,"zebra_sort");
957 if (zebra_begin_read (zh))
959 resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
960 output_setname, sort_sequence, sort_status);
965 int zebra_deleleResultSet(ZebraHandle zh, int function,
966 int num_setnames, char **setnames,
971 assert(num_setnames>0);
974 yaz_log(LOG_API,"zebra_deleleResultSet n=%d",num_setnames);
976 if (zebra_begin_read(zh))
977 return Z_DeleteStatus_systemProblemAtTarget;
980 case Z_DeleteResultSetRequest_list:
981 resultSetDestroy (zh, num_setnames, setnames, statuses);
983 case Z_DeleteResultSetRequest_all:
984 resultSetDestroy (zh, -1, 0, statuses);
988 status = Z_DeleteStatus_success;
989 for (i = 0; i<num_setnames; i++)
990 if (statuses[i] == Z_DeleteStatus_resultSetDidNotExist)
991 status = statuses[i];
995 int zebra_errCode (ZebraHandle zh)
999 yaz_log(LOG_API,"zebra_errCode: %d",zh->errCode);
1002 yaz_log(LOG_API,"zebra_errCode: o");
1006 const char *zebra_errString (ZebraHandle zh)
1010 e= diagbib1_str (zh->errCode);
1011 yaz_log(LOG_API,"zebra_errString: %s",e);
1015 char *zebra_errAdd (ZebraHandle zh)
1020 yaz_log(LOG_API,"zebra_errAdd: %s",a);
1024 void zebra_clearError(ZebraHandle zh)
1033 int zebra_auth (ZebraHandle zh, const char *user, const char *pass)
1043 sprintf(u, "perm.%.30s", user ? user : "anonymous");
1044 p = res_get(zs->global_res, u);
1045 xfree (zh->user_perm);
1046 zh->user_perm = xstrdup(p ? p : "r");
1048 /* users that don't require a password .. */
1049 if (zh->user_perm && strchr(zh->user_perm, 'a'))
1052 if (!zs->passwd_db || !passwd_db_auth (zs->passwd_db, user, pass))
1057 int zebra_admin_import_begin (ZebraHandle zh, const char *database,
1058 const char *record_type)
1061 yaz_log(LOG_API,"zebra_admin_import_begin db=%s rt=%s",
1062 database, record_type);
1064 if (zebra_select_database(zh, database))
1066 if (zebra_begin_trans (zh, 1))
1071 int zebra_admin_import_end (ZebraHandle zh)
1074 yaz_log(LOG_API,"zebra_admin_import_end");
1076 zebra_end_trans (zh);
1080 int zebra_admin_import_segment (ZebraHandle zh, Z_Segment *segment)
1085 yaz_log(LOG_API,"zebra_admin_import_segment");
1087 for (i = 0; i<segment->num_segmentRecords; i++)
1089 Z_NamePlusRecord *npr = segment->segmentRecords[i];
1091 printf ("--------------%d--------------------\n", i);
1092 /* FIXME - What! printing on stdout ??? */
1093 if (npr->which == Z_NamePlusRecord_intermediateFragment)
1095 Z_FragmentSyntax *fragment = npr->u.intermediateFragment;
1096 if (fragment->which == Z_FragmentSyntax_notExternallyTagged)
1098 Odr_oct *oct = fragment->u.notExternallyTagged;
1099 printf ("%.*s", (oct->len > 100 ? 100 : oct->len) ,
1104 zebra_update_record(zh,
1105 0, /* record Type */
1117 int zebra_admin_exchange_record (ZebraHandle zh,
1118 const char *rec_buf,
1120 const char *recid_buf, size_t recid_len,
1122 /* 1 = insert. Fail it already exists */
1123 /* 2 = replace. Fail it does not exist */
1124 /* 3 = delete. Fail if does not exist */
1125 /* 4 = update. Insert/replace */
1131 assert(action>0 && action <=4);
1134 yaz_log(LOG_API,"zebra_admin_exchange_record ac=%d", action);
1137 if (!recid_buf || recid_len <= 0 || recid_len >= sizeof(recid_z))
1139 memcpy (recid_z, recid_buf, recid_len);
1140 recid_z[recid_len] = 0;
1142 if (zebra_begin_trans(zh, 1))
1145 rinfo = dict_lookup (zh->reg->matchDict, recid_z);
1148 if (action == 1) /* fail if insert */
1150 zebra_end_trans(zh);
1154 memcpy (&sysno, rinfo+1, sizeof(sysno));
1158 if (action == 2 || action == 3) /* fail if delete or update */
1160 zebra_end_trans(zh);
1163 action = 1; /* make it an insert (if it's an update).. */
1165 buffer_extract_record (zh, rec_buf, rec_len,
1166 action == 3 ? 1 : 0 /* delete flag */,
1172 0, /* force update */
1173 1 /* allow update */
1177 dict_insert (zh->reg->matchDict, recid_z, sizeof(sysno), &sysno);
1179 else if (action == 3)
1181 dict_delete (zh->reg->matchDict, recid_z);
1183 zebra_end_trans(zh);
1187 int delete_w_handle(const char *info, void *handle)
1189 ZebraHandle zh = (ZebraHandle) handle;
1193 if (*info == sizeof(pos))
1195 memcpy (&pos, info+1, sizeof(pos));
1196 isamb_unlink(zh->reg->isamb, pos);
1201 static int delete_SU_handle(void *handle, int ord)
1203 ZebraHandle zh = (ZebraHandle) handle;
1207 ord_len = key_SU_encode (ord, ord_buf);
1208 ord_buf[ord_len] = '\0';
1210 assert (zh->reg->isamb);
1211 dict_delete_subtree(zh->reg->dict, ord_buf,
1212 zh, delete_w_handle);
1216 int zebra_drop_database (ZebraHandle zh, const char *database)
1220 yaz_log(LOG_API,"zebra_drop_database");
1223 if (zebra_select_database (zh, database))
1225 if (zebra_begin_trans (zh, 1))
1229 zebraExplain_curDatabase (zh->reg->zei, database);
1231 zebraExplain_trav_ord(zh->reg->zei, zh, delete_SU_handle);
1232 zebraExplain_removeDatabase(zh->reg->zei, zh);
1236 yaz_log(LOG_WARN, "drop database only supported for isam:b");
1239 zebra_end_trans (zh);
1243 int zebra_create_database (ZebraHandle zh, const char *database)
1246 yaz_log(LOG_API,"zebra_create_database %s",database);
1250 if (zebra_select_database (zh, database))
1252 if (zebra_begin_trans (zh, 1))
1255 /* announce database */
1256 if (zebraExplain_newDatabase (zh->reg->zei, database, 0
1257 /* explainDatabase */))
1259 zebra_end_trans (zh);
1261 zh->errString = "database already exist";
1264 zebra_end_trans (zh);
1268 int zebra_string_norm (ZebraHandle zh, unsigned reg_id,
1269 const char *input_str, int input_len,
1270 char *output_str, int output_len)
1276 yaz_log(LOG_API,"zebra_string_norm ");
1278 if (!zh->reg->zebra_maps)
1280 wrbuf = zebra_replace(zh->reg->zebra_maps, reg_id, "",
1281 input_str, input_len);
1284 if (wrbuf_len(wrbuf) >= output_len)
1286 if (wrbuf_len(wrbuf))
1287 memcpy (output_str, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
1288 output_str[wrbuf_len(wrbuf)] = '\0';
1289 return wrbuf_len(wrbuf);
1293 int zebra_set_state (ZebraHandle zh, int val, int seqno)
1294 /* FIXME - zint seqno ?? */
1296 char state_fname[256];
1301 yaz_log(LOG_API,"zebra_set_state v=%d seq=%d", val, seqno);
1304 sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1305 fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1306 f = fopen (fname, "w");
1308 yaz_log (LOG_DEBUG, "zebra_set_state: %c %d %ld", val, seqno, p);
1309 fprintf (f, "%c %d %ld\n", val, seqno, p);
1315 int zebra_get_state (ZebraHandle zh, char *val, int *seqno)
1317 char state_fname[256];
1322 yaz_log(LOG_API,"zebra_get_state ");
1324 sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1325 fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1326 f = fopen (fname, "r");
1332 fscanf (f, "%c %d", val, seqno);
1339 int zebra_begin_read (ZebraHandle zh)
1341 return zebra_begin_trans(zh, 0);
1344 int zebra_end_read (ZebraHandle zh)
1346 return zebra_end_trans(zh);
1349 static void read_res_for_transaction(ZebraHandle zh)
1351 const char *group = res_get(zh->res, "group");
1353 /* FIXME - do we still use groups ?? */
1355 zh->m_group = group;
1356 v = res_get_prefix(zh->res, "followLinks", group, "1");
1357 zh->m_follow_links = atoi(v);
1359 zh->m_record_id = res_get_prefix(zh->res, "recordId", group, 0);
1360 zh->m_record_type = res_get_prefix(zh->res, "recordType", group, 0);
1362 v = res_get_prefix(zh->res, "storeKeys", group, "1");
1363 zh->m_store_keys = atoi(v);
1365 v = res_get_prefix(zh->res, "storeData", group, "1");
1366 zh->m_store_data = atoi(v);
1368 v = res_get_prefix(zh->res, "explainDatabase", group, "0");
1369 zh->m_explain_database = atoi(v);
1371 v = res_get_prefix(zh->res, "openRW", group, "1");
1372 zh->m_flag_rw = atoi(v);
1374 v = res_get_prefix(zh->res, "fileVerboseLimit", group, "100000");
1375 zh->m_file_verbose_limit = atoi(v);
1378 int zebra_begin_trans (ZebraHandle zh, int rw)
1384 zh->errString = "zebra_begin_trans: no database selected";
1388 yaz_log(LOG_API,"zebra_begin_trans rw=%d",rw);
1392 if (rw && !strchr(zh->user_perm, 'w'))
1406 const char *rval = 0;
1411 read_res_for_transaction(zh);
1414 if (zh->trans_no != 1)
1417 zh->errString = "zebra_begin_trans: write trans not allowed within read trans";
1422 resultSetInvalidate (zh);
1423 zebra_register_close (zh->service, zh->reg);
1425 zh->trans_w_no = zh->trans_no;
1429 zh->records_inserted = 0;
1430 zh->records_updated = 0;
1431 zh->records_deleted = 0;
1432 zh->records_processed = 0;
1434 #if HAVE_SYS_TIMES_H
1438 if (zh->shadow_enable)
1439 rval = res_get (zh->res, "shadow");
1441 for (pass = 0; pass < 2; pass++)
1445 zebra_lock_r (zh->lock_normal);
1446 zebra_lock_w (zh->lock_shadow);
1450 zebra_lock_w (zh->lock_normal);
1451 zebra_lock_w (zh->lock_shadow);
1454 zebra_get_state (zh, &val, &seqno);
1457 yaz_log (LOG_WARN, "previous transaction didn't finish commit");
1458 zebra_unlock (zh->lock_shadow);
1459 zebra_unlock (zh->lock_normal);
1463 else if (val == 'd')
1467 BFiles bfs = bfs_create (res_get (zh->res, "shadow"),
1469 yaz_log (LOG_WARN, "previous transaction didn't reach commit");
1470 bf_commitClean (bfs, rval);
1475 yaz_log (LOG_WARN, "your previous transaction didn't finish");
1482 yaz_log (LOG_FATAL, "zebra_begin_trans couldn't finish commit");
1486 zebra_set_state (zh, 'd', seqno);
1488 zh->reg = zebra_register_open (zh->service, zh->reg_name,
1489 1, rval ? 1 : 0, zh->res,
1492 zh->reg->seqno = seqno;
1495 zebra_set_state (zh, 'o', seqno);
1497 zebra_unlock (zh->lock_shadow);
1498 zebra_unlock (zh->lock_normal);
1504 zh->errString = "zebra_begin_trans: cannot open register";
1505 yaz_log(LOG_FATAL, zh->errString);
1517 if (zh->trans_no != 1)
1519 zebra_flush_reg (zh);
1523 #if HAVE_SYS_TIMES_H
1532 if (!zh->lock_normal || !zh->lock_shadow)
1538 zebra_get_state (zh, &val, &seqno);
1544 else if (seqno != zh->reg->seqno)
1546 yaz_log (LOG_DEBUG, "reopen seqno cur/old %d/%d",
1547 seqno, zh->reg->seqno);
1550 else if (zh->reg->last_val != val)
1552 yaz_log (LOG_DEBUG, "reopen last cur/old %d/%d",
1553 val, zh->reg->last_val);
1560 zebra_lock_r (zh->lock_shadow);
1562 zebra_lock_r (zh->lock_normal);
1566 resultSetInvalidate (zh);
1567 zebra_register_close (zh->service, zh->reg);
1569 zh->reg = zebra_register_open (zh->service, zh->reg_name,
1570 0, val == 'c' ? 1 : 0,
1571 zh->res, zh->path_reg);
1574 zebra_unlock (zh->lock_normal);
1575 zebra_unlock (zh->lock_shadow);
1580 zh->reg->last_val = val;
1581 zh->reg->seqno = seqno;
1583 read_res_for_transaction(zh);
1587 int zebra_end_trans (ZebraHandle zh)
1589 ZebraTransactionStatus dummy;
1591 yaz_log(LOG_API,"zebra_end_trans");
1592 return zebra_end_transaction(zh, &dummy);
1595 int zebra_end_transaction (ZebraHandle zh, ZebraTransactionStatus *status)
1603 yaz_log(LOG_API,"zebra_end_transaction");
1605 status->processed = 0;
1606 status->inserted = 0;
1607 status->updated = 0;
1608 status->deleted = 0;
1612 if (!zh->res || !zh->reg)
1615 zh->errString = "zebra_end_trans: no open transaction";
1618 if (zh->trans_no != zh->trans_w_no)
1621 if (zh->trans_no != 0)
1624 /* release read lock */
1626 zebra_unlock (zh->lock_normal);
1627 zebra_unlock (zh->lock_shadow);
1630 { /* release write lock */
1634 yaz_log (LOG_DEBUG, "zebra_end_trans");
1635 rval = res_get (zh->res, "shadow");
1637 zebraExplain_runNumberIncrement (zh->reg->zei, 1);
1639 zebra_flush_reg (zh);
1641 resultSetInvalidate (zh);
1643 zebra_register_close (zh->service, zh->reg);
1646 yaz_log (LOG_LOG, "Records: "ZINT_FORMAT" i/u/d "
1647 ZINT_FORMAT"/"ZINT_FORMAT"/"ZINT_FORMAT,
1648 zh->records_processed, zh->records_inserted,
1649 zh->records_updated, zh->records_deleted);
1651 status->processed = zh->records_processed;
1652 status->inserted = zh->records_inserted;
1653 status->updated = zh->records_updated;
1654 status->deleted = zh->records_deleted;
1656 zebra_get_state (zh, &val, &seqno);
1659 BFiles bfs = bfs_create (rval, zh->path_reg);
1660 yaz_log (LOG_DEBUG, "deleting shadow val=%c", val);
1661 bf_commitClean (bfs, rval);
1666 zebra_set_state (zh, 'o', seqno);
1668 zebra_unlock (zh->lock_shadow);
1669 zebra_unlock (zh->lock_normal);
1672 #if HAVE_SYS_TIMES_H
1674 logf (LOG_LOG, "user/system: %ld/%ld",
1675 (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1676 (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1678 status->utime = (long) (zh->tms2.tms_utime - zh->tms1.tms_utime);
1679 status->stime = (long) (zh->tms2.tms_stime - zh->tms1.tms_stime);
1684 int zebra_repository_update (ZebraHandle zh, const char *path)
1689 logf (LOG_API, "updating %s", path);
1690 repositoryUpdate (zh, path);
1694 int zebra_repository_delete (ZebraHandle zh, const char *path)
1699 logf (LOG_API, "deleting %s", path);
1700 repositoryDelete (zh, path);
1704 int zebra_repository_show (ZebraHandle zh, const char *path)
1708 yaz_log(LOG_API,"zebra_repository_show");
1710 repositoryShow (zh, path);
1714 static int zebra_commit_ex (ZebraHandle zh, int clean_only)
1728 rval = res_get (zh->res, "shadow");
1731 logf (LOG_WARN, "Cannot perform commit");
1732 logf (LOG_WARN, "No shadow area defined");
1736 zebra_lock_w (zh->lock_normal);
1737 zebra_lock_r (zh->lock_shadow);
1739 bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1741 zebra_get_state (zh, &val, &seqno);
1744 bf_cache (bfs, rval);
1745 if (bf_commitExists (bfs))
1748 zebra_set_state (zh, 'd', seqno);
1751 zebra_set_state (zh, 'c', seqno);
1753 logf (LOG_DEBUG, "commit start");
1754 bf_commitExec (bfs);
1759 logf (LOG_DEBUG, "commit clean");
1760 bf_commitClean (bfs, rval);
1762 zebra_set_state (zh, 'o', seqno);
1766 logf (LOG_LOG, "nothing to commit");
1770 zebra_unlock (zh->lock_shadow);
1771 zebra_unlock (zh->lock_normal);
1775 int zebra_clean (ZebraHandle zh)
1778 yaz_log(LOG_API,"zebra_clean");
1779 return zebra_commit_ex(zh, 1);
1782 int zebra_commit (ZebraHandle zh)
1785 yaz_log(LOG_API,"zebra_commit");
1786 return zebra_commit_ex(zh, 0);
1789 int zebra_init (ZebraHandle zh)
1794 yaz_log(LOG_API,"zebra_init");
1802 rval = res_get (zh->res, "shadow");
1804 bfs = bfs_create (res_get (zh->service->global_res, "register"),
1809 bf_cache (bfs, rval);
1813 zebra_set_state (zh, 'o', 0);
1817 int zebra_compact (ZebraHandle zh)
1821 yaz_log(LOG_API,"zebra_compact");
1828 bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1834 int zebra_result (ZebraHandle zh, int *code, char **addinfo)
1837 yaz_log(LOG_API,"zebra_result");
1838 *code = zh->errCode;
1839 *addinfo = zh->errString;
1843 int zebra_shadow_enable (ZebraHandle zh, int value)
1846 yaz_log(LOG_API,"zebra_shadow_enable");
1848 zh->shadow_enable = value;
1852 int zebra_record_encoding (ZebraHandle zh, const char *encoding)
1856 yaz_log(LOG_API,"zebra_record_encoding");
1858 xfree (zh->record_encoding);
1862 * Something about charset aliases. Oleg???
1865 if (zh->iconv_to_utf8 != 0)
1866 yaz_iconv_close(zh->iconv_to_utf8);
1867 if (zh->iconv_from_utf8 != 0)
1868 yaz_iconv_close(zh->iconv_from_utf8);
1870 zh->record_encoding = xstrdup (encoding);
1872 logf(LOG_DEBUG, "Reset record encoding: %s", encoding);
1875 yaz_iconv_open ("UTF-8", encoding);
1876 if (zh->iconv_to_utf8 == 0)
1877 yaz_log (LOG_WARN, "iconv: %s to UTF-8 unsupported", encoding);
1878 zh->iconv_from_utf8 =
1879 yaz_iconv_open (encoding, "UTF-8");
1880 if (zh->iconv_to_utf8 == 0)
1881 yaz_log (LOG_WARN, "iconv: UTF-8 to %s unsupported", encoding);
1886 int zebra_set_resource(ZebraHandle zh, const char *name, const char *value)
1891 yaz_log(LOG_API,"zebra_set_resource %s:%s",name,value);
1893 res_set(zh->res, name, value);
1897 const char *zebra_get_resource(ZebraHandle zh,
1898 const char *name, const char *defaultvalue)
1903 assert(defaultvalue);
1904 v= res_get_def( zh->res, name, (char *)defaultvalue);
1906 yaz_log(LOG_API,"zebra_get_resource %s:%s",name,v);
1910 /* moved from zebra_api_ext.c by pop */
1911 /* FIXME: Should this really be public??? -Heikki */
1913 int zebra_trans_no (ZebraHandle zh)
1916 yaz_log(LOG_API,"zebra_trans_no");
1917 return zh->trans_no;
1920 int zebra_get_shadow_enable (ZebraHandle zh)
1923 yaz_log(LOG_API,"zebra_get_shadow_enable");
1924 return (zh->shadow_enable);
1927 int zebra_set_shadow_enable (ZebraHandle zh, int value)
1930 yaz_log(LOG_API,"zebra_set_shadow_enable %d",value);
1931 zh->shadow_enable = value;
1935 /* almost the same as zebra_records_retrieve ... but how did it work?
1936 I mean for multiple records ??? CHECK ??? */
1937 void api_records_retrieve (ZebraHandle zh, ODR stream,
1938 const char *setname, Z_RecordComposition *comp,
1939 oid_value input_format, int num_recs,
1940 ZebraRetrievalRecord *recs)
1950 yaz_log(LOG_API,"api_records_retrieve s=%s n=%d",setname,num_recs);
1955 zh->errString = odr_strdup (stream, setname);
1961 if (zebra_begin_read (zh))
1964 pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
1965 for (i = 0; i<num_recs; i++)
1966 pos_array[i] = recs[i].position;
1967 poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
1970 logf (LOG_DEBUG, "zebraPosSetCreate error");
1972 zh->errString = nmem_strdup (stream->mem, setname);
1976 for (i = 0; i<num_recs; i++)
1980 recs[i].errCode = 0;
1981 recs[i].format = VAL_SUTRS;
1982 recs[i].len = strlen(poset[i].term);
1983 recs[i].buf = poset[i].term;
1984 recs[i].base = poset[i].db;
1988 else if (poset[i].sysno)
1990 /* changed here ??? CHECK ??? */
1993 zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
1994 stream, input_format, comp,
1999 recs[i].buf = (char *) odr_malloc(stream,recs[i].len);
2000 memcpy(recs[i].buf, b, recs[i].len);
2001 recs[i].errString = 0; /* Hmmm !!! we should get this */
2002 recs[i].sysno = poset[i].sysno;
2003 recs[i].score = poset[i].score;
2009 sprintf (num_str, "%d", pos_array[i]);
2011 zh->errString = odr_strdup (stream, num_str);
2016 zebraPosSetDestroy (zh, poset, num_recs);
2018 zebra_end_read (zh);
2023 /* ---------------------------------------------------------------------------
2024 Record insert(=update), delete
2026 If sysno is provided, then it's used to identify the record.
2027 If not, and match_criteria is provided, then sysno is guessed
2028 If not, and a record is provided, then sysno is got from there
2029 NOTE: Now returns 0 at success and updates sysno, which is an int*
2033 int zebra_add_record(ZebraHandle zh,
2034 const char *buf, int buf_size)
2037 return zebra_update_record(zh, 0, &sysno, 0, 0, buf, buf_size, 0);
2040 int zebra_insert_record (ZebraHandle zh,
2041 const char *recordType,
2042 SYSNO *sysno, const char *match, const char *fname,
2043 const char *buf, int buf_size, int force_update)
2049 yaz_log(LOG_API, "zebra_insert_record sysno=" ZINT_FORMAT, *sysno);
2051 if (buf_size < 1) buf_size = strlen(buf);
2053 if (zebra_begin_trans(zh, 1))
2055 res = buffer_extract_record (zh, buf, buf_size,
2056 0, /* delete_flag */
2062 0); /* allow_update */
2063 zebra_end_trans(zh);
2067 int zebra_update_record (ZebraHandle zh,
2068 const char *recordType,
2069 SYSNO* sysno, const char *match, const char *fname,
2070 const char *buf, int buf_size,
2078 yaz_log(LOG_API, "zebra_update_record sysno=" ZINT_FORMAT, *sysno);
2080 if (buf_size < 1) buf_size = strlen(buf);
2082 if (zebra_begin_trans(zh, 1))
2084 res = buffer_extract_record (zh, buf, buf_size,
2085 0, /* delete_flag */
2091 1); /* allow_update */
2092 zebra_end_trans(zh);
2096 int zebra_delete_record (ZebraHandle zh,
2097 const char *recordType,
2098 SYSNO *sysno, const char *match, const char *fname,
2099 const char *buf, int buf_size,
2106 yaz_log(LOG_API, "zebra_delete_record sysno=" ZINT_FORMAT, *sysno);
2108 if (buf_size < 1) buf_size = strlen(buf);
2110 if (zebra_begin_trans(zh, 1))
2112 res = buffer_extract_record (zh, buf, buf_size,
2113 1, /* delete_flag */
2119 1); /* allow_update */
2120 zebra_end_trans(zh);
2124 /* ---------------------------------------------------------------------------
2128 int zebra_search_PQF (ZebraHandle zh, const char *pqf_query,
2129 const char *setname, int *numhits)
2134 ODR odr = odr_createmem(ODR_ENCODE);
2139 yaz_log(LOG_API,"zebra_search_PQF s=%s q=%s",setname, pqf_query);
2141 query = p_query_rpn (odr, PROTO_Z3950, pqf_query);
2144 yaz_log (LOG_WARN, "bad query %s\n", pqf_query);
2146 res=zebra_search_RPN (zh, odr, query, setname, &hits);
2150 yaz_log(LOG_API,"Hits: %d",hits);
2158 /* ---------------------------------------------------------------------------
2159 Sort - a simplified interface, with optional read locks.
2161 int zebra_sort_by_specstr (ZebraHandle zh,
2163 const char *sort_spec,
2164 const char *output_setname,
2165 const char **input_setnames)
2167 int num_input_setnames = 0;
2168 int sort_status = 0;
2169 Z_SortKeySpecList *sort_sequence;
2173 assert(output_setname);
2174 assert(input_setnames);
2175 sort_sequence = yaz_sort_spec (stream, sort_spec);
2176 yaz_log(LOG_API,"sort (FIXME) ");
2179 logf(LOG_WARN,"invalid sort specs '%s'", sort_spec);
2184 /* we can do this, since the perl typemap code for char** will
2185 put a NULL at the end of list */
2186 while (input_setnames[num_input_setnames]) num_input_setnames++;
2188 if (zebra_begin_read (zh))
2191 resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
2192 output_setname, sort_sequence, &sort_status);