1 /* $Id: zebraapi.c,v 1.120.2.17 2006-10-23 11:37:11 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 this program; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
34 #include <yaz/diagbib1.h>
35 #include <yaz/pquery.h>
36 #include <yaz/sortspec.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;
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_LOG,"zebra_start %s %s", configName, ZEBRAVER);
157 if ((res = res_open (configName, def_res, over_res)))
159 const char *passwd_plain = 0;
160 const char *passwd_encrypt = 0;
161 ZebraService zh = xmalloc (sizeof(*zh));
163 yaz_log (LOG_DEBUG, "Read resources `%s'", configName);
165 zh->global_res = res;
166 zh->configName = xstrdup(configName);
171 zebra_mutex_cond_init (&zh->session_lock);
172 passwd_plain = res_get (zh->global_res, "passwd");
173 passwd_encrypt = res_get (zh->global_res, "passwd.c");
175 if (!passwd_plain && !passwd_encrypt)
176 zh->passwd_db = NULL;
179 zh->passwd_db = passwd_db_open();
181 logf (LOG_WARN|LOG_ERRNO, "passwd_db_open failed");
185 if (passwd_db_file_plain(zh->passwd_db, passwd_plain))
188 "Failed to read passwords %s (or unsupported)",
193 if (passwd_db_file_crypt(zh->passwd_db, passwd_encrypt))
196 "Failed to read encrypted pwds %s "
197 "(or unsupported)", passwd_encrypt);
203 zh->path_root = res_get (zh->global_res, "root");
210 void zebra_pidfname(ZebraService zs, char *path)
212 zebra_lock_prefix (zs->global_res, path);
213 strcat(path, "zebrasrv.pid");
217 struct zebra_register *zebra_register_open (ZebraService zs, const char *name,
218 int rw, int useshadow, Res res,
219 const char *reg_path)
221 struct zebra_register *reg;
222 int record_compression = REC_COMPRESS_NONE;
223 const char *recordCompression = 0;
224 const char *profilePath;
229 reg = xmalloc (sizeof(*reg));
232 reg->name = xstrdup (name);
239 yaz_log (LOG_LOG|LOG_API, "zebra_register_open rw = %d useshadow=%d p=%p,n=%s,rp=%s",
240 rw, useshadow, reg, name, reg_path ? reg_path : "(none)");
242 reg->dh = data1_createx (DATA1_FLAG_XML);
245 reg->bfs = bfs_create (res_get (res, "register"), reg_path);
248 data1_destroy(reg->dh);
252 bf_cache (reg->bfs, res_get (res, "shadow"));
254 getcwd(cwd, sizeof(cwd)-1);
255 profilePath = res_get_def(res, "profilePath", DEFAULT_PROFILE_PATH);
256 yaz_log(LOG_LOG, "profilePath=%s cwd=%s", profilePath, cwd);
258 data1_set_tabpath (reg->dh, profilePath);
259 data1_set_tabroot (reg->dh, reg_path);
260 reg->recTypes = recTypes_init (reg->dh);
261 recTypes_default_handlers (reg->recTypes);
263 reg->zebra_maps = zebra_maps_open (res, reg_path);
264 reg->rank_classes = NULL;
268 reg->keys.buf_max = 0;
270 reg->sortKeys.buf = 0;
271 reg->sortKeys.buf_max = 0;
284 reg->key_file_no = 0;
287 zebraRankInstall (reg, rank1_class);
288 zebraRankInstall (reg, rankzv_class);
289 zebraRankInstall (reg, rankliv_class);
291 recordCompression = res_get_def (res, "recordCompression", "none");
292 if (!strcmp (recordCompression, "none"))
293 record_compression = REC_COMPRESS_NONE;
294 if (!strcmp (recordCompression, "bzip2"))
295 record_compression = REC_COMPRESS_BZIP2;
297 if (!(reg->records = rec_open (reg->bfs, rw, record_compression)))
299 logf (LOG_WARN, "rec_open");
304 reg->matchDict = dict_open (reg->bfs, GMATCH_DICT, 20, 1, 0);
306 if (!(reg->dict = dict_open (reg->bfs, FNAME_DICT, 40, rw, 0)))
308 logf (LOG_WARN, "dict_open");
311 if (!(reg->sortIdx = sortIdx_open (reg->bfs, rw)))
313 logf (LOG_WARN, "sortIdx_open");
316 if (res_get_match (res, "isam", "s", ISAM_DEFAULT))
318 struct ISAMS_M_s isams_m;
319 if (!(reg->isams = isams_open (reg->bfs, FNAME_ISAMS, rw,
320 key_isams_m(res, &isams_m))))
322 logf (LOG_WARN, "isams_open");
326 if (res_get_match (res, "isam", "i", ISAM_DEFAULT))
328 if (!(reg->isam = is_open (reg->bfs, FNAME_ISAM, key_compare, rw,
329 sizeof (struct it_key), res)))
331 logf (LOG_WARN, "is_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", "d", ISAM_DEFAULT))
347 struct ISAMD_M_s isamd_m;
349 if (!(reg->isamd = isamd_open (reg->bfs, FNAME_ISAMD,
350 rw, key_isamd_m(res, &isamd_m))))
352 logf (LOG_WARN, "isamd_open");
356 if (res_get_match (res, "isam", "b", 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), 0)))
363 logf (LOG_WARN, "isamb_open");
367 if (res_get_match (res, "isam", "bc", 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 if (res_get_match (res, "isam", "null", ISAM_DEFAULT))
380 struct ISAMC_M_s isamc_m;
382 if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
383 rw, key_isamc_m(res, &isamc_m), -1)))
385 logf (LOG_WARN, "isamb_open");
389 reg->zei = zebraExplain_open (reg->records, reg->dh,
394 logf (LOG_WARN, "Cannot obtain EXPLAIN information");
398 yaz_log (LOG_DEBUG, "zebra_register_open ok p=%p", reg);
402 int zebra_admin_shutdown (ZebraHandle zh)
405 yaz_log(LOG_API,"zebra_admin_shutdown");
408 zebra_mutex_cond_lock (&zh->service->session_lock);
409 zh->service->stop_flag = 1;
410 zebra_mutex_cond_unlock (&zh->service->session_lock);
414 int zebra_admin_start (ZebraHandle zh)
418 yaz_log(LOG_API,"zebra_admin_start");
421 zebra_mutex_cond_lock (&zs->session_lock);
422 zebra_mutex_cond_unlock (&zs->session_lock);
426 static void zebra_register_close (ZebraService zs, struct zebra_register *reg)
429 yaz_log(LOG_LOG|LOG_API, "zebra_register_close p=%p", reg);
434 zebraExplain_close (reg->zei);
435 dict_close (reg->dict);
437 dict_close (reg->matchDict);
438 sortIdx_close (reg->sortIdx);
440 isams_close (reg->isams);
442 is_close (reg->isam);
444 isc_close (reg->isamc);
446 isamd_close (reg->isamd);
448 isamb_close (reg->isamb);
449 rec_close (®->records);
452 recTypes_destroy (reg->recTypes);
453 zebra_maps_close (reg->zebra_maps);
454 zebraRankDestroy (reg);
455 bfs_destroy (reg->bfs);
456 data1_destroy (reg->dh);
458 xfree (reg->sortKeys.buf);
459 xfree (reg->keys.buf);
461 xfree (reg->key_buf);
466 int zebra_stop(ZebraService zs)
470 yaz_log (LOG_LOG|LOG_API, "zebra_stop");
474 zebra_close (zs->sessions);
477 zebra_mutex_cond_destroy (&zs->session_lock);
480 passwd_db_close (zs->passwd_db);
482 res_close (zs->global_res);
483 xfree (zs->configName);
488 int zebra_close (ZebraHandle zh)
491 struct zebra_session **sp;
494 yaz_log(LOG_API,"zebra_close");
501 yaz_log (LOG_DEBUG, "zebra_close zh=%p", zh);
502 resultSetDestroy (zh, -1, 0, 0);
505 zebra_register_close (zh->service, zh->reg);
506 zebra_close_res (zh);
508 xfree (zh->record_encoding);
510 for (i = 0; i < zh->num_basenames; i++)
511 xfree (zh->basenames[i]);
512 xfree (zh->basenames);
514 if (zh->iconv_to_utf8 != 0)
515 yaz_iconv_close (zh->iconv_to_utf8);
516 if (zh->iconv_from_utf8 != 0)
517 yaz_iconv_close (zh->iconv_from_utf8);
519 zebra_mutex_cond_lock (&zs->session_lock);
520 zebra_lock_destroy (zh->lock_normal);
521 zebra_lock_destroy (zh->lock_shadow);
533 zebra_mutex_cond_unlock (&zs->session_lock);
534 xfree (zh->reg_name);
535 xfree (zh->user_perm);
536 zh->service=0; /* more likely to trigger an assert */
537 xfree (zh->path_reg);
542 struct map_baseinfo {
548 char **new_basenames;
552 static Res zebra_open_res (ZebraHandle zh)
561 sprintf (fname, "%.200s/zebra.cfg", zh->path_reg);
562 res = res_open (fname, zh->service->global_res, 0);
564 res = zh->service->global_res;
566 else if (*zh->reg_name == 0)
568 res = zh->service->global_res;
572 yaz_log (LOG_WARN, "no register root specified");
573 return 0; /* no path for register - fail! */
578 static void zebra_close_res (ZebraHandle zh)
582 if (zh->res != zh->service->global_res)
587 static int zebra_select_register (ZebraHandle zh, const char *new_reg)
591 if (zh->res && strcmp (zh->reg_name, new_reg) == 0)
595 assert (zh->reg == 0);
596 assert (*zh->reg_name == 0);
602 resultSetInvalidate (zh);
603 zebra_register_close (zh->service, zh->reg);
608 xfree (zh->reg_name);
609 zh->reg_name = xstrdup (new_reg);
611 xfree (zh->path_reg);
613 if (zh->service->path_root)
615 zh->path_reg = xmalloc (strlen(zh->service->path_root) +
616 strlen(zh->reg_name) + 3);
617 strcpy (zh->path_reg, zh->service->path_root);
620 strcat (zh->path_reg, "/");
621 strcat (zh->path_reg, zh->reg_name);
624 zh->res = zebra_open_res (zh);
627 zebra_lock_destroy (zh->lock_normal);
631 zebra_lock_destroy (zh->lock_shadow);
637 const char *lock_area =res_get (zh->res, "lockDir");
639 if (!lock_area && zh->path_reg)
640 res_set (zh->res, "lockDir", zh->path_reg);
641 sprintf (fname, "norm.%s.LCK", zh->reg_name);
643 zebra_lock_create (res_get(zh->res, "lockDir"), fname);
645 sprintf (fname, "shadow.%s.LCK", zh->reg_name);
647 zebra_lock_create (res_get(zh->res, "lockDir"), fname);
649 if (!zh->lock_normal || !zh->lock_shadow)
653 zebra_lock_destroy(zh->lock_normal);
658 zebra_lock_destroy(zh->lock_shadow);
669 void map_basenames_func (void *vp, const char *name, const char *value)
671 struct map_baseinfo *p = (struct map_baseinfo *) vp;
673 char fromdb[128], todb[8][128];
676 sscanf (value, "%127s %127s %127s %127s %127s %127s %127s %127s %127s",
677 fromdb, todb[0], todb[1], todb[2], todb[3], todb[4],
678 todb[5], todb[6], todb[7]);
682 for (i = 0; i<p->num_bases; i++)
683 if (p->basenames[i] && !STRCASECMP (p->basenames[i], fromdb))
686 for (i = 0; i < no; i++)
688 if (p->new_num_bases == p->new_num_max)
690 p->new_basenames[(p->new_num_bases)++] =
691 nmem_strdup (p->mem, todb[i]);
697 void map_basenames (ZebraHandle zh, ODR stream,
698 int *num_bases, char ***basenames)
700 struct map_baseinfo info;
701 struct map_baseinfo *p = &info;
704 yaz_log(LOG_API,"map_basenames ");
708 info.num_bases = *num_bases;
709 info.basenames = *basenames;
710 info.new_num_max = 128;
711 info.new_num_bases = 0;
712 info.new_basenames = (char **)
713 odr_malloc (stream, sizeof(*info.new_basenames) * info.new_num_max);
714 info.mem = stream->mem;
716 res_trav (zh->service->global_res, "mapdb", &info, map_basenames_func);
718 for (i = 0; i<p->num_bases; i++)
719 if (p->basenames[i] && p->new_num_bases < p->new_num_max)
721 p->new_basenames[(p->new_num_bases)++] =
722 nmem_strdup (p->mem, p->basenames[i]);
724 *num_bases = info.new_num_bases;
725 *basenames = info.new_basenames;
726 for (i = 0; i<*num_bases; i++)
727 logf (LOG_LOG, "base %s", (*basenames)[i]);
730 int zebra_select_default_database(ZebraHandle zh)
734 /* no database has been selected - so we select based on
735 resource setting (including group)
737 const char *group = res_get(zh->service->global_res, "group");
738 const char *v = res_get_prefix(zh->service->global_res,
739 "database", group, "Default");
740 return zebra_select_database(zh, v);
745 int zebra_select_database (ZebraHandle zh, const char *basename)
748 yaz_log(LOG_API,"zebra_select_database %s",basename);
749 return zebra_select_databases (zh, 1, &basename);
752 int zebra_select_databases (ZebraHandle zh, int num_bases,
753 const char **basenames)
760 yaz_log(LOG_API,"zebra_select_databases n=%d [0]=%s",
761 num_bases,basenames[0]);
762 zebra_clearError(zh);
769 for (i = 0; i < zh->num_basenames; i++)
770 xfree (zh->basenames[i]);
771 xfree (zh->basenames);
773 zh->num_basenames = num_bases;
774 zh->basenames = xmalloc (zh->num_basenames * sizeof(*zh->basenames));
775 for (i = 0; i < zh->num_basenames; i++)
776 zh->basenames[i] = xstrdup (basenames[i]);
778 cp = strrchr(basenames[0], '/');
781 len = cp - basenames[0];
782 new_reg = xmalloc (len + 1);
783 memcpy (new_reg, basenames[0], len);
787 new_reg = xstrdup ("");
788 for (i = 1; i<num_bases; i++)
792 cp1 = strrchr (basenames[i], '/');
800 if (len != cp1 - basenames[i] ||
801 memcmp (basenames[i], new_reg, len))
816 zebra_select_register (zh, new_reg);
823 if (!zh->lock_normal || !zh->lock_shadow)
831 int zebra_search_RPN (ZebraHandle zh, ODR o,
832 Z_RPNQuery *query, const char *setname, int *hits)
835 yaz_log(LOG_API,"zebra_search_rpn");
837 zebra_clearError(zh);
841 if (zebra_begin_read (zh))
844 zebra_livcode_transform(zh, query);
846 resultSetAddRPN (zh, odr_extract_mem(o), query,
847 zh->num_basenames, zh->basenames, setname);
855 int zebra_records_retrieve (ZebraHandle zh, ODR stream,
856 const char *setname, Z_RecordComposition *comp,
857 oid_value input_format, int num_recs,
858 ZebraRetrievalRecord *recs)
861 int i, *pos_array, ret = 0;
863 yaz_log(LOG_API,"zebra_records_retrieve n=%d",num_recs);
865 zebra_clearError(zh);
870 zh->errString = odr_strdup (stream, setname);
874 if (zebra_begin_read (zh))
877 pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
878 for (i = 0; i<num_recs; i++)
879 pos_array[i] = recs[i].position;
880 poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
883 logf (LOG_DEBUG, "zebraPosSetCreate error");
885 zh->errString = nmem_strdup (stream->mem, setname);
890 for (i = 0; i<num_recs; i++)
895 recs[i].format = VAL_SUTRS;
896 recs[i].len = strlen(poset[i].term);
897 recs[i].buf = poset[i].term;
898 recs[i].base = poset[i].db;
900 else if (poset[i].sysno)
903 zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
904 stream, input_format, comp,
905 &recs[i].format, &recs[i].buf,
908 recs[i].errString = NULL;
914 sprintf (num_str, "%d", pos_array[i]);
916 zh->errString = odr_strdup (stream, num_str);
921 zebraPosSetDestroy (zh, poset, num_recs);
928 int zebra_scan (ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
929 oid_value attributeset,
930 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,
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 yaz_log(LOG_API,"zebra_deleleResultSet n=%d",num_setnames);
973 if (zebra_begin_read(zh))
974 return Z_DeleteStatus_systemProblemAtTarget;
977 case Z_DeleteResultSetRequest_list:
978 resultSetDestroy (zh, num_setnames, setnames, statuses);
980 case Z_DeleteResultSetRequest_all:
981 resultSetDestroy (zh, -1, 0, statuses);
985 status = Z_DeleteStatus_success;
986 for (i = 0; i<num_setnames; i++)
987 if (statuses[i] == Z_DeleteStatus_resultSetDidNotExist)
988 status = statuses[i];
992 int zebra_errCode (ZebraHandle zh)
996 yaz_log(LOG_API,"zebra_errCode: %d",zh->errCode);
999 yaz_log(LOG_API,"zebra_errCode: o");
1003 const char *zebra_errString (ZebraHandle zh)
1007 e= diagbib1_str (zh->errCode);
1008 yaz_log(LOG_API,"zebra_errString: %s",e);
1012 char *zebra_errAdd (ZebraHandle zh)
1017 yaz_log(LOG_API,"zebra_errAdd: %s",a);
1021 void zebra_clearError(ZebraHandle zh)
1030 int zebra_auth (ZebraHandle zh, const char *user, const char *pass)
1040 sprintf(u, "perm.%.30s", user ? user : "anonymous");
1041 p = res_get(zs->global_res, u);
1042 xfree (zh->user_perm);
1043 zh->user_perm = xstrdup(p ? p : "r");
1045 yaz_log(LOG_LOG, "User perm for %s: %s", u, zh->user_perm);
1047 /* users that don't require a password .. */
1048 if (zh->user_perm && strchr(zh->user_perm, 'a'))
1051 if (!zs->passwd_db || !passwd_db_auth (zs->passwd_db, user, pass))
1056 int zebra_admin_import_begin (ZebraHandle zh, const char *database,
1057 const char *record_type)
1060 yaz_log(LOG_API,"zebra_admin_import_begin db=%s rt=%s",
1061 database, record_type);
1063 if (zebra_select_database(zh, database))
1065 if (zebra_begin_trans (zh, 1))
1070 int zebra_admin_import_end (ZebraHandle zh)
1073 yaz_log(LOG_API,"zebra_admin_import_end");
1075 zebra_end_trans (zh);
1079 int zebra_admin_import_segment (ZebraHandle zh, Z_Segment *segment)
1084 yaz_log(LOG_API,"zebra_admin_import_segment");
1086 for (i = 0; i<segment->num_segmentRecords; i++)
1088 Z_NamePlusRecord *npr = segment->segmentRecords[i];
1090 printf ("--------------%d--------------------\n", i);
1091 if (npr->which == Z_NamePlusRecord_intermediateFragment)
1093 Z_FragmentSyntax *fragment = npr->u.intermediateFragment;
1094 if (fragment->which == Z_FragmentSyntax_notExternallyTagged)
1096 Odr_oct *oct = fragment->u.notExternallyTagged;
1097 printf ("%.*s", (oct->len > 100 ? 100 : oct->len) ,
1102 zebra_update_record(zh,
1103 0, /* record Type */
1115 int zebra_admin_exchange_record (ZebraHandle zh,
1116 const char *rec_buf,
1118 const char *recid_buf, size_t recid_len,
1120 /* 1 = insert. Fail it already exists */
1121 /* 2 = replace. Fail it does not exist */
1122 /* 3 = delete. Fail if does not exist */
1123 /* 4 = update. Insert/replace */
1129 yaz_log(LOG_API,"zebra_admin_exchange_record ac=%d", action);
1132 if (!recid_buf || recid_len <= 0 || recid_len >= sizeof(recid_z))
1134 memcpy (recid_z, recid_buf, recid_len);
1135 recid_z[recid_len] = 0;
1137 if (zebra_begin_trans(zh, 1))
1140 rinfo = dict_lookup (zh->reg->matchDict, recid_z);
1143 if (action == 1) /* fail if insert */
1145 zebra_end_trans(zh);
1149 memcpy (&sysno, rinfo+1, sizeof(sysno));
1153 if (action == 2 || action == 3) /* fail if delete or update */
1155 zebra_end_trans(zh);
1158 action = 1; /* make it an insert (if it's an update).. */
1160 buffer_extract_record (zh, rec_buf, rec_len,
1161 action == 3 ? 1 : 0 /* delete flag */,
1167 0, /* force update */
1168 1 /* allow update */
1172 dict_insert (zh->reg->matchDict, recid_z, sizeof(sysno), &sysno);
1174 else if (action == 3)
1176 dict_delete (zh->reg->matchDict, recid_z);
1178 zebra_end_trans(zh);
1182 int delete_w_handle(const char *info, void *handle)
1184 ZebraHandle zh = (ZebraHandle) handle;
1187 if (*info == sizeof(pos))
1189 memcpy (&pos, info+1, sizeof(pos));
1190 isamb_unlink(zh->reg->isamb, pos);
1195 static int delete_SU_handle(void *handle, int ord)
1197 ZebraHandle zh = (ZebraHandle) handle;
1201 ord_len = key_SU_encode (ord, ord_buf);
1202 ord_buf[ord_len] = '\0';
1204 assert (zh->reg->isamb);
1205 dict_delete_subtree(zh->reg->dict, ord_buf,
1206 zh, delete_w_handle);
1210 int zebra_drop_database (ZebraHandle zh, const char *database)
1214 yaz_log(LOG_API,"zebra_drop_database");
1216 zebra_clearError(zh);
1218 if (zebra_select_database (zh, database))
1220 if (zebra_begin_trans (zh, 1))
1224 zebraExplain_curDatabase (zh->reg->zei, database);
1226 zebraExplain_trav_ord(zh->reg->zei, zh, delete_SU_handle);
1227 zebraExplain_removeDatabase(zh->reg->zei, zh);
1231 yaz_log(LOG_WARN, "drop database only supported for isam:b");
1234 zebra_end_trans (zh);
1238 int zebra_create_database (ZebraHandle zh, const char *database)
1241 yaz_log(LOG_API,"zebra_create_database");
1244 if (zebra_select_database (zh, database))
1246 if (zebra_begin_trans (zh, 1))
1249 /* announce database */
1250 if (zebraExplain_newDatabase (zh->reg->zei, database, 0
1251 /* explainDatabase */))
1253 zebra_end_trans (zh);
1255 zh->errString = "database already exist";
1258 zebra_end_trans (zh);
1262 int zebra_string_norm (ZebraHandle zh, unsigned reg_id,
1263 const char *input_str, int input_len,
1264 char *output_str, int output_len)
1268 yaz_log(LOG_API,"zebra_string_norm ");
1270 if (!zh->reg->zebra_maps)
1272 wrbuf = zebra_replace(zh->reg->zebra_maps, reg_id, "",
1273 input_str, input_len);
1276 if (wrbuf_len(wrbuf) >= output_len)
1278 if (wrbuf_len(wrbuf))
1279 memcpy (output_str, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
1280 output_str[wrbuf_len(wrbuf)] = '\0';
1281 return wrbuf_len(wrbuf);
1285 int zebra_set_state (ZebraHandle zh, int val, int seqno)
1287 char state_fname[256];
1292 yaz_log(LOG_API,"zebra_set_state v=%d seq=%d", val, seqno);
1295 sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1296 fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1297 f = fopen (fname, "w");
1299 yaz_log (LOG_DEBUG, "%c %d %ld", val, seqno, p);
1300 fprintf (f, "%c %d %ld\n", val, seqno, p);
1306 int zebra_get_state (ZebraHandle zh, char *val, int *seqno)
1308 char state_fname[256];
1313 yaz_log(LOG_API,"zebra_get_state ");
1315 sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1316 fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1317 f = fopen (fname, "r");
1323 fscanf (f, "%c %d", val, seqno);
1330 int zebra_begin_read (ZebraHandle zh)
1332 return zebra_begin_trans(zh, 0);
1335 int zebra_end_read (ZebraHandle zh)
1337 return zebra_end_trans(zh);
1340 static void read_res_for_transaction(ZebraHandle zh)
1342 const char *group = res_get(zh->res, "group");
1345 zh->m_group = group;
1346 v = res_get_prefix(zh->res, "followLinks", group, "1");
1347 zh->m_follow_links = atoi(v);
1349 zh->m_record_id = res_get_prefix(zh->res, "recordId", group, 0);
1350 zh->m_record_type = res_get_prefix(zh->res, "recordType", group, 0);
1352 v = res_get_prefix(zh->res, "storeKeys", group, "1");
1353 zh->m_store_keys = atoi(v);
1355 v = res_get_prefix(zh->res, "storeData", group, "1");
1356 zh->m_store_data = atoi(v);
1358 v = res_get_prefix(zh->res, "explainDatabase", group, "0");
1359 zh->m_explain_database = atoi(v);
1361 v = res_get_prefix(zh->res, "openRW", group, "1");
1362 zh->m_flag_rw = atoi(v);
1364 v = res_get_prefix(zh->res, "fileVerboseLimit", group, "100000");
1365 zh->m_file_verbose_limit = atoi(v);
1368 int zebra_begin_trans (ZebraHandle zh, int rw)
1370 zebra_select_default_database(zh);
1374 zh->errString = "zebra_begin_trans: no database selected";
1378 yaz_log(LOG_API,"zebra_begin_trans rw=%d",rw);
1382 if (rw && !strchr(zh->user_perm, 'w'))
1396 const char *rval = 0;
1401 read_res_for_transaction(zh);
1404 if (zh->trans_no != 1)
1407 zh->errString = "zebra_begin_trans: write trans not allowed within read trans";
1412 resultSetInvalidate (zh);
1413 zebra_register_close (zh->service, zh->reg);
1415 zh->trans_w_no = zh->trans_no;
1419 zh->records_inserted = 0;
1420 zh->records_updated = 0;
1421 zh->records_deleted = 0;
1422 zh->records_processed = 0;
1424 #if HAVE_SYS_TIMES_H
1428 if (zh->shadow_enable)
1429 rval = res_get (zh->res, "shadow");
1431 for (pass = 0; pass < 2; pass++)
1435 zebra_lock_r (zh->lock_normal);
1436 zebra_lock_w (zh->lock_shadow);
1440 zebra_lock_w (zh->lock_normal);
1441 zebra_lock_w (zh->lock_shadow);
1444 zebra_get_state (zh, &val, &seqno);
1447 yaz_log (LOG_LOG, "previous transaction didn't finish commit");
1448 zebra_unlock (zh->lock_shadow);
1449 zebra_unlock (zh->lock_normal);
1453 else if (val == 'd')
1457 BFiles bfs = bfs_create (res_get (zh->res, "shadow"),
1459 yaz_log (LOG_LOG, "previous transaction didn't reach commit");
1460 bf_commitClean (bfs, rval);
1465 yaz_log (LOG_WARN, "your previous transaction didn't finish");
1472 yaz_log (LOG_FATAL, "zebra_begin_trans couldn't finish commit");
1476 zebra_set_state (zh, 'd', seqno);
1478 zh->reg = zebra_register_open (zh->service, zh->reg_name,
1479 1, rval ? 1 : 0, zh->res,
1482 zh->reg->seqno = seqno;
1485 zebra_set_state (zh, 'o', seqno);
1487 zebra_unlock (zh->lock_shadow);
1488 zebra_unlock (zh->lock_normal);
1494 zh->errString = "zebra_begin_trans: cannot open register";
1495 yaz_log(LOG_FATAL, zh->errString);
1507 if (zh->trans_no != 1)
1509 zebra_flush_reg (zh);
1513 #if HAVE_SYS_TIMES_H
1522 if (!zh->lock_normal || !zh->lock_shadow)
1528 zebra_get_state (zh, &val, &seqno);
1534 else if (seqno != zh->reg->seqno)
1536 yaz_log (LOG_LOG, "reopen seqno cur/old %d/%d",
1537 seqno, zh->reg->seqno);
1540 else if (zh->reg->last_val != val)
1542 yaz_log (LOG_LOG, "reopen last cur/old %d/%d",
1543 val, zh->reg->last_val);
1550 zebra_lock_r (zh->lock_shadow);
1552 zebra_lock_r (zh->lock_normal);
1556 resultSetInvalidate (zh);
1557 zebra_register_close (zh->service, zh->reg);
1559 zh->reg = zebra_register_open (zh->service, zh->reg_name,
1560 0, val == 'c' ? 1 : 0,
1561 zh->res, zh->path_reg);
1564 zebra_unlock (zh->lock_normal);
1565 zebra_unlock (zh->lock_shadow);
1570 zh->reg->last_val = val;
1571 zh->reg->seqno = seqno;
1573 read_res_for_transaction(zh);
1577 int zebra_end_trans (ZebraHandle zh)
1579 ZebraTransactionStatus dummy;
1580 yaz_log(LOG_API,"zebra_end_trans");
1581 return zebra_end_transaction(zh, &dummy);
1584 int zebra_end_transaction (ZebraHandle zh, ZebraTransactionStatus *status)
1591 yaz_log(LOG_API,"zebra_end_transaction");
1593 status->processed = 0;
1594 status->inserted = 0;
1595 status->updated = 0;
1596 status->deleted = 0;
1600 if (!zh->res || !zh->reg)
1603 zh->errString = "zebra_end_trans: no open transaction";
1606 if (zh->trans_no != zh->trans_w_no)
1609 if (zh->trans_no != 0)
1612 /* release read lock */
1614 zebra_unlock (zh->lock_normal);
1615 zebra_unlock (zh->lock_shadow);
1618 { /* release write lock */
1622 yaz_log (LOG_LOG, "zebra_end_trans");
1623 rval = res_get (zh->res, "shadow");
1625 zebraExplain_runNumberIncrement (zh->reg->zei, 1);
1627 zebra_flush_reg (zh);
1629 resultSetInvalidate (zh);
1631 zebra_register_close (zh->service, zh->reg);
1634 yaz_log (LOG_LOG, "Records: %7d i/u/d %d/%d/%d",
1635 zh->records_processed, zh->records_inserted,
1636 zh->records_updated, zh->records_deleted);
1638 status->processed = zh->records_processed;
1639 status->inserted = zh->records_inserted;
1640 status->updated = zh->records_updated;
1641 status->deleted = zh->records_deleted;
1643 zebra_get_state (zh, &val, &seqno);
1646 BFiles bfs = bfs_create (rval, zh->path_reg);
1647 yaz_log (LOG_LOG, "deleting shadow stuff val=%c", val);
1648 bf_commitClean (bfs, rval);
1653 zebra_set_state (zh, 'o', seqno);
1655 zebra_unlock (zh->lock_shadow);
1656 zebra_unlock (zh->lock_normal);
1659 #if HAVE_SYS_TIMES_H
1661 logf (LOG_LOG, "user/system: %ld/%ld",
1662 (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1663 (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1665 status->utime = (long) (zh->tms2.tms_utime - zh->tms1.tms_utime);
1666 status->stime = (long) (zh->tms2.tms_stime - zh->tms1.tms_stime);
1671 int zebra_repository_update (ZebraHandle zh, const char *path)
1675 logf (LOG_LOG|LOG_API, "updating %s", path);
1676 repositoryUpdate (zh, path);
1680 int zebra_repository_delete (ZebraHandle zh, const char *path)
1684 logf (LOG_LOG|LOG_API, "deleting %s", path);
1685 repositoryDelete (zh, path);
1689 int zebra_repository_show (ZebraHandle zh, const char *path)
1692 yaz_log(LOG_API,"zebra_repository_show");
1694 repositoryShow (zh, path);
1698 static int zebra_commit_ex (ZebraHandle zh, int clean_only)
1707 zebra_select_default_database(zh);
1713 rval = res_get (zh->res, "shadow");
1716 logf (LOG_WARN, "Cannot perform commit");
1717 logf (LOG_WARN, "No shadow area defined");
1721 zebra_lock_w (zh->lock_normal);
1722 zebra_lock_r (zh->lock_shadow);
1724 bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1726 zebra_get_state (zh, &val, &seqno);
1730 logf(LOG_WARN, "previous transaction didn't reach commit");
1735 bf_cache (bfs, rval);
1736 if (bf_commitExists (bfs))
1739 zebra_set_state (zh, 'd', seqno);
1742 zebra_set_state (zh, 'c', seqno);
1744 logf (LOG_LOG, "commit start");
1745 bf_commitExec (bfs);
1748 zebra_set_state (zh, 'o', seqno);
1750 zebra_unlock (zh->lock_shadow);
1751 zebra_unlock (zh->lock_normal);
1753 zebra_lock_w(zh->lock_shadow);
1754 bf_commitClean (bfs, rval);
1755 zebra_unlock (zh->lock_shadow);
1759 zebra_unlock (zh->lock_shadow);
1760 zebra_unlock (zh->lock_normal);
1761 logf (LOG_LOG, "nothing to commit");
1768 int zebra_clean (ZebraHandle zh)
1770 yaz_log(LOG_API,"zebra_clean");
1771 return zebra_commit_ex(zh, 1);
1774 int zebra_commit (ZebraHandle zh)
1776 yaz_log(LOG_API,"zebra_commit");
1777 return zebra_commit_ex(zh, 0);
1780 int zebra_init (ZebraHandle zh)
1785 yaz_log(LOG_API,"zebra_init");
1788 zebra_select_default_database(zh);
1794 rval = res_get (zh->res, "shadow");
1796 bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1800 bf_cache (bfs, rval);
1804 zebra_set_state (zh, 'o', 0);
1808 int zebra_compact (ZebraHandle zh)
1812 yaz_log(LOG_API,"zebra_compact");
1819 bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1825 int zebra_result (ZebraHandle zh, int *code, char **addinfo)
1828 yaz_log(LOG_API,"zebra_result");
1829 *code = zh->errCode;
1830 *addinfo = zh->errString;
1834 int zebra_shadow_enable (ZebraHandle zh, int value)
1837 yaz_log(LOG_API,"zebra_shadow_enable");
1839 zh->shadow_enable = value;
1843 int zebra_record_encoding (ZebraHandle zh, const char *encoding)
1846 yaz_log(LOG_API,"zebra_record_encoding");
1848 xfree (zh->record_encoding);
1852 * Something about charset aliases. Oleg???
1855 if (zh->iconv_to_utf8 != 0)
1856 yaz_iconv_close(zh->iconv_to_utf8);
1857 if (zh->iconv_from_utf8 != 0)
1858 yaz_iconv_close(zh->iconv_from_utf8);
1860 zh->record_encoding = xstrdup (encoding);
1862 logf(LOG_DEBUG, "Reset record encoding: %s", encoding);
1865 yaz_iconv_open ("UTF-8", encoding);
1866 if (zh->iconv_to_utf8 == 0)
1867 yaz_log (LOG_WARN, "iconv: %s to UTF-8 unsupported", encoding);
1868 zh->iconv_from_utf8 =
1869 yaz_iconv_open (encoding, "UTF-8");
1870 if (zh->iconv_to_utf8 == 0)
1871 yaz_log (LOG_WARN, "iconv: UTF-8 to %s unsupported", encoding);
1876 int zebra_set_resource(ZebraHandle zh, const char *name, const char *value)
1879 yaz_log(LOG_API,"zebra_set_resource %s:%s",name,value);
1881 res_set(zh->res, name, value);
1885 const char *zebra_get_resource(ZebraHandle zh,
1886 const char *name, const char *defaultvalue)
1890 v= res_get_def( zh->res, name, (char *)defaultvalue);
1892 yaz_log(LOG_API,"zebra_get_resource %s:%s",name,v);
1896 /* moved from zebra_api_ext.c by pop */
1897 /* FIXME: Should this really be public??? -Heikki */
1899 int zebra_trans_no (ZebraHandle zh)
1902 yaz_log(LOG_API,"zebra_trans_no");
1903 return zh->trans_no;
1906 int zebra_get_shadow_enable (ZebraHandle zh)
1908 yaz_log(LOG_API,"zebra_get_shadow_enable");
1909 return (zh->shadow_enable);
1912 int zebra_set_shadow_enable (ZebraHandle zh, int value)
1914 yaz_log(LOG_API,"zebra_set_shadow_enable %d",value);
1915 zh->shadow_enable = value;
1919 /* almost the same as zebra_records_retrieve ... but how did it work?
1920 I mean for multiple records ??? CHECK ??? */
1921 void api_records_retrieve (ZebraHandle zh, ODR stream,
1922 const char *setname, Z_RecordComposition *comp,
1923 oid_value input_format, int num_recs,
1924 ZebraRetrievalRecord *recs)
1928 yaz_log(LOG_API,"api_records_retrieve s=%s n=%d",setname,num_recs);
1933 zh->errString = odr_strdup (stream, setname);
1939 if (zebra_begin_read (zh))
1942 pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
1943 for (i = 0; i<num_recs; i++)
1944 pos_array[i] = recs[i].position;
1945 poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
1948 logf (LOG_DEBUG, "zebraPosSetCreate error");
1950 zh->errString = nmem_strdup (stream->mem, setname);
1954 for (i = 0; i<num_recs; i++)
1958 recs[i].errCode = 0;
1959 recs[i].format = VAL_SUTRS;
1960 recs[i].len = strlen(poset[i].term);
1961 recs[i].buf = poset[i].term;
1962 recs[i].base = poset[i].db;
1966 else if (poset[i].sysno)
1968 /* changed here ??? CHECK ??? */
1971 zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
1972 stream, input_format, comp,
1977 recs[i].buf = (char *) odr_malloc(stream,recs[i].len);
1978 memcpy(recs[i].buf, b, recs[i].len);
1979 recs[i].errString = 0; /* Hmmm !!! we should get this */
1980 recs[i].sysno = poset[i].sysno;
1981 recs[i].score = poset[i].score;
1987 sprintf (num_str, "%d", pos_array[i]);
1989 zh->errString = odr_strdup (stream, num_str);
1994 zebraPosSetDestroy (zh, poset, num_recs);
1996 zebra_end_read (zh);
2001 /* ---------------------------------------------------------------------------
2002 Record insert(=update), delete
2004 If sysno is provided, then it's used to identify the record.
2005 If not, and match_criteria is provided, then sysno is guessed
2006 If not, and a record is provided, then sysno is got from there
2007 NOTE: Now returns 0 at success and updates sysno, which is an int*
2011 int zebra_add_record(ZebraHandle zh,
2012 const char *buf, int buf_size)
2015 return zebra_update_record(zh, 0, &sysno, 0, 0, buf, buf_size, 0);
2018 int zebra_insert_record (ZebraHandle zh,
2019 const char *recordType,
2020 int *sysno, const char *match, const char *fname,
2021 const char *buf, int buf_size, int force_update)
2024 yaz_log(LOG_API,"zebra_insert_record sysno=%d", *sysno);
2026 if (buf_size < 1) buf_size = strlen(buf);
2028 if (zebra_begin_trans(zh, 1))
2030 res = buffer_extract_record (zh, buf, buf_size,
2031 0, /* delete_flag */
2037 0); /* allow_update */
2038 zebra_end_trans(zh);
2042 int zebra_update_record (ZebraHandle zh,
2043 const char *recordType,
2044 int* sysno, const char *match, const char *fname,
2045 const char *buf, int buf_size,
2050 yaz_log(LOG_API,"zebra_update_record sysno=%d", *sysno);
2052 if (buf_size < 1) buf_size = strlen(buf);
2054 if (zebra_begin_trans(zh, 1))
2056 res = buffer_extract_record (zh, buf, buf_size,
2057 0, /* delete_flag */
2063 1); /* allow_update */
2064 yaz_log(LOG_LOG, "zebra_update_record returned res=%d", res);
2065 zebra_end_trans(zh);
2069 int zebra_delete_record (ZebraHandle zh,
2070 const char *recordType,
2071 int *sysno, const char *match, const char *fname,
2072 const char *buf, int buf_size,
2076 yaz_log(LOG_API,"zebra_delete_record sysno=%d", *sysno);
2078 if (buf_size < 1) buf_size = strlen(buf);
2080 if (zebra_begin_trans(zh, 1))
2082 res = buffer_extract_record (zh, buf, buf_size,
2083 1, /* delete_flag */
2089 1); /* allow_update */
2090 zebra_end_trans(zh);
2094 /* ---------------------------------------------------------------------------
2098 int zebra_search_PQF (ZebraHandle zh, const char *pqf_query,
2099 const char *setname, int *numhits)
2104 ODR odr = odr_createmem(ODR_ENCODE);
2106 yaz_log(LOG_API,"zebra_search_PQF s=%s q=%s",setname, pqf_query);
2108 query = p_query_rpn (odr, PROTO_Z3950, pqf_query);
2111 yaz_log (LOG_WARN, "bad query %s\n", pqf_query);
2113 res=zebra_search_RPN (zh, odr, query, setname, &hits);
2117 yaz_log(LOG_API,"Hits: %d",hits);
2125 /* ---------------------------------------------------------------------------
2126 Sort - a simplified interface, with optional read locks.
2127 FIXME - This is a horrible name, will conflict with half the applications
2129 int zebra_sort_by_specstr (ZebraHandle zh,
2131 const char *sort_spec,
2132 const char *output_setname,
2133 const char **input_setnames)
2135 int num_input_setnames = 0;
2136 int sort_status = 0;
2137 Z_SortKeySpecList *sort_sequence = yaz_sort_spec (stream, sort_spec);
2138 yaz_log(LOG_API,"sort (FIXME) ");
2141 logf(LOG_WARN,"invalid sort specs '%s'", sort_spec);
2146 /* we can do this, since the perl typemap code for char** will
2147 put a NULL at the end of list */
2148 while (input_setnames[num_input_setnames]) num_input_setnames++;
2150 if (zebra_begin_read (zh))
2153 resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
2154 output_setname, sort_sequence, &sort_status);
2160 void zebra_lock_prefix (Res res, char *path)
2162 const char *lock_dir = res_get_def (res, "lockDir", "");
2164 strcpy (path, lock_dir);
2165 if (*path && path[strlen(path)-1] != '/')