1 /* $Id: zebraapi.c,v 1.131 2004-09-13 09:02:16 adam 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;
91 yaz_log(LOG_API,"zebra_open");
96 zh = (ZebraHandle) xmalloc (sizeof(*zh));
97 yaz_log (LOG_DEBUG, "zebra_open zs=%p returns %p", zs, zh);
100 zh->reg = 0; /* no register attached yet */
108 zh->reg_name = xstrdup ("");
110 zh->num_basenames = 0;
119 zh->shadow_enable = 1;
121 default_encoding = res_get_def(zs->global_res, "encoding", "ISO-8859-1");
122 zh->record_encoding = xstrdup (default_encoding);
125 yaz_iconv_open ("UTF-8", default_encoding);
126 if (zh->iconv_to_utf8 == 0)
127 yaz_log (LOG_WARN, "iconv: %s to UTF-8 unsupported",
129 zh->iconv_from_utf8 =
130 yaz_iconv_open (default_encoding, "UTF-8");
131 if (zh->iconv_to_utf8 == 0)
132 yaz_log (LOG_WARN, "iconv: UTF-8 to %s unsupported",
135 zebra_mutex_cond_lock (&zs->session_lock);
137 zh->next = zs->sessions;
140 zebra_mutex_cond_unlock (&zs->session_lock);
145 ZebraService zebra_start (const char *configName)
147 return zebra_start_res(configName, 0, 0);
150 ZebraService zebra_start_res (const char *configName, Res def_res, Res over_res)
154 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");
187 void zebra_pidfname(ZebraService zs, char *path)
189 zebra_lock_prefix (zs->global_res, path);
190 strcat(path, "zebrasrv.pid");
193 Dict dict_open_res (BFiles bfs, const char *name, int cache, int rw,
194 int compact_flag, Res res)
196 int page_size = 4096;
197 char resource_str[200];
199 sprintf (resource_str, "dict.%.100s.pagesize", name);
201 v = res_get(res, resource_str);
205 yaz_log(LOG_LOG, "Using custom dictionary page size %d for %s",
208 return dict_open(bfs, name, cache, rw, compact_flag, page_size);
213 struct zebra_register *zebra_register_open (ZebraService zs, const char *name,
214 int rw, int useshadow, Res res,
215 const char *reg_path)
217 struct zebra_register *reg;
218 int record_compression = REC_COMPRESS_NONE;
219 const char *recordCompression = 0;
220 const char *profilePath;
225 reg = xmalloc (sizeof(*reg));
228 reg->name = xstrdup (name);
235 yaz_log (LOG_DEBUG, "zebra_register_open rw=%d useshadow=%d p=%p n=%s rp=%s",
236 rw, useshadow, reg, name, reg_path ? reg_path : "(none)");
238 reg->dh = data1_createx (DATA1_FLAG_XML);
241 reg->bfs = bfs_create (res_get (res, "register"), reg_path);
244 data1_destroy(reg->dh);
248 bf_cache (reg->bfs, res_get (res, "shadow"));
250 getcwd(cwd, sizeof(cwd)-1);
251 profilePath = res_get_def(res, "profilePath", DEFAULT_PROFILE_PATH);
252 yaz_log(LOG_DEBUG, "profilePath=%s cwd=%s", profilePath, cwd);
254 data1_set_tabpath (reg->dh, profilePath);
255 data1_set_tabroot (reg->dh, reg_path);
256 reg->recTypes = recTypes_init (reg->dh);
257 recTypes_default_handlers (reg->recTypes);
259 reg->zebra_maps = zebra_maps_open (res, reg_path);
260 reg->rank_classes = NULL;
264 reg->keys.buf_max = 0;
267 reg->keys.codec_handle = iscz1_start();
270 reg->sortKeys.buf = 0;
271 reg->sortKeys.buf_max = 0;
282 reg->key_file_no = 0;
285 zebraRankInstall (reg, rank1_class);
286 zebraRankInstall (reg, rankzv_class);
287 zebraRankInstall (reg, rankliv_class);
289 recordCompression = res_get_def (res, "recordCompression", "none");
290 if (!strcmp (recordCompression, "none"))
291 record_compression = REC_COMPRESS_NONE;
292 if (!strcmp (recordCompression, "bzip2"))
293 record_compression = REC_COMPRESS_BZIP2;
295 if (!(reg->records = rec_open (reg->bfs, rw, record_compression)))
297 logf (LOG_WARN, "rec_open");
302 reg->matchDict = dict_open_res (reg->bfs, GMATCH_DICT, 20, 1, 0, res);
304 if (!(reg->dict = dict_open_res (reg->bfs, FNAME_DICT, 40, rw, 0, res)))
306 logf (LOG_WARN, "dict_open");
309 if (!(reg->sortIdx = sortIdx_open (reg->bfs, rw)))
311 logf (LOG_WARN, "sortIdx_open");
314 if (res_get_match (res, "isam", "s", ISAM_DEFAULT))
316 struct ISAMS_M_s isams_m;
317 if (!(reg->isams = isams_open (reg->bfs, FNAME_ISAMS, rw,
318 key_isams_m(res, &isams_m))))
320 logf (LOG_WARN, "isams_open");
324 if (res_get_match (res, "isam", "c", ISAM_DEFAULT))
326 struct ISAMC_M_s isamc_m;
327 if (!(reg->isamc = isc_open (reg->bfs, FNAME_ISAMC,
328 rw, key_isamc_m(res, &isamc_m))))
330 logf (LOG_WARN, "isc_open");
334 if (res_get_match (res, "isam", "b", ISAM_DEFAULT))
336 struct ISAMC_M_s isamc_m;
338 if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
339 rw, key_isamc_m(res, &isamc_m), 0)))
341 logf (LOG_WARN, "isamb_open");
345 if (res_get_match (res, "isam", "bc", 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), 1)))
352 logf (LOG_WARN, "isamb_open");
356 if (res_get_match (res, "isam", "null", 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 reg->zei = zebraExplain_open (reg->records, reg->dh,
372 logf (LOG_WARN, "Cannot obtain EXPLAIN information");
376 yaz_log (LOG_DEBUG, "zebra_register_open ok p=%p", reg);
380 int zebra_admin_shutdown (ZebraHandle zh)
383 yaz_log(LOG_API,"zebra_admin_shutdown");
386 zebra_mutex_cond_lock (&zh->service->session_lock);
387 zh->service->stop_flag = 1;
388 zebra_mutex_cond_unlock (&zh->service->session_lock);
392 int zebra_admin_start (ZebraHandle zh)
396 yaz_log(LOG_API,"zebra_admin_start");
399 zebra_mutex_cond_lock (&zs->session_lock);
400 zebra_mutex_cond_unlock (&zs->session_lock);
404 static void zebra_register_close (ZebraService zs, struct zebra_register *reg)
407 yaz_log(LOG_DEBUG, "zebra_register_close p=%p", reg);
412 zebraExplain_close (reg->zei);
413 dict_close (reg->dict);
415 dict_close (reg->matchDict);
416 sortIdx_close (reg->sortIdx);
418 isams_close (reg->isams);
420 isc_close (reg->isamc);
422 isamb_close (reg->isamb);
423 rec_close (®->records);
426 recTypes_destroy (reg->recTypes);
427 zebra_maps_close (reg->zebra_maps);
428 zebraRankDestroy (reg);
429 bfs_destroy (reg->bfs);
430 data1_destroy (reg->dh);
432 xfree (reg->sortKeys.buf);
433 xfree (reg->keys.buf);
435 if (reg->keys.codec_handle)
436 iscz1_stop(reg->keys.codec_handle);
439 xfree (reg->key_buf);
444 int zebra_stop(ZebraService zs)
448 yaz_log (LOG_API, "zebra_stop");
452 zebra_close (zs->sessions);
455 zebra_mutex_cond_destroy (&zs->session_lock);
458 passwd_db_close (zs->passwd_db);
460 res_close (zs->global_res);
461 xfree (zs->configName);
466 int zebra_close (ZebraHandle zh)
469 struct zebra_session **sp;
472 yaz_log(LOG_API,"zebra_close");
479 yaz_log (LOG_DEBUG, "zebra_close zh=%p", zh);
480 resultSetDestroy (zh, -1, 0, 0);
483 zebra_register_close (zh->service, zh->reg);
484 zebra_close_res (zh);
486 xfree (zh->record_encoding);
488 for (i = 0; i < zh->num_basenames; i++)
489 xfree (zh->basenames[i]);
490 xfree (zh->basenames);
492 if (zh->iconv_to_utf8 != 0)
493 yaz_iconv_close (zh->iconv_to_utf8);
494 if (zh->iconv_from_utf8 != 0)
495 yaz_iconv_close (zh->iconv_from_utf8);
497 zebra_mutex_cond_lock (&zs->session_lock);
498 zebra_lock_destroy (zh->lock_normal);
499 zebra_lock_destroy (zh->lock_shadow);
511 zebra_mutex_cond_unlock (&zs->session_lock);
512 xfree (zh->reg_name);
513 xfree (zh->user_perm);
514 zh->service=0; /* more likely to trigger an assert */
515 xfree (zh->path_reg);
520 struct map_baseinfo {
526 char **new_basenames;
530 static Res zebra_open_res (ZebraHandle zh)
539 sprintf (fname, "%.200s/zebra.cfg", zh->path_reg);
540 res = res_open (fname, zh->service->global_res, 0);
542 res = zh->service->global_res;
544 else if (*zh->reg_name == 0)
546 res = zh->service->global_res;
550 yaz_log (LOG_WARN, "no register root specified");
551 return 0; /* no path for register - fail! */
556 static void zebra_close_res (ZebraHandle zh)
560 if (zh->res != zh->service->global_res)
565 static int zebra_select_register (ZebraHandle zh, const char *new_reg)
569 if (zh->res && strcmp (zh->reg_name, new_reg) == 0)
573 assert (zh->reg == 0);
574 assert (*zh->reg_name == 0);
580 resultSetInvalidate (zh);
581 zebra_register_close (zh->service, zh->reg);
586 xfree (zh->reg_name);
587 zh->reg_name = xstrdup (new_reg);
589 xfree (zh->path_reg);
591 if (zh->service->path_root)
593 zh->path_reg = xmalloc (strlen(zh->service->path_root) +
594 strlen(zh->reg_name) + 3);
595 strcpy (zh->path_reg, zh->service->path_root);
598 strcat (zh->path_reg, "/");
599 strcat (zh->path_reg, zh->reg_name);
602 zh->res = zebra_open_res (zh);
605 zebra_lock_destroy (zh->lock_normal);
609 zebra_lock_destroy (zh->lock_shadow);
615 const char *lock_area =res_get (zh->res, "lockDir");
617 if (!lock_area && zh->path_reg)
618 res_set (zh->res, "lockDir", zh->path_reg);
619 sprintf (fname, "norm.%s.LCK", zh->reg_name);
621 zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
623 sprintf (fname, "shadow.%s.LCK", zh->reg_name);
625 zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
631 void map_basenames_func (void *vp, const char *name, const char *value)
633 struct map_baseinfo *p = (struct map_baseinfo *) vp;
635 char fromdb[128], todb[8][128];
638 sscanf (value, "%127s %127s %127s %127s %127s %127s %127s %127s %127s",
639 fromdb, todb[0], todb[1], todb[2], todb[3], todb[4],
640 todb[5], todb[6], todb[7]);
644 for (i = 0; i<p->num_bases; i++)
645 if (p->basenames[i] && !STRCASECMP (p->basenames[i], fromdb))
648 for (i = 0; i < no; i++)
650 if (p->new_num_bases == p->new_num_max)
652 p->new_basenames[(p->new_num_bases)++] =
653 nmem_strdup (p->mem, todb[i]);
659 void map_basenames (ZebraHandle zh, ODR stream,
660 int *num_bases, char ***basenames)
662 struct map_baseinfo info;
663 struct map_baseinfo *p = &info;
666 yaz_log(LOG_API,"map_basenames ");
670 info.num_bases = *num_bases;
671 info.basenames = *basenames;
672 info.new_num_max = 128;
673 info.new_num_bases = 0;
674 info.new_basenames = (char **)
675 odr_malloc (stream, sizeof(*info.new_basenames) * info.new_num_max);
676 info.mem = stream->mem;
678 res_trav (zh->service->global_res, "mapdb", &info, map_basenames_func);
680 for (i = 0; i<p->num_bases; i++)
681 if (p->basenames[i] && p->new_num_bases < p->new_num_max)
683 p->new_basenames[(p->new_num_bases)++] =
684 nmem_strdup (p->mem, p->basenames[i]);
686 *num_bases = info.new_num_bases;
687 *basenames = info.new_basenames;
688 for (i = 0; i<*num_bases; i++)
689 logf (LOG_DEBUG, "base %s", (*basenames)[i]);
692 int zebra_select_database (ZebraHandle zh, const char *basename)
695 yaz_log(LOG_API,"zebra_select_database %s",basename);
697 return zebra_select_databases (zh, 1, &basename);
700 int zebra_select_databases (ZebraHandle zh, int num_bases,
701 const char **basenames)
708 yaz_log(LOG_API,"zebra_select_databases n=%d [0]=%s",
709 num_bases,basenames[0]);
717 for (i = 0; i < zh->num_basenames; i++)
718 xfree (zh->basenames[i]);
719 xfree (zh->basenames);
721 zh->num_basenames = num_bases;
722 zh->basenames = xmalloc (zh->num_basenames * sizeof(*zh->basenames));
723 for (i = 0; i < zh->num_basenames; i++)
724 zh->basenames[i] = xstrdup (basenames[i]);
726 cp = strrchr(basenames[0], '/');
729 len = cp - basenames[0];
730 new_reg = xmalloc (len + 1);
731 memcpy (new_reg, basenames[0], len);
735 new_reg = xstrdup ("");
736 for (i = 1; i<num_bases; i++)
740 cp1 = strrchr (basenames[i], '/');
748 if (len != cp1 - basenames[i] ||
749 memcmp (basenames[i], new_reg, len))
764 zebra_select_register (zh, new_reg);
771 if (!zh->lock_normal || !zh->lock_shadow)
779 int zebra_search_RPN (ZebraHandle zh, ODR o,
780 Z_RPNQuery *query, const char *setname, int *hits)
785 yaz_log(LOG_API,"zebra_search_rpn");
790 if (zebra_begin_read (zh))
793 zebra_livcode_transform(zh, query);
795 resultSetAddRPN (zh, odr_extract_mem(o), query,
796 zh->num_basenames, zh->basenames, setname);
799 max = res_get (zh->res, "maxhits");
805 while (maxhits>100) { maxhits/=10; i++;}
806 while (i--) maxhits *= 10;
808 if (zh->hits > maxhits) { /* too large for yaz to handle */
809 logf(LOG_DEBUG,"limiting hits to "ZINT_FORMAT, maxhits);
810 *hits=maxhits; /* round it down to two digits, to look like rounded */
817 int zebra_records_retrieve (ZebraHandle zh, ODR stream,
818 const char *setname, Z_RecordComposition *comp,
819 oid_value input_format, int num_recs,
820 ZebraRetrievalRecord *recs)
823 int i, *pos_array, ret = 0;
825 yaz_log(LOG_API,"zebra_records_retrieve n=%d",num_recs);
831 zh->errString = odr_strdup (stream, setname);
837 if (zebra_begin_read (zh))
840 pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
841 for (i = 0; i<num_recs; i++)
842 pos_array[i] = recs[i].position;
843 poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
846 logf (LOG_DEBUG, "zebraPosSetCreate error");
848 zh->errString = nmem_strdup (stream->mem, setname);
853 for (i = 0; i<num_recs; i++)
858 recs[i].format = VAL_SUTRS;
859 recs[i].len = strlen(poset[i].term);
860 recs[i].buf = poset[i].term;
861 recs[i].base = poset[i].db;
863 else if (poset[i].sysno)
866 zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
867 stream, input_format, comp,
868 &recs[i].format, &recs[i].buf,
871 recs[i].errString = NULL;
877 sprintf (num_str, "%d", pos_array[i]);
879 zh->errString = odr_strdup (stream, num_str);
884 zebraPosSetDestroy (zh, poset, num_recs);
891 int zebra_scan (ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
892 oid_value attributeset,
893 int *position, int *num_entries, ZebraScanEntry **entries,
897 yaz_log(LOG_API,"zebra_scan");
899 if (zebra_begin_read (zh))
905 rpn_scan (zh, stream, zapt, attributeset,
906 zh->num_basenames, zh->basenames, position,
907 num_entries, entries, is_partial, 0, 0);
912 int zebra_sort (ZebraHandle zh, ODR stream,
913 int num_input_setnames, const char **input_setnames,
914 const char *output_setname, Z_SortKeySpecList *sort_sequence,
918 yaz_log(LOG_API,"zebra_sort");
920 if (zebra_begin_read (zh))
922 resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
923 output_setname, sort_sequence, sort_status);
928 int zebra_deleleResultSet(ZebraHandle zh, int function,
929 int num_setnames, char **setnames,
934 yaz_log(LOG_API,"zebra_deleleResultSet n=%d",num_setnames);
936 if (zebra_begin_read(zh))
937 return Z_DeleteStatus_systemProblemAtTarget;
940 case Z_DeleteResultSetRequest_list:
941 resultSetDestroy (zh, num_setnames, setnames, statuses);
943 case Z_DeleteResultSetRequest_all:
944 resultSetDestroy (zh, -1, 0, statuses);
948 status = Z_DeleteStatus_success;
949 for (i = 0; i<num_setnames; i++)
950 if (statuses[i] == Z_DeleteStatus_resultSetDidNotExist)
951 status = statuses[i];
955 int zebra_errCode (ZebraHandle zh)
959 yaz_log(LOG_API,"zebra_errCode: %d",zh->errCode);
962 yaz_log(LOG_API,"zebra_errCode: o");
966 const char *zebra_errString (ZebraHandle zh)
970 e= diagbib1_str (zh->errCode);
971 yaz_log(LOG_API,"zebra_errString: %s",e);
975 char *zebra_errAdd (ZebraHandle zh)
980 yaz_log(LOG_API,"zebra_errAdd: %s",a);
984 void zebra_clearError(ZebraHandle zh)
993 int zebra_auth (ZebraHandle zh, const char *user, const char *pass)
1003 sprintf(u, "perm.%.30s", user ? user : "anonymous");
1004 p = res_get(zs->global_res, u);
1005 xfree (zh->user_perm);
1006 zh->user_perm = xstrdup(p ? p : "r");
1008 /* users that don't require a password .. */
1009 if (zh->user_perm && strchr(zh->user_perm, 'a'))
1012 if (!zs->passwd_db || !passwd_db_auth (zs->passwd_db, user, pass))
1017 int zebra_admin_import_begin (ZebraHandle zh, const char *database,
1018 const char *record_type)
1021 yaz_log(LOG_API,"zebra_admin_import_begin db=%s rt=%s",
1022 database, record_type);
1024 if (zebra_select_database(zh, database))
1026 if (zebra_begin_trans (zh, 1))
1031 int zebra_admin_import_end (ZebraHandle zh)
1034 yaz_log(LOG_API,"zebra_admin_import_end");
1036 zebra_end_trans (zh);
1040 int zebra_admin_import_segment (ZebraHandle zh, Z_Segment *segment)
1045 yaz_log(LOG_API,"zebra_admin_import_segment");
1047 for (i = 0; i<segment->num_segmentRecords; i++)
1049 Z_NamePlusRecord *npr = segment->segmentRecords[i];
1051 printf ("--------------%d--------------------\n", i);
1052 if (npr->which == Z_NamePlusRecord_intermediateFragment)
1054 Z_FragmentSyntax *fragment = npr->u.intermediateFragment;
1055 if (fragment->which == Z_FragmentSyntax_notExternallyTagged)
1057 Odr_oct *oct = fragment->u.notExternallyTagged;
1058 printf ("%.*s", (oct->len > 100 ? 100 : oct->len) ,
1063 zebra_update_record(zh,
1064 0, /* record Type */
1076 int zebra_admin_exchange_record (ZebraHandle zh,
1077 const char *rec_buf,
1079 const char *recid_buf, size_t recid_len,
1081 /* 1 = insert. Fail it already exists */
1082 /* 2 = replace. Fail it does not exist */
1083 /* 3 = delete. Fail if does not exist */
1084 /* 4 = update. Insert/replace */
1090 yaz_log(LOG_API,"zebra_admin_exchange_record ac=%d", action);
1093 if (!recid_buf || recid_len <= 0 || recid_len >= sizeof(recid_z))
1095 memcpy (recid_z, recid_buf, recid_len);
1096 recid_z[recid_len] = 0;
1098 if (zebra_begin_trans(zh, 1))
1101 rinfo = dict_lookup (zh->reg->matchDict, recid_z);
1104 if (action == 1) /* fail if insert */
1106 zebra_end_trans(zh);
1110 memcpy (&sysno, rinfo+1, sizeof(sysno));
1114 if (action == 2 || action == 3) /* fail if delete or update */
1116 zebra_end_trans(zh);
1119 action = 1; /* make it an insert (if it's an update).. */
1121 buffer_extract_record (zh, rec_buf, rec_len,
1122 action == 3 ? 1 : 0 /* delete flag */,
1128 0, /* force update */
1129 1 /* allow update */
1133 dict_insert (zh->reg->matchDict, recid_z, sizeof(sysno), &sysno);
1135 else if (action == 3)
1137 dict_delete (zh->reg->matchDict, recid_z);
1139 zebra_end_trans(zh);
1143 int delete_w_handle(const char *info, void *handle)
1145 ZebraHandle zh = (ZebraHandle) handle;
1148 if (*info == sizeof(pos))
1150 memcpy (&pos, info+1, sizeof(pos));
1151 isamb_unlink(zh->reg->isamb, pos);
1156 static int delete_SU_handle(void *handle, int ord)
1158 ZebraHandle zh = (ZebraHandle) handle;
1162 ord_len = key_SU_encode (ord, ord_buf);
1163 ord_buf[ord_len] = '\0';
1165 assert (zh->reg->isamb);
1166 dict_delete_subtree(zh->reg->dict, ord_buf,
1167 zh, delete_w_handle);
1171 int zebra_drop_database (ZebraHandle zh, const char *database)
1175 yaz_log(LOG_API,"zebra_drop_database");
1178 if (zebra_select_database (zh, database))
1180 if (zebra_begin_trans (zh, 1))
1184 zebraExplain_curDatabase (zh->reg->zei, database);
1186 zebraExplain_trav_ord(zh->reg->zei, zh, delete_SU_handle);
1187 zebraExplain_removeDatabase(zh->reg->zei, zh);
1191 yaz_log(LOG_WARN, "drop database only supported for isam:b");
1194 zebra_end_trans (zh);
1198 int zebra_create_database (ZebraHandle zh, const char *database)
1201 yaz_log(LOG_API,"zebra_create_database");
1204 if (zebra_select_database (zh, database))
1206 if (zebra_begin_trans (zh, 1))
1209 /* announce database */
1210 if (zebraExplain_newDatabase (zh->reg->zei, database, 0
1211 /* explainDatabase */))
1213 zebra_end_trans (zh);
1215 zh->errString = "database already exist";
1218 zebra_end_trans (zh);
1222 int zebra_string_norm (ZebraHandle zh, unsigned reg_id,
1223 const char *input_str, int input_len,
1224 char *output_str, int output_len)
1228 yaz_log(LOG_API,"zebra_string_norm ");
1230 if (!zh->reg->zebra_maps)
1232 wrbuf = zebra_replace(zh->reg->zebra_maps, reg_id, "",
1233 input_str, input_len);
1236 if (wrbuf_len(wrbuf) >= output_len)
1238 if (wrbuf_len(wrbuf))
1239 memcpy (output_str, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
1240 output_str[wrbuf_len(wrbuf)] = '\0';
1241 return wrbuf_len(wrbuf);
1245 int zebra_set_state (ZebraHandle zh, int val, int seqno)
1247 char state_fname[256];
1252 yaz_log(LOG_API,"zebra_set_state v=%d seq=%d", val, seqno);
1255 sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1256 fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1257 f = fopen (fname, "w");
1259 yaz_log (LOG_DEBUG, "%c %d %ld", val, seqno, p);
1260 fprintf (f, "%c %d %ld\n", val, seqno, p);
1266 int zebra_get_state (ZebraHandle zh, char *val, int *seqno)
1268 char state_fname[256];
1273 yaz_log(LOG_API,"zebra_get_state ");
1275 sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1276 fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1277 f = fopen (fname, "r");
1283 fscanf (f, "%c %d", val, seqno);
1290 int zebra_begin_read (ZebraHandle zh)
1292 return zebra_begin_trans(zh, 0);
1295 int zebra_end_read (ZebraHandle zh)
1297 return zebra_end_trans(zh);
1300 static void read_res_for_transaction(ZebraHandle zh)
1302 const char *group = res_get(zh->res, "group");
1305 zh->m_group = group;
1306 v = res_get_prefix(zh->res, "followLinks", group, "1");
1307 zh->m_follow_links = atoi(v);
1309 zh->m_record_id = res_get_prefix(zh->res, "recordId", group, 0);
1310 zh->m_record_type = res_get_prefix(zh->res, "recordType", group, 0);
1312 v = res_get_prefix(zh->res, "storeKeys", group, "1");
1313 zh->m_store_keys = atoi(v);
1315 v = res_get_prefix(zh->res, "storeData", group, "1");
1316 zh->m_store_data = atoi(v);
1318 v = res_get_prefix(zh->res, "explainDatabase", group, "0");
1319 zh->m_explain_database = atoi(v);
1321 v = res_get_prefix(zh->res, "openRW", group, "1");
1322 zh->m_flag_rw = atoi(v);
1324 v = res_get_prefix(zh->res, "fileVerboseLimit", group, "100000");
1325 zh->m_file_verbose_limit = atoi(v);
1328 int zebra_begin_trans (ZebraHandle zh, int rw)
1333 zh->errString = "zebra_begin_trans: no database selected";
1337 yaz_log(LOG_API,"zebra_begin_trans rw=%d",rw);
1341 if (rw && !strchr(zh->user_perm, 'w'))
1355 const char *rval = 0;
1360 read_res_for_transaction(zh);
1363 if (zh->trans_no != 1)
1366 zh->errString = "zebra_begin_trans: write trans not allowed within read trans";
1371 resultSetInvalidate (zh);
1372 zebra_register_close (zh->service, zh->reg);
1374 zh->trans_w_no = zh->trans_no;
1378 zh->records_inserted = 0;
1379 zh->records_updated = 0;
1380 zh->records_deleted = 0;
1381 zh->records_processed = 0;
1383 #if HAVE_SYS_TIMES_H
1387 if (zh->shadow_enable)
1388 rval = res_get (zh->res, "shadow");
1390 for (pass = 0; pass < 2; pass++)
1394 zebra_lock_r (zh->lock_normal);
1395 zebra_lock_w (zh->lock_shadow);
1399 zebra_lock_w (zh->lock_normal);
1400 zebra_lock_w (zh->lock_shadow);
1403 zebra_get_state (zh, &val, &seqno);
1406 yaz_log (LOG_WARN, "previous transaction didn't finish commit");
1407 zebra_unlock (zh->lock_shadow);
1408 zebra_unlock (zh->lock_normal);
1412 else if (val == 'd')
1416 BFiles bfs = bfs_create (res_get (zh->res, "shadow"),
1418 yaz_log (LOG_WARN, "previous transaction didn't reach commit");
1419 bf_commitClean (bfs, rval);
1424 yaz_log (LOG_WARN, "your previous transaction didn't finish");
1431 yaz_log (LOG_FATAL, "zebra_begin_trans couldn't finish commit");
1435 zebra_set_state (zh, 'd', seqno);
1437 zh->reg = zebra_register_open (zh->service, zh->reg_name,
1438 1, rval ? 1 : 0, zh->res,
1441 zh->reg->seqno = seqno;
1444 zebra_set_state (zh, 'o', seqno);
1446 zebra_unlock (zh->lock_shadow);
1447 zebra_unlock (zh->lock_normal);
1453 zh->errString = "zebra_begin_trans: cannot open register";
1454 yaz_log(LOG_FATAL, zh->errString);
1466 if (zh->trans_no != 1)
1468 zebra_flush_reg (zh);
1472 #if HAVE_SYS_TIMES_H
1481 if (!zh->lock_normal || !zh->lock_shadow)
1487 zebra_get_state (zh, &val, &seqno);
1493 else if (seqno != zh->reg->seqno)
1495 yaz_log (LOG_DEBUG, "reopen seqno cur/old %d/%d",
1496 seqno, zh->reg->seqno);
1499 else if (zh->reg->last_val != val)
1501 yaz_log (LOG_DEBUG, "reopen last cur/old %d/%d",
1502 val, zh->reg->last_val);
1509 zebra_lock_r (zh->lock_shadow);
1511 zebra_lock_r (zh->lock_normal);
1515 resultSetInvalidate (zh);
1516 zebra_register_close (zh->service, zh->reg);
1518 zh->reg = zebra_register_open (zh->service, zh->reg_name,
1519 0, val == 'c' ? 1 : 0,
1520 zh->res, zh->path_reg);
1523 zebra_unlock (zh->lock_normal);
1524 zebra_unlock (zh->lock_shadow);
1529 zh->reg->last_val = val;
1530 zh->reg->seqno = seqno;
1532 read_res_for_transaction(zh);
1536 int zebra_end_trans (ZebraHandle zh)
1538 ZebraTransactionStatus dummy;
1539 yaz_log(LOG_API,"zebra_end_trans");
1540 return zebra_end_transaction(zh, &dummy);
1543 int zebra_end_transaction (ZebraHandle zh, ZebraTransactionStatus *status)
1550 yaz_log(LOG_API,"zebra_end_transaction");
1552 status->processed = 0;
1553 status->inserted = 0;
1554 status->updated = 0;
1555 status->deleted = 0;
1559 if (!zh->res || !zh->reg)
1562 zh->errString = "zebra_end_trans: no open transaction";
1565 if (zh->trans_no != zh->trans_w_no)
1568 if (zh->trans_no != 0)
1571 /* release read lock */
1573 zebra_unlock (zh->lock_normal);
1574 zebra_unlock (zh->lock_shadow);
1577 { /* release write lock */
1581 yaz_log (LOG_DEBUG, "zebra_end_trans");
1582 rval = res_get (zh->res, "shadow");
1584 zebraExplain_runNumberIncrement (zh->reg->zei, 1);
1586 zebra_flush_reg (zh);
1588 resultSetInvalidate (zh);
1590 zebra_register_close (zh->service, zh->reg);
1593 yaz_log (LOG_LOG, "Records: "ZINT_FORMAT" i/u/d "
1594 ZINT_FORMAT"/"ZINT_FORMAT"/"ZINT_FORMAT,
1595 zh->records_processed, zh->records_inserted,
1596 zh->records_updated, zh->records_deleted);
1598 status->processed = zh->records_processed;
1599 status->inserted = zh->records_inserted;
1600 status->updated = zh->records_updated;
1601 status->deleted = zh->records_deleted;
1603 zebra_get_state (zh, &val, &seqno);
1606 BFiles bfs = bfs_create (rval, zh->path_reg);
1607 yaz_log (LOG_DEBUG, "deleting shadow val=%c", val);
1608 bf_commitClean (bfs, rval);
1613 zebra_set_state (zh, 'o', seqno);
1615 zebra_unlock (zh->lock_shadow);
1616 zebra_unlock (zh->lock_normal);
1619 #if HAVE_SYS_TIMES_H
1621 logf (LOG_LOG, "user/system: %ld/%ld",
1622 (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1623 (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1625 status->utime = (long) (zh->tms2.tms_utime - zh->tms1.tms_utime);
1626 status->stime = (long) (zh->tms2.tms_stime - zh->tms1.tms_stime);
1631 int zebra_repository_update (ZebraHandle zh, const char *path)
1635 logf (LOG_API, "updating %s", path);
1636 repositoryUpdate (zh, path);
1640 int zebra_repository_delete (ZebraHandle zh, const char *path)
1644 logf (LOG_API, "deleting %s", path);
1645 repositoryDelete (zh, path);
1649 int zebra_repository_show (ZebraHandle zh, const char *path)
1652 yaz_log(LOG_API,"zebra_repository_show");
1654 repositoryShow (zh, path);
1658 static int zebra_commit_ex (ZebraHandle zh, int clean_only)
1672 rval = res_get (zh->res, "shadow");
1675 logf (LOG_WARN, "Cannot perform commit");
1676 logf (LOG_WARN, "No shadow area defined");
1680 zebra_lock_w (zh->lock_normal);
1681 zebra_lock_r (zh->lock_shadow);
1683 bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1685 zebra_get_state (zh, &val, &seqno);
1688 bf_cache (bfs, rval);
1689 if (bf_commitExists (bfs))
1692 zebra_set_state (zh, 'd', seqno);
1695 zebra_set_state (zh, 'c', seqno);
1697 logf (LOG_DEBUG, "commit start");
1698 bf_commitExec (bfs);
1703 logf (LOG_DEBUG, "commit clean");
1704 bf_commitClean (bfs, rval);
1706 zebra_set_state (zh, 'o', seqno);
1710 logf (LOG_LOG, "nothing to commit");
1714 zebra_unlock (zh->lock_shadow);
1715 zebra_unlock (zh->lock_normal);
1719 int zebra_clean (ZebraHandle zh)
1721 yaz_log(LOG_API,"zebra_clean");
1722 return zebra_commit_ex(zh, 1);
1725 int zebra_commit (ZebraHandle zh)
1727 yaz_log(LOG_API,"zebra_commit");
1728 return zebra_commit_ex(zh, 0);
1731 int zebra_init (ZebraHandle zh)
1736 yaz_log(LOG_API,"zebra_init");
1744 rval = res_get (zh->res, "shadow");
1746 bfs = bfs_create (res_get (zh->service->global_res, "register"),
1751 bf_cache (bfs, rval);
1755 zebra_set_state (zh, 'o', 0);
1759 int zebra_compact (ZebraHandle zh)
1763 yaz_log(LOG_API,"zebra_compact");
1770 bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1776 int zebra_result (ZebraHandle zh, int *code, char **addinfo)
1779 yaz_log(LOG_API,"zebra_result");
1780 *code = zh->errCode;
1781 *addinfo = zh->errString;
1785 int zebra_shadow_enable (ZebraHandle zh, int value)
1788 yaz_log(LOG_API,"zebra_shadow_enable");
1790 zh->shadow_enable = value;
1794 int zebra_record_encoding (ZebraHandle zh, const char *encoding)
1797 yaz_log(LOG_API,"zebra_record_encoding");
1799 xfree (zh->record_encoding);
1803 * Something about charset aliases. Oleg???
1806 if (zh->iconv_to_utf8 != 0)
1807 yaz_iconv_close(zh->iconv_to_utf8);
1808 if (zh->iconv_from_utf8 != 0)
1809 yaz_iconv_close(zh->iconv_from_utf8);
1811 zh->record_encoding = xstrdup (encoding);
1813 logf(LOG_DEBUG, "Reset record encoding: %s", encoding);
1816 yaz_iconv_open ("UTF-8", encoding);
1817 if (zh->iconv_to_utf8 == 0)
1818 yaz_log (LOG_WARN, "iconv: %s to UTF-8 unsupported", encoding);
1819 zh->iconv_from_utf8 =
1820 yaz_iconv_open (encoding, "UTF-8");
1821 if (zh->iconv_to_utf8 == 0)
1822 yaz_log (LOG_WARN, "iconv: UTF-8 to %s unsupported", encoding);
1827 int zebra_set_resource(ZebraHandle zh, const char *name, const char *value)
1830 yaz_log(LOG_API,"zebra_set_resource %s:%s",name,value);
1832 res_set(zh->res, name, value);
1836 const char *zebra_get_resource(ZebraHandle zh,
1837 const char *name, const char *defaultvalue)
1841 v= res_get_def( zh->res, name, (char *)defaultvalue);
1843 yaz_log(LOG_API,"zebra_get_resource %s:%s",name,v);
1847 /* moved from zebra_api_ext.c by pop */
1848 /* FIXME: Should this really be public??? -Heikki */
1850 int zebra_trans_no (ZebraHandle zh)
1853 yaz_log(LOG_API,"zebra_trans_no");
1854 return zh->trans_no;
1857 int zebra_get_shadow_enable (ZebraHandle zh)
1859 yaz_log(LOG_API,"zebra_get_shadow_enable");
1860 return (zh->shadow_enable);
1863 int zebra_set_shadow_enable (ZebraHandle zh, int value)
1865 yaz_log(LOG_API,"zebra_set_shadow_enable %d",value);
1866 zh->shadow_enable = value;
1870 /* almost the same as zebra_records_retrieve ... but how did it work?
1871 I mean for multiple records ??? CHECK ??? */
1872 void api_records_retrieve (ZebraHandle zh, ODR stream,
1873 const char *setname, Z_RecordComposition *comp,
1874 oid_value input_format, int num_recs,
1875 ZebraRetrievalRecord *recs)
1879 yaz_log(LOG_API,"api_records_retrieve s=%s n=%d",setname,num_recs);
1884 zh->errString = odr_strdup (stream, setname);
1890 if (zebra_begin_read (zh))
1893 pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
1894 for (i = 0; i<num_recs; i++)
1895 pos_array[i] = recs[i].position;
1896 poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
1899 logf (LOG_DEBUG, "zebraPosSetCreate error");
1901 zh->errString = nmem_strdup (stream->mem, setname);
1905 for (i = 0; i<num_recs; i++)
1909 recs[i].errCode = 0;
1910 recs[i].format = VAL_SUTRS;
1911 recs[i].len = strlen(poset[i].term);
1912 recs[i].buf = poset[i].term;
1913 recs[i].base = poset[i].db;
1917 else if (poset[i].sysno)
1919 /* changed here ??? CHECK ??? */
1922 zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
1923 stream, input_format, comp,
1928 recs[i].buf = (char *) odr_malloc(stream,recs[i].len);
1929 memcpy(recs[i].buf, b, recs[i].len);
1930 recs[i].errString = 0; /* Hmmm !!! we should get this */
1931 recs[i].sysno = poset[i].sysno;
1932 recs[i].score = poset[i].score;
1938 sprintf (num_str, "%d", pos_array[i]);
1940 zh->errString = odr_strdup (stream, num_str);
1945 zebraPosSetDestroy (zh, poset, num_recs);
1947 zebra_end_read (zh);
1952 /* ---------------------------------------------------------------------------
1953 Record insert(=update), delete
1955 If sysno is provided, then it's used to identify the record.
1956 If not, and match_criteria is provided, then sysno is guessed
1957 If not, and a record is provided, then sysno is got from there
1958 NOTE: Now returns 0 at success and updates sysno, which is an int*
1962 int zebra_add_record(ZebraHandle zh,
1963 const char *buf, int buf_size)
1966 return zebra_update_record(zh, 0, &sysno, 0, 0, buf, buf_size, 0);
1969 int zebra_insert_record (ZebraHandle zh,
1970 const char *recordType,
1971 SYSNO *sysno, const char *match, const char *fname,
1972 const char *buf, int buf_size, int force_update)
1975 yaz_log(LOG_API, "zebra_insert_record sysno=" ZINT_FORMAT, *sysno);
1977 if (buf_size < 1) buf_size = strlen(buf);
1979 if (zebra_begin_trans(zh, 1))
1981 res = buffer_extract_record (zh, buf, buf_size,
1982 0, /* delete_flag */
1988 0); /* allow_update */
1989 zebra_end_trans(zh);
1993 int zebra_update_record (ZebraHandle zh,
1994 const char *recordType,
1995 SYSNO* sysno, const char *match, const char *fname,
1996 const char *buf, int buf_size,
2001 yaz_log(LOG_API, "zebra_update_record sysno=" ZINT_FORMAT, *sysno);
2003 if (buf_size < 1) buf_size = strlen(buf);
2005 if (zebra_begin_trans(zh, 1))
2007 res = buffer_extract_record (zh, buf, buf_size,
2008 0, /* delete_flag */
2014 1); /* allow_update */
2015 zebra_end_trans(zh);
2019 int zebra_delete_record (ZebraHandle zh,
2020 const char *recordType,
2021 SYSNO *sysno, const char *match, const char *fname,
2022 const char *buf, int buf_size,
2026 yaz_log(LOG_API, "zebra_delete_record sysno=" ZINT_FORMAT, *sysno);
2028 if (buf_size < 1) buf_size = strlen(buf);
2030 if (zebra_begin_trans(zh, 1))
2032 res = buffer_extract_record (zh, buf, buf_size,
2033 1, /* delete_flag */
2039 1); /* allow_update */
2040 zebra_end_trans(zh);
2044 /* ---------------------------------------------------------------------------
2048 int zebra_search_PQF (ZebraHandle zh, const char *pqf_query,
2049 const char *setname, int *numhits)
2054 ODR odr = odr_createmem(ODR_ENCODE);
2056 yaz_log(LOG_API,"zebra_search_PQF s=%s q=%s",setname, pqf_query);
2058 query = p_query_rpn (odr, PROTO_Z3950, pqf_query);
2061 yaz_log (LOG_WARN, "bad query %s\n", pqf_query);
2063 res=zebra_search_RPN (zh, odr, query, setname, &hits);
2067 yaz_log(LOG_API,"Hits: %d",hits);
2075 /* ---------------------------------------------------------------------------
2076 Sort - a simplified interface, with optional read locks.
2078 int zebra_sort_by_specstr (ZebraHandle zh,
2080 const char *sort_spec,
2081 const char *output_setname,
2082 const char **input_setnames)
2084 int num_input_setnames = 0;
2085 int sort_status = 0;
2086 Z_SortKeySpecList *sort_sequence = yaz_sort_spec (stream, sort_spec);
2087 yaz_log(LOG_API,"sort (FIXME) ");
2090 logf(LOG_WARN,"invalid sort specs '%s'", sort_spec);
2095 /* we can do this, since the perl typemap code for char** will
2096 put a NULL at the end of list */
2097 while (input_setnames[num_input_setnames]) num_input_setnames++;
2099 if (zebra_begin_read (zh))
2102 resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
2103 output_setname, sort_sequence, &sort_status);