1 /* $Id: zebraapi.c,v 1.136 2004-10-15 10:07:32 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);
296 zebraRankInstall (reg, rankliv_class);
298 recordCompression = res_get_def (res, "recordCompression", "none");
299 if (!strcmp (recordCompression, "none"))
300 record_compression = REC_COMPRESS_NONE;
301 if (!strcmp (recordCompression, "bzip2"))
302 record_compression = REC_COMPRESS_BZIP2;
304 if (!(reg->records = rec_open (reg->bfs, rw, record_compression)))
306 logf (LOG_WARN, "rec_open");
311 reg->matchDict = dict_open_res (reg->bfs, GMATCH_DICT, 20, 1, 0, res);
313 if (!(reg->dict = dict_open_res (reg->bfs, FNAME_DICT, 40, rw, 0, res)))
315 logf (LOG_WARN, "dict_open");
318 if (!(reg->sortIdx = sortIdx_open (reg->bfs, rw)))
320 logf (LOG_WARN, "sortIdx_open");
323 if (res_get_match (res, "isam", "s", ISAM_DEFAULT))
325 struct ISAMS_M_s isams_m;
326 if (!(reg->isams = isams_open (reg->bfs, FNAME_ISAMS, rw,
327 key_isams_m(res, &isams_m))))
329 logf (LOG_WARN, "isams_open");
333 if (res_get_match (res, "isam", "c", ISAM_DEFAULT))
335 struct ISAMC_M_s isamc_m;
336 if (!(reg->isamc = isc_open (reg->bfs, FNAME_ISAMC,
337 rw, key_isamc_m(res, &isamc_m))))
339 logf (LOG_WARN, "isc_open");
343 if (res_get_match (res, "isam", "b", ISAM_DEFAULT))
345 struct ISAMC_M_s isamc_m;
347 if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
348 rw, key_isamc_m(res, &isamc_m), 0)))
350 logf (LOG_WARN, "isamb_open");
354 if (res_get_match (res, "isam", "bc", ISAM_DEFAULT))
356 struct ISAMC_M_s isamc_m;
358 if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
359 rw, key_isamc_m(res, &isamc_m), 1)))
361 logf (LOG_WARN, "isamb_open");
365 if (res_get_match (res, "isam", "null", ISAM_DEFAULT))
367 struct ISAMC_M_s isamc_m;
369 if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
370 rw, key_isamc_m(res, &isamc_m), -1)))
372 logf (LOG_WARN, "isamb_open");
376 reg->zei = zebraExplain_open (reg->records, reg->dh,
381 logf (LOG_WARN, "Cannot obtain EXPLAIN information");
385 yaz_log (LOG_DEBUG, "zebra_register_open ok p=%p", reg);
389 int zebra_admin_shutdown (ZebraHandle zh)
392 yaz_log(LOG_API,"zebra_admin_shutdown");
395 zebra_mutex_cond_lock (&zh->service->session_lock);
396 zh->service->stop_flag = 1;
397 zebra_mutex_cond_unlock (&zh->service->session_lock);
401 int zebra_admin_start (ZebraHandle zh)
405 yaz_log(LOG_API,"zebra_admin_start");
408 zebra_mutex_cond_lock (&zs->session_lock);
409 zebra_mutex_cond_unlock (&zs->session_lock);
413 static void zebra_register_close (ZebraService zs, struct zebra_register *reg)
417 yaz_log(LOG_DEBUG, "zebra_register_close p=%p", reg);
422 zebraExplain_close (reg->zei);
423 dict_close (reg->dict);
425 dict_close (reg->matchDict);
426 sortIdx_close (reg->sortIdx);
428 isams_close (reg->isams);
430 isc_close (reg->isamc);
432 isamb_close (reg->isamb);
433 rec_close (®->records);
436 recTypes_destroy (reg->recTypes);
437 zebra_maps_close (reg->zebra_maps);
438 zebraRankDestroy (reg);
439 bfs_destroy (reg->bfs);
440 data1_destroy (reg->dh);
442 xfree (reg->sortKeys.buf);
443 xfree (reg->keys.buf);
444 if (reg->keys.codec_handle)
445 iscz1_stop(reg->keys.codec_handle);
446 xfree (reg->key_buf);
451 int zebra_stop(ZebraService zs)
455 yaz_log (LOG_API, "zebra_stop");
459 zebra_close (zs->sessions);
462 zebra_mutex_cond_destroy (&zs->session_lock);
465 passwd_db_close (zs->passwd_db);
467 recTypeClass_destroy(zs->record_classes);
468 nmem_destroy(zs->nmem);
469 res_close (zs->global_res);
470 xfree (zs->configName);
475 int zebra_close (ZebraHandle zh)
478 struct zebra_session **sp;
481 yaz_log(LOG_API,"zebra_close");
488 yaz_log (LOG_DEBUG, "zebra_close zh=%p", zh);
489 resultSetDestroy (zh, -1, 0, 0);
492 zebra_register_close (zh->service, zh->reg);
493 zebra_close_res (zh);
495 xfree (zh->record_encoding);
497 for (i = 0; i < zh->num_basenames; i++)
498 xfree (zh->basenames[i]);
499 xfree (zh->basenames);
501 if (zh->iconv_to_utf8 != 0)
502 yaz_iconv_close (zh->iconv_to_utf8);
503 if (zh->iconv_from_utf8 != 0)
504 yaz_iconv_close (zh->iconv_from_utf8);
506 zebra_mutex_cond_lock (&zs->session_lock);
507 zebra_lock_destroy (zh->lock_normal);
508 zebra_lock_destroy (zh->lock_shadow);
520 zebra_mutex_cond_unlock (&zs->session_lock);
521 xfree (zh->reg_name);
522 xfree (zh->user_perm);
523 zh->service=0; /* more likely to trigger an assert */
524 xfree (zh->path_reg);
529 struct map_baseinfo {
535 char **new_basenames;
539 static Res zebra_open_res (ZebraHandle zh)
548 sprintf (fname, "%.200s/zebra.cfg", zh->path_reg);
549 res = res_open (fname, zh->service->global_res, 0);
551 res = zh->service->global_res;
553 else if (*zh->reg_name == 0)
555 res = zh->service->global_res;
559 yaz_log (LOG_WARN, "no register root specified");
560 return 0; /* no path for register - fail! */
565 static void zebra_close_res (ZebraHandle zh)
569 if (zh->res != zh->service->global_res)
574 static int zebra_select_register (ZebraHandle zh, const char *new_reg)
578 if (zh->res && strcmp (zh->reg_name, new_reg) == 0)
582 assert (zh->reg == 0);
583 assert (*zh->reg_name == 0);
589 resultSetInvalidate (zh);
590 zebra_register_close (zh->service, zh->reg);
595 xfree (zh->reg_name);
596 zh->reg_name = xstrdup (new_reg);
598 xfree (zh->path_reg);
600 if (zh->service->path_root)
602 zh->path_reg = xmalloc (strlen(zh->service->path_root) +
603 strlen(zh->reg_name) + 3);
604 strcpy (zh->path_reg, zh->service->path_root);
607 strcat (zh->path_reg, "/");
608 strcat (zh->path_reg, zh->reg_name);
611 zh->res = zebra_open_res (zh);
614 zebra_lock_destroy (zh->lock_normal);
618 zebra_lock_destroy (zh->lock_shadow);
624 const char *lock_area =res_get (zh->res, "lockDir");
626 if (!lock_area && zh->path_reg)
627 res_set (zh->res, "lockDir", zh->path_reg);
628 sprintf (fname, "norm.%s.LCK", zh->reg_name);
630 zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
632 sprintf (fname, "shadow.%s.LCK", zh->reg_name);
634 zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
640 void map_basenames_func (void *vp, const char *name, const char *value)
642 struct map_baseinfo *p = (struct map_baseinfo *) vp;
644 char fromdb[128], todb[8][128];
651 sscanf (value, "%127s %127s %127s %127s %127s %127s %127s %127s %127s",
652 fromdb, todb[0], todb[1], todb[2], todb[3], todb[4],
653 todb[5], todb[6], todb[7]);
657 for (i = 0; i<p->num_bases; i++)
658 if (p->basenames[i] && !STRCASECMP (p->basenames[i], fromdb))
661 for (i = 0; i < no; i++)
663 if (p->new_num_bases == p->new_num_max)
665 p->new_basenames[(p->new_num_bases)++] =
666 nmem_strdup (p->mem, todb[i]);
672 void map_basenames (ZebraHandle zh, ODR stream,
673 int *num_bases, char ***basenames)
675 struct map_baseinfo info;
676 struct map_baseinfo *p = &info;
679 yaz_log(LOG_API,"map_basenames ");
685 info.num_bases = *num_bases;
686 info.basenames = *basenames;
687 info.new_num_max = 128;
688 info.new_num_bases = 0;
689 info.new_basenames = (char **)
690 odr_malloc (stream, sizeof(*info.new_basenames) * info.new_num_max);
691 info.mem = stream->mem;
693 res_trav (zh->service->global_res, "mapdb", &info, map_basenames_func);
695 for (i = 0; i<p->num_bases; i++)
696 if (p->basenames[i] && p->new_num_bases < p->new_num_max)
698 p->new_basenames[(p->new_num_bases)++] =
699 nmem_strdup (p->mem, p->basenames[i]);
701 *num_bases = info.new_num_bases;
702 *basenames = info.new_basenames;
703 for (i = 0; i<*num_bases; i++)
704 logf (LOG_DEBUG, "base %s", (*basenames)[i]);
707 int zebra_select_database (ZebraHandle zh, const char *basename)
710 yaz_log(LOG_API,"zebra_select_database %s",basename);
713 return zebra_select_databases (zh, 1, &basename);
716 int zebra_select_databases (ZebraHandle zh, int num_bases,
717 const char **basenames)
726 yaz_log(LOG_API,"zebra_select_databases n=%d [0]=%s",
727 num_bases,basenames[0]);
735 for (i = 0; i < zh->num_basenames; i++)
736 xfree (zh->basenames[i]);
737 xfree (zh->basenames);
739 zh->num_basenames = num_bases;
740 zh->basenames = xmalloc (zh->num_basenames * sizeof(*zh->basenames));
741 for (i = 0; i < zh->num_basenames; i++)
742 zh->basenames[i] = xstrdup (basenames[i]);
744 cp = strrchr(basenames[0], '/');
747 len = cp - basenames[0];
748 new_reg = xmalloc (len + 1);
749 memcpy (new_reg, basenames[0], len);
753 new_reg = xstrdup ("");
754 for (i = 1; i<num_bases; i++)
758 cp1 = strrchr (basenames[i], '/');
766 if (len != cp1 - basenames[i] ||
767 memcmp (basenames[i], new_reg, len))
782 zebra_select_register (zh, new_reg);
789 if (!zh->lock_normal || !zh->lock_shadow)
797 int zebra_search_RPN (ZebraHandle zh, ODR o,
798 Z_RPNQuery *query, const char *setname, int *hits)
807 yaz_log(LOG_API,"zebra_search_rpn");
812 if (zebra_begin_read (zh))
815 zebra_livcode_transform(zh, query);
817 resultSetAddRPN (zh, odr_extract_mem(o), query,
818 zh->num_basenames, zh->basenames, setname);
821 max = res_get (zh->res, "maxhits");
826 maxhits=INT_MAX; /* properly rounded, to make it look like a limit*/
827 while (maxhits>100) { maxhits/=10; i++;}
828 while (i--) maxhits *= 10;
830 if (zh->hits > maxhits) { /* too large for yaz to handle */
831 logf(LOG_DEBUG,"limiting hits to "ZINT_FORMAT, maxhits);
839 int zebra_records_retrieve (ZebraHandle zh, ODR stream,
840 const char *setname, Z_RecordComposition *comp,
841 oid_value input_format, int num_recs,
842 ZebraRetrievalRecord *recs)
845 int i, *pos_array, ret = 0;
852 yaz_log(LOG_API,"zebra_records_retrieve n=%d",num_recs);
858 zh->errString = odr_strdup (stream, setname);
864 if (zebra_begin_read (zh))
867 pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
868 for (i = 0; i<num_recs; i++)
869 pos_array[i] = recs[i].position;
870 poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
873 logf (LOG_DEBUG, "zebraPosSetCreate error");
875 zh->errString = nmem_strdup (stream->mem, setname);
880 for (i = 0; i<num_recs; i++)
885 recs[i].format = VAL_SUTRS;
886 recs[i].len = strlen(poset[i].term);
887 recs[i].buf = poset[i].term;
888 recs[i].base = poset[i].db;
890 else if (poset[i].sysno)
893 zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
894 stream, input_format, comp,
895 &recs[i].format, &recs[i].buf,
898 recs[i].errString = NULL;
904 sprintf (num_str, "%d", pos_array[i]);
906 zh->errString = odr_strdup (stream, num_str);
911 zebraPosSetDestroy (zh, poset, num_recs);
918 int zebra_scan (ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
919 oid_value attributeset,
920 int *position, int *num_entries, ZebraScanEntry **entries,
930 yaz_log(LOG_API,"zebra_scan");
932 if (zebra_begin_read (zh))
938 rpn_scan (zh, stream, zapt, attributeset,
939 zh->num_basenames, zh->basenames, position,
940 num_entries, entries, is_partial, 0, 0);
945 int zebra_sort (ZebraHandle zh, ODR stream,
946 int num_input_setnames, const char **input_setnames,
947 const char *output_setname, Z_SortKeySpecList *sort_sequence,
952 assert(num_input_setnames>0);
953 assert(input_setnames);
954 assert(sort_sequence);
956 yaz_log(LOG_API,"zebra_sort");
958 if (zebra_begin_read (zh))
960 resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
961 output_setname, sort_sequence, sort_status);
966 int zebra_deleleResultSet(ZebraHandle zh, int function,
967 int num_setnames, char **setnames,
972 assert(num_setnames>0);
975 yaz_log(LOG_API,"zebra_deleleResultSet n=%d",num_setnames);
977 if (zebra_begin_read(zh))
978 return Z_DeleteStatus_systemProblemAtTarget;
981 case Z_DeleteResultSetRequest_list:
982 resultSetDestroy (zh, num_setnames, setnames, statuses);
984 case Z_DeleteResultSetRequest_all:
985 resultSetDestroy (zh, -1, 0, statuses);
989 status = Z_DeleteStatus_success;
990 for (i = 0; i<num_setnames; i++)
991 if (statuses[i] == Z_DeleteStatus_resultSetDidNotExist)
992 status = statuses[i];
996 int zebra_errCode (ZebraHandle zh)
1000 yaz_log(LOG_API,"zebra_errCode: %d",zh->errCode);
1003 yaz_log(LOG_API,"zebra_errCode: o");
1007 const char *zebra_errString (ZebraHandle zh)
1011 e= diagbib1_str (zh->errCode);
1012 yaz_log(LOG_API,"zebra_errString: %s",e);
1016 char *zebra_errAdd (ZebraHandle zh)
1021 yaz_log(LOG_API,"zebra_errAdd: %s",a);
1025 void zebra_clearError(ZebraHandle zh)
1034 int zebra_auth (ZebraHandle zh, const char *user, const char *pass)
1044 sprintf(u, "perm.%.30s", user ? user : "anonymous");
1045 p = res_get(zs->global_res, u);
1046 xfree (zh->user_perm);
1047 zh->user_perm = xstrdup(p ? p : "r");
1049 /* users that don't require a password .. */
1050 if (zh->user_perm && strchr(zh->user_perm, 'a'))
1053 if (!zs->passwd_db || !passwd_db_auth (zs->passwd_db, user, pass))
1058 int zebra_admin_import_begin (ZebraHandle zh, const char *database,
1059 const char *record_type)
1062 yaz_log(LOG_API,"zebra_admin_import_begin db=%s rt=%s",
1063 database, record_type);
1065 if (zebra_select_database(zh, database))
1067 if (zebra_begin_trans (zh, 1))
1072 int zebra_admin_import_end (ZebraHandle zh)
1075 yaz_log(LOG_API,"zebra_admin_import_end");
1077 zebra_end_trans (zh);
1081 int zebra_admin_import_segment (ZebraHandle zh, Z_Segment *segment)
1086 yaz_log(LOG_API,"zebra_admin_import_segment");
1088 for (i = 0; i<segment->num_segmentRecords; i++)
1090 Z_NamePlusRecord *npr = segment->segmentRecords[i];
1092 printf ("--------------%d--------------------\n", i);
1093 /* FIXME - What! printing on stdout ??? */
1094 if (npr->which == Z_NamePlusRecord_intermediateFragment)
1096 Z_FragmentSyntax *fragment = npr->u.intermediateFragment;
1097 if (fragment->which == Z_FragmentSyntax_notExternallyTagged)
1099 Odr_oct *oct = fragment->u.notExternallyTagged;
1100 printf ("%.*s", (oct->len > 100 ? 100 : oct->len) ,
1105 zebra_update_record(zh,
1106 0, /* record Type */
1118 int zebra_admin_exchange_record (ZebraHandle zh,
1119 const char *rec_buf,
1121 const char *recid_buf, size_t recid_len,
1123 /* 1 = insert. Fail it already exists */
1124 /* 2 = replace. Fail it does not exist */
1125 /* 3 = delete. Fail if does not exist */
1126 /* 4 = update. Insert/replace */
1132 assert(action>0 && action <=4);
1135 yaz_log(LOG_API,"zebra_admin_exchange_record ac=%d", action);
1138 if (!recid_buf || recid_len <= 0 || recid_len >= sizeof(recid_z))
1140 memcpy (recid_z, recid_buf, recid_len);
1141 recid_z[recid_len] = 0;
1143 if (zebra_begin_trans(zh, 1))
1146 rinfo = dict_lookup (zh->reg->matchDict, recid_z);
1149 if (action == 1) /* fail if insert */
1151 zebra_end_trans(zh);
1155 memcpy (&sysno, rinfo+1, sizeof(sysno));
1159 if (action == 2 || action == 3) /* fail if delete or update */
1161 zebra_end_trans(zh);
1164 action = 1; /* make it an insert (if it's an update).. */
1166 buffer_extract_record (zh, rec_buf, rec_len,
1167 action == 3 ? 1 : 0 /* delete flag */,
1173 0, /* force update */
1174 1 /* allow update */
1178 dict_insert (zh->reg->matchDict, recid_z, sizeof(sysno), &sysno);
1180 else if (action == 3)
1182 dict_delete (zh->reg->matchDict, recid_z);
1184 zebra_end_trans(zh);
1188 int delete_w_handle(const char *info, void *handle)
1190 ZebraHandle zh = (ZebraHandle) handle;
1194 if (*info == sizeof(pos))
1196 memcpy (&pos, info+1, sizeof(pos));
1197 isamb_unlink(zh->reg->isamb, pos);
1202 static int delete_SU_handle(void *handle, int ord)
1204 ZebraHandle zh = (ZebraHandle) handle;
1208 ord_len = key_SU_encode (ord, ord_buf);
1209 ord_buf[ord_len] = '\0';
1211 assert (zh->reg->isamb);
1212 dict_delete_subtree(zh->reg->dict, ord_buf,
1213 zh, delete_w_handle);
1217 int zebra_drop_database (ZebraHandle zh, const char *database)
1221 yaz_log(LOG_API,"zebra_drop_database");
1224 if (zebra_select_database (zh, database))
1226 if (zebra_begin_trans (zh, 1))
1230 zebraExplain_curDatabase (zh->reg->zei, database);
1232 zebraExplain_trav_ord(zh->reg->zei, zh, delete_SU_handle);
1233 zebraExplain_removeDatabase(zh->reg->zei, zh);
1237 yaz_log(LOG_WARN, "drop database only supported for isam:b");
1240 zebra_end_trans (zh);
1244 int zebra_create_database (ZebraHandle zh, const char *database)
1247 yaz_log(LOG_API,"zebra_create_database %s",database);
1251 if (zebra_select_database (zh, database))
1253 if (zebra_begin_trans (zh, 1))
1256 /* announce database */
1257 if (zebraExplain_newDatabase (zh->reg->zei, database, 0
1258 /* explainDatabase */))
1260 zebra_end_trans (zh);
1262 zh->errString = "database already exist";
1265 zebra_end_trans (zh);
1269 int zebra_string_norm (ZebraHandle zh, unsigned reg_id,
1270 const char *input_str, int input_len,
1271 char *output_str, int output_len)
1277 yaz_log(LOG_API,"zebra_string_norm ");
1279 if (!zh->reg->zebra_maps)
1281 wrbuf = zebra_replace(zh->reg->zebra_maps, reg_id, "",
1282 input_str, input_len);
1285 if (wrbuf_len(wrbuf) >= output_len)
1287 if (wrbuf_len(wrbuf))
1288 memcpy (output_str, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
1289 output_str[wrbuf_len(wrbuf)] = '\0';
1290 return wrbuf_len(wrbuf);
1294 int zebra_set_state (ZebraHandle zh, int val, int seqno)
1295 /* FIXME - zint seqno ?? */
1297 char state_fname[256];
1302 yaz_log(LOG_API,"zebra_set_state v=%d seq=%d", val, seqno);
1305 sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1306 fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1307 f = fopen (fname, "w");
1309 yaz_log (LOG_DEBUG, "zebra_set_state: %c %d %ld", val, seqno, p);
1310 fprintf (f, "%c %d %ld\n", val, seqno, p);
1316 int zebra_get_state (ZebraHandle zh, char *val, int *seqno)
1318 char state_fname[256];
1323 yaz_log(LOG_API,"zebra_get_state ");
1325 sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1326 fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1327 f = fopen (fname, "r");
1333 fscanf (f, "%c %d", val, seqno);
1340 int zebra_begin_read (ZebraHandle zh)
1342 return zebra_begin_trans(zh, 0);
1345 int zebra_end_read (ZebraHandle zh)
1347 return zebra_end_trans(zh);
1350 static void read_res_for_transaction(ZebraHandle zh)
1352 const char *group = res_get(zh->res, "group");
1354 /* FIXME - do we still use groups ?? */
1356 zh->m_group = group;
1357 v = res_get_prefix(zh->res, "followLinks", group, "1");
1358 zh->m_follow_links = atoi(v);
1360 zh->m_record_id = res_get_prefix(zh->res, "recordId", group, 0);
1361 zh->m_record_type = res_get_prefix(zh->res, "recordType", group, 0);
1363 v = res_get_prefix(zh->res, "storeKeys", group, "1");
1364 zh->m_store_keys = atoi(v);
1366 v = res_get_prefix(zh->res, "storeData", group, "1");
1367 zh->m_store_data = atoi(v);
1369 v = res_get_prefix(zh->res, "explainDatabase", group, "0");
1370 zh->m_explain_database = atoi(v);
1372 v = res_get_prefix(zh->res, "openRW", group, "1");
1373 zh->m_flag_rw = atoi(v);
1375 v = res_get_prefix(zh->res, "fileVerboseLimit", group, "100000");
1376 zh->m_file_verbose_limit = atoi(v);
1379 int zebra_begin_trans (ZebraHandle zh, int rw)
1385 zh->errString = "zebra_begin_trans: no database selected";
1389 yaz_log(LOG_API,"zebra_begin_trans rw=%d",rw);
1393 if (rw && !strchr(zh->user_perm, 'w'))
1407 const char *rval = 0;
1412 read_res_for_transaction(zh);
1415 if (zh->trans_no != 1)
1418 zh->errString = "zebra_begin_trans: write trans not allowed within read trans";
1423 resultSetInvalidate (zh);
1424 zebra_register_close (zh->service, zh->reg);
1426 zh->trans_w_no = zh->trans_no;
1430 zh->records_inserted = 0;
1431 zh->records_updated = 0;
1432 zh->records_deleted = 0;
1433 zh->records_processed = 0;
1435 #if HAVE_SYS_TIMES_H
1439 if (zh->shadow_enable)
1440 rval = res_get (zh->res, "shadow");
1442 for (pass = 0; pass < 2; pass++)
1446 zebra_lock_r (zh->lock_normal);
1447 zebra_lock_w (zh->lock_shadow);
1451 zebra_lock_w (zh->lock_normal);
1452 zebra_lock_w (zh->lock_shadow);
1455 zebra_get_state (zh, &val, &seqno);
1458 yaz_log (LOG_WARN, "previous transaction didn't finish commit");
1459 zebra_unlock (zh->lock_shadow);
1460 zebra_unlock (zh->lock_normal);
1464 else if (val == 'd')
1468 BFiles bfs = bfs_create (res_get (zh->res, "shadow"),
1470 yaz_log (LOG_WARN, "previous transaction didn't reach commit");
1471 bf_commitClean (bfs, rval);
1476 yaz_log (LOG_WARN, "your previous transaction didn't finish");
1483 yaz_log (LOG_FATAL, "zebra_begin_trans couldn't finish commit");
1487 zebra_set_state (zh, 'd', seqno);
1489 zh->reg = zebra_register_open (zh->service, zh->reg_name,
1490 1, rval ? 1 : 0, zh->res,
1493 zh->reg->seqno = seqno;
1496 zebra_set_state (zh, 'o', seqno);
1498 zebra_unlock (zh->lock_shadow);
1499 zebra_unlock (zh->lock_normal);
1505 zh->errString = "zebra_begin_trans: cannot open register";
1506 yaz_log(LOG_FATAL, zh->errString);
1518 if (zh->trans_no != 1)
1520 zebra_flush_reg (zh);
1524 #if HAVE_SYS_TIMES_H
1533 if (!zh->lock_normal || !zh->lock_shadow)
1539 zebra_get_state (zh, &val, &seqno);
1545 else if (seqno != zh->reg->seqno)
1547 yaz_log (LOG_DEBUG, "reopen seqno cur/old %d/%d",
1548 seqno, zh->reg->seqno);
1551 else if (zh->reg->last_val != val)
1553 yaz_log (LOG_DEBUG, "reopen last cur/old %d/%d",
1554 val, zh->reg->last_val);
1561 zebra_lock_r (zh->lock_shadow);
1563 zebra_lock_r (zh->lock_normal);
1567 resultSetInvalidate (zh);
1568 zebra_register_close (zh->service, zh->reg);
1570 zh->reg = zebra_register_open (zh->service, zh->reg_name,
1571 0, val == 'c' ? 1 : 0,
1572 zh->res, zh->path_reg);
1575 zebra_unlock (zh->lock_normal);
1576 zebra_unlock (zh->lock_shadow);
1581 zh->reg->last_val = val;
1582 zh->reg->seqno = seqno;
1584 read_res_for_transaction(zh);
1588 int zebra_end_trans (ZebraHandle zh)
1591 ZebraTransactionStatus dummy;
1592 yaz_log(LOG_API,"zebra_end_trans");
1593 return zebra_end_transaction(zh, &dummy);
1596 int zebra_end_transaction (ZebraHandle zh, ZebraTransactionStatus *status)
1604 yaz_log(LOG_API,"zebra_end_transaction");
1606 status->processed = 0;
1607 status->inserted = 0;
1608 status->updated = 0;
1609 status->deleted = 0;
1613 if (!zh->res || !zh->reg)
1616 zh->errString = "zebra_end_trans: no open transaction";
1619 if (zh->trans_no != zh->trans_w_no)
1622 if (zh->trans_no != 0)
1625 /* release read lock */
1627 zebra_unlock (zh->lock_normal);
1628 zebra_unlock (zh->lock_shadow);
1631 { /* release write lock */
1635 yaz_log (LOG_DEBUG, "zebra_end_trans");
1636 rval = res_get (zh->res, "shadow");
1638 zebraExplain_runNumberIncrement (zh->reg->zei, 1);
1640 zebra_flush_reg (zh);
1642 resultSetInvalidate (zh);
1644 zebra_register_close (zh->service, zh->reg);
1647 yaz_log (LOG_LOG, "Records: "ZINT_FORMAT" i/u/d "
1648 ZINT_FORMAT"/"ZINT_FORMAT"/"ZINT_FORMAT,
1649 zh->records_processed, zh->records_inserted,
1650 zh->records_updated, zh->records_deleted);
1652 status->processed = zh->records_processed;
1653 status->inserted = zh->records_inserted;
1654 status->updated = zh->records_updated;
1655 status->deleted = zh->records_deleted;
1657 zebra_get_state (zh, &val, &seqno);
1660 BFiles bfs = bfs_create (rval, zh->path_reg);
1661 yaz_log (LOG_DEBUG, "deleting shadow val=%c", val);
1662 bf_commitClean (bfs, rval);
1667 zebra_set_state (zh, 'o', seqno);
1669 zebra_unlock (zh->lock_shadow);
1670 zebra_unlock (zh->lock_normal);
1673 #if HAVE_SYS_TIMES_H
1675 logf (LOG_LOG, "user/system: %ld/%ld",
1676 (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1677 (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1679 status->utime = (long) (zh->tms2.tms_utime - zh->tms1.tms_utime);
1680 status->stime = (long) (zh->tms2.tms_stime - zh->tms1.tms_stime);
1685 int zebra_repository_update (ZebraHandle zh, const char *path)
1690 logf (LOG_API, "updating %s", path);
1691 repositoryUpdate (zh, path);
1695 int zebra_repository_delete (ZebraHandle zh, const char *path)
1700 logf (LOG_API, "deleting %s", path);
1701 repositoryDelete (zh, path);
1705 int zebra_repository_show (ZebraHandle zh, const char *path)
1709 yaz_log(LOG_API,"zebra_repository_show");
1711 repositoryShow (zh, path);
1715 static int zebra_commit_ex (ZebraHandle zh, int clean_only)
1729 rval = res_get (zh->res, "shadow");
1732 logf (LOG_WARN, "Cannot perform commit");
1733 logf (LOG_WARN, "No shadow area defined");
1737 zebra_lock_w (zh->lock_normal);
1738 zebra_lock_r (zh->lock_shadow);
1740 bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1742 zebra_get_state (zh, &val, &seqno);
1745 bf_cache (bfs, rval);
1746 if (bf_commitExists (bfs))
1749 zebra_set_state (zh, 'd', seqno);
1752 zebra_set_state (zh, 'c', seqno);
1754 logf (LOG_DEBUG, "commit start");
1755 bf_commitExec (bfs);
1760 logf (LOG_DEBUG, "commit clean");
1761 bf_commitClean (bfs, rval);
1763 zebra_set_state (zh, 'o', seqno);
1767 logf (LOG_LOG, "nothing to commit");
1771 zebra_unlock (zh->lock_shadow);
1772 zebra_unlock (zh->lock_normal);
1776 int zebra_clean (ZebraHandle zh)
1779 yaz_log(LOG_API,"zebra_clean");
1780 return zebra_commit_ex(zh, 1);
1783 int zebra_commit (ZebraHandle zh)
1786 yaz_log(LOG_API,"zebra_commit");
1787 return zebra_commit_ex(zh, 0);
1790 int zebra_init (ZebraHandle zh)
1795 yaz_log(LOG_API,"zebra_init");
1803 rval = res_get (zh->res, "shadow");
1805 bfs = bfs_create (res_get (zh->service->global_res, "register"),
1810 bf_cache (bfs, rval);
1814 zebra_set_state (zh, 'o', 0);
1818 int zebra_compact (ZebraHandle zh)
1822 yaz_log(LOG_API,"zebra_compact");
1829 bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1835 int zebra_result (ZebraHandle zh, int *code, char **addinfo)
1838 yaz_log(LOG_API,"zebra_result");
1839 *code = zh->errCode;
1840 *addinfo = zh->errString;
1844 int zebra_shadow_enable (ZebraHandle zh, int value)
1847 yaz_log(LOG_API,"zebra_shadow_enable");
1849 zh->shadow_enable = value;
1853 int zebra_record_encoding (ZebraHandle zh, const char *encoding)
1857 yaz_log(LOG_API,"zebra_record_encoding");
1859 xfree (zh->record_encoding);
1863 * Something about charset aliases. Oleg???
1866 if (zh->iconv_to_utf8 != 0)
1867 yaz_iconv_close(zh->iconv_to_utf8);
1868 if (zh->iconv_from_utf8 != 0)
1869 yaz_iconv_close(zh->iconv_from_utf8);
1871 zh->record_encoding = xstrdup (encoding);
1873 logf(LOG_DEBUG, "Reset record encoding: %s", encoding);
1876 yaz_iconv_open ("UTF-8", encoding);
1877 if (zh->iconv_to_utf8 == 0)
1878 yaz_log (LOG_WARN, "iconv: %s to UTF-8 unsupported", encoding);
1879 zh->iconv_from_utf8 =
1880 yaz_iconv_open (encoding, "UTF-8");
1881 if (zh->iconv_to_utf8 == 0)
1882 yaz_log (LOG_WARN, "iconv: UTF-8 to %s unsupported", encoding);
1887 int zebra_set_resource(ZebraHandle zh, const char *name, const char *value)
1892 yaz_log(LOG_API,"zebra_set_resource %s:%s",name,value);
1894 res_set(zh->res, name, value);
1898 const char *zebra_get_resource(ZebraHandle zh,
1899 const char *name, const char *defaultvalue)
1904 assert(defaultvalue);
1905 v= res_get_def( zh->res, name, (char *)defaultvalue);
1907 yaz_log(LOG_API,"zebra_get_resource %s:%s",name,v);
1911 /* moved from zebra_api_ext.c by pop */
1912 /* FIXME: Should this really be public??? -Heikki */
1914 int zebra_trans_no (ZebraHandle zh)
1917 yaz_log(LOG_API,"zebra_trans_no");
1918 return zh->trans_no;
1921 int zebra_get_shadow_enable (ZebraHandle zh)
1924 yaz_log(LOG_API,"zebra_get_shadow_enable");
1925 return (zh->shadow_enable);
1928 int zebra_set_shadow_enable (ZebraHandle zh, int value)
1931 yaz_log(LOG_API,"zebra_set_shadow_enable %d",value);
1932 zh->shadow_enable = value;
1936 /* almost the same as zebra_records_retrieve ... but how did it work?
1937 I mean for multiple records ??? CHECK ??? */
1938 void api_records_retrieve (ZebraHandle zh, ODR stream,
1939 const char *setname, Z_RecordComposition *comp,
1940 oid_value input_format, int num_recs,
1941 ZebraRetrievalRecord *recs)
1951 yaz_log(LOG_API,"api_records_retrieve s=%s n=%d",setname,num_recs);
1956 zh->errString = odr_strdup (stream, setname);
1962 if (zebra_begin_read (zh))
1965 pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
1966 for (i = 0; i<num_recs; i++)
1967 pos_array[i] = recs[i].position;
1968 poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
1971 logf (LOG_DEBUG, "zebraPosSetCreate error");
1973 zh->errString = nmem_strdup (stream->mem, setname);
1977 for (i = 0; i<num_recs; i++)
1981 recs[i].errCode = 0;
1982 recs[i].format = VAL_SUTRS;
1983 recs[i].len = strlen(poset[i].term);
1984 recs[i].buf = poset[i].term;
1985 recs[i].base = poset[i].db;
1989 else if (poset[i].sysno)
1991 /* changed here ??? CHECK ??? */
1994 zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
1995 stream, input_format, comp,
2000 recs[i].buf = (char *) odr_malloc(stream,recs[i].len);
2001 memcpy(recs[i].buf, b, recs[i].len);
2002 recs[i].errString = 0; /* Hmmm !!! we should get this */
2003 recs[i].sysno = poset[i].sysno;
2004 recs[i].score = poset[i].score;
2010 sprintf (num_str, "%d", pos_array[i]);
2012 zh->errString = odr_strdup (stream, num_str);
2017 zebraPosSetDestroy (zh, poset, num_recs);
2019 zebra_end_read (zh);
2024 /* ---------------------------------------------------------------------------
2025 Record insert(=update), delete
2027 If sysno is provided, then it's used to identify the record.
2028 If not, and match_criteria is provided, then sysno is guessed
2029 If not, and a record is provided, then sysno is got from there
2030 NOTE: Now returns 0 at success and updates sysno, which is an int*
2034 int zebra_add_record(ZebraHandle zh,
2035 const char *buf, int buf_size)
2038 return zebra_update_record(zh, 0, &sysno, 0, 0, buf, buf_size, 0);
2041 int zebra_insert_record (ZebraHandle zh,
2042 const char *recordType,
2043 SYSNO *sysno, const char *match, const char *fname,
2044 const char *buf, int buf_size, int force_update)
2050 yaz_log(LOG_API, "zebra_insert_record sysno=" ZINT_FORMAT, *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 0); /* allow_update */
2064 zebra_end_trans(zh);
2068 int zebra_update_record (ZebraHandle zh,
2069 const char *recordType,
2070 SYSNO* sysno, const char *match, const char *fname,
2071 const char *buf, int buf_size,
2079 yaz_log(LOG_API, "zebra_update_record sysno=" ZINT_FORMAT, *sysno);
2081 if (buf_size < 1) buf_size = strlen(buf);
2083 if (zebra_begin_trans(zh, 1))
2085 res = buffer_extract_record (zh, buf, buf_size,
2086 0, /* delete_flag */
2092 1); /* allow_update */
2093 zebra_end_trans(zh);
2097 int zebra_delete_record (ZebraHandle zh,
2098 const char *recordType,
2099 SYSNO *sysno, const char *match, const char *fname,
2100 const char *buf, int buf_size,
2107 yaz_log(LOG_API, "zebra_delete_record sysno=" ZINT_FORMAT, *sysno);
2109 if (buf_size < 1) buf_size = strlen(buf);
2111 if (zebra_begin_trans(zh, 1))
2113 res = buffer_extract_record (zh, buf, buf_size,
2114 1, /* delete_flag */
2120 1); /* allow_update */
2121 zebra_end_trans(zh);
2125 /* ---------------------------------------------------------------------------
2129 int zebra_search_PQF (ZebraHandle zh, const char *pqf_query,
2130 const char *setname, int *numhits)
2135 ODR odr = odr_createmem(ODR_ENCODE);
2140 yaz_log(LOG_API,"zebra_search_PQF s=%s q=%s",setname, pqf_query);
2142 query = p_query_rpn (odr, PROTO_Z3950, pqf_query);
2145 yaz_log (LOG_WARN, "bad query %s\n", pqf_query);
2147 res=zebra_search_RPN (zh, odr, query, setname, &hits);
2151 yaz_log(LOG_API,"Hits: %d",hits);
2159 /* ---------------------------------------------------------------------------
2160 Sort - a simplified interface, with optional read locks.
2162 int zebra_sort_by_specstr (ZebraHandle zh,
2164 const char *sort_spec,
2165 const char *output_setname,
2166 const char **input_setnames)
2168 int num_input_setnames = 0;
2169 int sort_status = 0;
2170 Z_SortKeySpecList *sort_sequence;
2174 assert(output_setname);
2175 assert(input_setnames);
2176 sort_sequence = yaz_sort_spec (stream, sort_spec);
2177 yaz_log(LOG_API,"sort (FIXME) ");
2180 logf(LOG_WARN,"invalid sort specs '%s'", sort_spec);
2185 /* we can do this, since the perl typemap code for char** will
2186 put a NULL at the end of list */
2187 while (input_setnames[num_input_setnames]) num_input_setnames++;
2189 if (zebra_begin_read (zh))
2192 resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
2193 output_setname, sort_sequence, &sort_status);