1 /* $Id: zebraapi.c,v 1.132 2004-09-15 08:13:51 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;
266 reg->keys.codec_handle = iscz1_start();
268 reg->sortKeys.buf = 0;
269 reg->sortKeys.buf_max = 0;
280 reg->key_file_no = 0;
283 zebraRankInstall (reg, rank1_class);
284 zebraRankInstall (reg, rankzv_class);
285 zebraRankInstall (reg, rankliv_class);
287 recordCompression = res_get_def (res, "recordCompression", "none");
288 if (!strcmp (recordCompression, "none"))
289 record_compression = REC_COMPRESS_NONE;
290 if (!strcmp (recordCompression, "bzip2"))
291 record_compression = REC_COMPRESS_BZIP2;
293 if (!(reg->records = rec_open (reg->bfs, rw, record_compression)))
295 logf (LOG_WARN, "rec_open");
300 reg->matchDict = dict_open_res (reg->bfs, GMATCH_DICT, 20, 1, 0, res);
302 if (!(reg->dict = dict_open_res (reg->bfs, FNAME_DICT, 40, rw, 0, res)))
304 logf (LOG_WARN, "dict_open");
307 if (!(reg->sortIdx = sortIdx_open (reg->bfs, rw)))
309 logf (LOG_WARN, "sortIdx_open");
312 if (res_get_match (res, "isam", "s", ISAM_DEFAULT))
314 struct ISAMS_M_s isams_m;
315 if (!(reg->isams = isams_open (reg->bfs, FNAME_ISAMS, rw,
316 key_isams_m(res, &isams_m))))
318 logf (LOG_WARN, "isams_open");
322 if (res_get_match (res, "isam", "c", ISAM_DEFAULT))
324 struct ISAMC_M_s isamc_m;
325 if (!(reg->isamc = isc_open (reg->bfs, FNAME_ISAMC,
326 rw, key_isamc_m(res, &isamc_m))))
328 logf (LOG_WARN, "isc_open");
332 if (res_get_match (res, "isam", "b", ISAM_DEFAULT))
334 struct ISAMC_M_s isamc_m;
336 if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
337 rw, key_isamc_m(res, &isamc_m), 0)))
339 logf (LOG_WARN, "isamb_open");
343 if (res_get_match (res, "isam", "bc", 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), 1)))
350 logf (LOG_WARN, "isamb_open");
354 if (res_get_match (res, "isam", "null", 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 reg->zei = zebraExplain_open (reg->records, reg->dh,
370 logf (LOG_WARN, "Cannot obtain EXPLAIN information");
374 yaz_log (LOG_DEBUG, "zebra_register_open ok p=%p", reg);
378 int zebra_admin_shutdown (ZebraHandle zh)
381 yaz_log(LOG_API,"zebra_admin_shutdown");
384 zebra_mutex_cond_lock (&zh->service->session_lock);
385 zh->service->stop_flag = 1;
386 zebra_mutex_cond_unlock (&zh->service->session_lock);
390 int zebra_admin_start (ZebraHandle zh)
394 yaz_log(LOG_API,"zebra_admin_start");
397 zebra_mutex_cond_lock (&zs->session_lock);
398 zebra_mutex_cond_unlock (&zs->session_lock);
402 static void zebra_register_close (ZebraService zs, struct zebra_register *reg)
405 yaz_log(LOG_DEBUG, "zebra_register_close p=%p", reg);
410 zebraExplain_close (reg->zei);
411 dict_close (reg->dict);
413 dict_close (reg->matchDict);
414 sortIdx_close (reg->sortIdx);
416 isams_close (reg->isams);
418 isc_close (reg->isamc);
420 isamb_close (reg->isamb);
421 rec_close (®->records);
424 recTypes_destroy (reg->recTypes);
425 zebra_maps_close (reg->zebra_maps);
426 zebraRankDestroy (reg);
427 bfs_destroy (reg->bfs);
428 data1_destroy (reg->dh);
430 xfree (reg->sortKeys.buf);
431 xfree (reg->keys.buf);
432 if (reg->keys.codec_handle)
433 iscz1_stop(reg->keys.codec_handle);
434 xfree (reg->key_buf);
439 int zebra_stop(ZebraService zs)
443 yaz_log (LOG_API, "zebra_stop");
447 zebra_close (zs->sessions);
450 zebra_mutex_cond_destroy (&zs->session_lock);
453 passwd_db_close (zs->passwd_db);
455 res_close (zs->global_res);
456 xfree (zs->configName);
461 int zebra_close (ZebraHandle zh)
464 struct zebra_session **sp;
467 yaz_log(LOG_API,"zebra_close");
474 yaz_log (LOG_DEBUG, "zebra_close zh=%p", zh);
475 resultSetDestroy (zh, -1, 0, 0);
478 zebra_register_close (zh->service, zh->reg);
479 zebra_close_res (zh);
481 xfree (zh->record_encoding);
483 for (i = 0; i < zh->num_basenames; i++)
484 xfree (zh->basenames[i]);
485 xfree (zh->basenames);
487 if (zh->iconv_to_utf8 != 0)
488 yaz_iconv_close (zh->iconv_to_utf8);
489 if (zh->iconv_from_utf8 != 0)
490 yaz_iconv_close (zh->iconv_from_utf8);
492 zebra_mutex_cond_lock (&zs->session_lock);
493 zebra_lock_destroy (zh->lock_normal);
494 zebra_lock_destroy (zh->lock_shadow);
506 zebra_mutex_cond_unlock (&zs->session_lock);
507 xfree (zh->reg_name);
508 xfree (zh->user_perm);
509 zh->service=0; /* more likely to trigger an assert */
510 xfree (zh->path_reg);
515 struct map_baseinfo {
521 char **new_basenames;
525 static Res zebra_open_res (ZebraHandle zh)
534 sprintf (fname, "%.200s/zebra.cfg", zh->path_reg);
535 res = res_open (fname, zh->service->global_res, 0);
537 res = zh->service->global_res;
539 else if (*zh->reg_name == 0)
541 res = zh->service->global_res;
545 yaz_log (LOG_WARN, "no register root specified");
546 return 0; /* no path for register - fail! */
551 static void zebra_close_res (ZebraHandle zh)
555 if (zh->res != zh->service->global_res)
560 static int zebra_select_register (ZebraHandle zh, const char *new_reg)
564 if (zh->res && strcmp (zh->reg_name, new_reg) == 0)
568 assert (zh->reg == 0);
569 assert (*zh->reg_name == 0);
575 resultSetInvalidate (zh);
576 zebra_register_close (zh->service, zh->reg);
581 xfree (zh->reg_name);
582 zh->reg_name = xstrdup (new_reg);
584 xfree (zh->path_reg);
586 if (zh->service->path_root)
588 zh->path_reg = xmalloc (strlen(zh->service->path_root) +
589 strlen(zh->reg_name) + 3);
590 strcpy (zh->path_reg, zh->service->path_root);
593 strcat (zh->path_reg, "/");
594 strcat (zh->path_reg, zh->reg_name);
597 zh->res = zebra_open_res (zh);
600 zebra_lock_destroy (zh->lock_normal);
604 zebra_lock_destroy (zh->lock_shadow);
610 const char *lock_area =res_get (zh->res, "lockDir");
612 if (!lock_area && zh->path_reg)
613 res_set (zh->res, "lockDir", zh->path_reg);
614 sprintf (fname, "norm.%s.LCK", zh->reg_name);
616 zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
618 sprintf (fname, "shadow.%s.LCK", zh->reg_name);
620 zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
626 void map_basenames_func (void *vp, const char *name, const char *value)
628 struct map_baseinfo *p = (struct map_baseinfo *) vp;
630 char fromdb[128], todb[8][128];
633 sscanf (value, "%127s %127s %127s %127s %127s %127s %127s %127s %127s",
634 fromdb, todb[0], todb[1], todb[2], todb[3], todb[4],
635 todb[5], todb[6], todb[7]);
639 for (i = 0; i<p->num_bases; i++)
640 if (p->basenames[i] && !STRCASECMP (p->basenames[i], fromdb))
643 for (i = 0; i < no; i++)
645 if (p->new_num_bases == p->new_num_max)
647 p->new_basenames[(p->new_num_bases)++] =
648 nmem_strdup (p->mem, todb[i]);
654 void map_basenames (ZebraHandle zh, ODR stream,
655 int *num_bases, char ***basenames)
657 struct map_baseinfo info;
658 struct map_baseinfo *p = &info;
661 yaz_log(LOG_API,"map_basenames ");
665 info.num_bases = *num_bases;
666 info.basenames = *basenames;
667 info.new_num_max = 128;
668 info.new_num_bases = 0;
669 info.new_basenames = (char **)
670 odr_malloc (stream, sizeof(*info.new_basenames) * info.new_num_max);
671 info.mem = stream->mem;
673 res_trav (zh->service->global_res, "mapdb", &info, map_basenames_func);
675 for (i = 0; i<p->num_bases; i++)
676 if (p->basenames[i] && p->new_num_bases < p->new_num_max)
678 p->new_basenames[(p->new_num_bases)++] =
679 nmem_strdup (p->mem, p->basenames[i]);
681 *num_bases = info.new_num_bases;
682 *basenames = info.new_basenames;
683 for (i = 0; i<*num_bases; i++)
684 logf (LOG_DEBUG, "base %s", (*basenames)[i]);
687 int zebra_select_database (ZebraHandle zh, const char *basename)
690 yaz_log(LOG_API,"zebra_select_database %s",basename);
692 return zebra_select_databases (zh, 1, &basename);
695 int zebra_select_databases (ZebraHandle zh, int num_bases,
696 const char **basenames)
703 yaz_log(LOG_API,"zebra_select_databases n=%d [0]=%s",
704 num_bases,basenames[0]);
712 for (i = 0; i < zh->num_basenames; i++)
713 xfree (zh->basenames[i]);
714 xfree (zh->basenames);
716 zh->num_basenames = num_bases;
717 zh->basenames = xmalloc (zh->num_basenames * sizeof(*zh->basenames));
718 for (i = 0; i < zh->num_basenames; i++)
719 zh->basenames[i] = xstrdup (basenames[i]);
721 cp = strrchr(basenames[0], '/');
724 len = cp - basenames[0];
725 new_reg = xmalloc (len + 1);
726 memcpy (new_reg, basenames[0], len);
730 new_reg = xstrdup ("");
731 for (i = 1; i<num_bases; i++)
735 cp1 = strrchr (basenames[i], '/');
743 if (len != cp1 - basenames[i] ||
744 memcmp (basenames[i], new_reg, len))
759 zebra_select_register (zh, new_reg);
766 if (!zh->lock_normal || !zh->lock_shadow)
774 int zebra_search_RPN (ZebraHandle zh, ODR o,
775 Z_RPNQuery *query, const char *setname, int *hits)
780 yaz_log(LOG_API,"zebra_search_rpn");
785 if (zebra_begin_read (zh))
788 zebra_livcode_transform(zh, query);
790 resultSetAddRPN (zh, odr_extract_mem(o), query,
791 zh->num_basenames, zh->basenames, setname);
794 max = res_get (zh->res, "maxhits");
800 while (maxhits>100) { maxhits/=10; i++;}
801 while (i--) maxhits *= 10;
803 if (zh->hits > maxhits) { /* too large for yaz to handle */
804 logf(LOG_DEBUG,"limiting hits to "ZINT_FORMAT, maxhits);
805 *hits=maxhits; /* round it down to two digits, to look like rounded */
812 int zebra_records_retrieve (ZebraHandle zh, ODR stream,
813 const char *setname, Z_RecordComposition *comp,
814 oid_value input_format, int num_recs,
815 ZebraRetrievalRecord *recs)
818 int i, *pos_array, ret = 0;
820 yaz_log(LOG_API,"zebra_records_retrieve n=%d",num_recs);
826 zh->errString = odr_strdup (stream, setname);
832 if (zebra_begin_read (zh))
835 pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
836 for (i = 0; i<num_recs; i++)
837 pos_array[i] = recs[i].position;
838 poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
841 logf (LOG_DEBUG, "zebraPosSetCreate error");
843 zh->errString = nmem_strdup (stream->mem, setname);
848 for (i = 0; i<num_recs; i++)
853 recs[i].format = VAL_SUTRS;
854 recs[i].len = strlen(poset[i].term);
855 recs[i].buf = poset[i].term;
856 recs[i].base = poset[i].db;
858 else if (poset[i].sysno)
861 zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
862 stream, input_format, comp,
863 &recs[i].format, &recs[i].buf,
866 recs[i].errString = NULL;
872 sprintf (num_str, "%d", pos_array[i]);
874 zh->errString = odr_strdup (stream, num_str);
879 zebraPosSetDestroy (zh, poset, num_recs);
886 int zebra_scan (ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
887 oid_value attributeset,
888 int *position, int *num_entries, ZebraScanEntry **entries,
892 yaz_log(LOG_API,"zebra_scan");
894 if (zebra_begin_read (zh))
900 rpn_scan (zh, stream, zapt, attributeset,
901 zh->num_basenames, zh->basenames, position,
902 num_entries, entries, is_partial, 0, 0);
907 int zebra_sort (ZebraHandle zh, ODR stream,
908 int num_input_setnames, const char **input_setnames,
909 const char *output_setname, Z_SortKeySpecList *sort_sequence,
913 yaz_log(LOG_API,"zebra_sort");
915 if (zebra_begin_read (zh))
917 resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
918 output_setname, sort_sequence, sort_status);
923 int zebra_deleleResultSet(ZebraHandle zh, int function,
924 int num_setnames, char **setnames,
929 yaz_log(LOG_API,"zebra_deleleResultSet n=%d",num_setnames);
931 if (zebra_begin_read(zh))
932 return Z_DeleteStatus_systemProblemAtTarget;
935 case Z_DeleteResultSetRequest_list:
936 resultSetDestroy (zh, num_setnames, setnames, statuses);
938 case Z_DeleteResultSetRequest_all:
939 resultSetDestroy (zh, -1, 0, statuses);
943 status = Z_DeleteStatus_success;
944 for (i = 0; i<num_setnames; i++)
945 if (statuses[i] == Z_DeleteStatus_resultSetDidNotExist)
946 status = statuses[i];
950 int zebra_errCode (ZebraHandle zh)
954 yaz_log(LOG_API,"zebra_errCode: %d",zh->errCode);
957 yaz_log(LOG_API,"zebra_errCode: o");
961 const char *zebra_errString (ZebraHandle zh)
965 e= diagbib1_str (zh->errCode);
966 yaz_log(LOG_API,"zebra_errString: %s",e);
970 char *zebra_errAdd (ZebraHandle zh)
975 yaz_log(LOG_API,"zebra_errAdd: %s",a);
979 void zebra_clearError(ZebraHandle zh)
988 int zebra_auth (ZebraHandle zh, const char *user, const char *pass)
998 sprintf(u, "perm.%.30s", user ? user : "anonymous");
999 p = res_get(zs->global_res, u);
1000 xfree (zh->user_perm);
1001 zh->user_perm = xstrdup(p ? p : "r");
1003 /* users that don't require a password .. */
1004 if (zh->user_perm && strchr(zh->user_perm, 'a'))
1007 if (!zs->passwd_db || !passwd_db_auth (zs->passwd_db, user, pass))
1012 int zebra_admin_import_begin (ZebraHandle zh, const char *database,
1013 const char *record_type)
1016 yaz_log(LOG_API,"zebra_admin_import_begin db=%s rt=%s",
1017 database, record_type);
1019 if (zebra_select_database(zh, database))
1021 if (zebra_begin_trans (zh, 1))
1026 int zebra_admin_import_end (ZebraHandle zh)
1029 yaz_log(LOG_API,"zebra_admin_import_end");
1031 zebra_end_trans (zh);
1035 int zebra_admin_import_segment (ZebraHandle zh, Z_Segment *segment)
1040 yaz_log(LOG_API,"zebra_admin_import_segment");
1042 for (i = 0; i<segment->num_segmentRecords; i++)
1044 Z_NamePlusRecord *npr = segment->segmentRecords[i];
1046 printf ("--------------%d--------------------\n", i);
1047 if (npr->which == Z_NamePlusRecord_intermediateFragment)
1049 Z_FragmentSyntax *fragment = npr->u.intermediateFragment;
1050 if (fragment->which == Z_FragmentSyntax_notExternallyTagged)
1052 Odr_oct *oct = fragment->u.notExternallyTagged;
1053 printf ("%.*s", (oct->len > 100 ? 100 : oct->len) ,
1058 zebra_update_record(zh,
1059 0, /* record Type */
1071 int zebra_admin_exchange_record (ZebraHandle zh,
1072 const char *rec_buf,
1074 const char *recid_buf, size_t recid_len,
1076 /* 1 = insert. Fail it already exists */
1077 /* 2 = replace. Fail it does not exist */
1078 /* 3 = delete. Fail if does not exist */
1079 /* 4 = update. Insert/replace */
1085 yaz_log(LOG_API,"zebra_admin_exchange_record ac=%d", action);
1088 if (!recid_buf || recid_len <= 0 || recid_len >= sizeof(recid_z))
1090 memcpy (recid_z, recid_buf, recid_len);
1091 recid_z[recid_len] = 0;
1093 if (zebra_begin_trans(zh, 1))
1096 rinfo = dict_lookup (zh->reg->matchDict, recid_z);
1099 if (action == 1) /* fail if insert */
1101 zebra_end_trans(zh);
1105 memcpy (&sysno, rinfo+1, sizeof(sysno));
1109 if (action == 2 || action == 3) /* fail if delete or update */
1111 zebra_end_trans(zh);
1114 action = 1; /* make it an insert (if it's an update).. */
1116 buffer_extract_record (zh, rec_buf, rec_len,
1117 action == 3 ? 1 : 0 /* delete flag */,
1123 0, /* force update */
1124 1 /* allow update */
1128 dict_insert (zh->reg->matchDict, recid_z, sizeof(sysno), &sysno);
1130 else if (action == 3)
1132 dict_delete (zh->reg->matchDict, recid_z);
1134 zebra_end_trans(zh);
1138 int delete_w_handle(const char *info, void *handle)
1140 ZebraHandle zh = (ZebraHandle) handle;
1143 if (*info == sizeof(pos))
1145 memcpy (&pos, info+1, sizeof(pos));
1146 isamb_unlink(zh->reg->isamb, pos);
1151 static int delete_SU_handle(void *handle, int ord)
1153 ZebraHandle zh = (ZebraHandle) handle;
1157 ord_len = key_SU_encode (ord, ord_buf);
1158 ord_buf[ord_len] = '\0';
1160 assert (zh->reg->isamb);
1161 dict_delete_subtree(zh->reg->dict, ord_buf,
1162 zh, delete_w_handle);
1166 int zebra_drop_database (ZebraHandle zh, const char *database)
1170 yaz_log(LOG_API,"zebra_drop_database");
1173 if (zebra_select_database (zh, database))
1175 if (zebra_begin_trans (zh, 1))
1179 zebraExplain_curDatabase (zh->reg->zei, database);
1181 zebraExplain_trav_ord(zh->reg->zei, zh, delete_SU_handle);
1182 zebraExplain_removeDatabase(zh->reg->zei, zh);
1186 yaz_log(LOG_WARN, "drop database only supported for isam:b");
1189 zebra_end_trans (zh);
1193 int zebra_create_database (ZebraHandle zh, const char *database)
1196 yaz_log(LOG_API,"zebra_create_database");
1199 if (zebra_select_database (zh, database))
1201 if (zebra_begin_trans (zh, 1))
1204 /* announce database */
1205 if (zebraExplain_newDatabase (zh->reg->zei, database, 0
1206 /* explainDatabase */))
1208 zebra_end_trans (zh);
1210 zh->errString = "database already exist";
1213 zebra_end_trans (zh);
1217 int zebra_string_norm (ZebraHandle zh, unsigned reg_id,
1218 const char *input_str, int input_len,
1219 char *output_str, int output_len)
1223 yaz_log(LOG_API,"zebra_string_norm ");
1225 if (!zh->reg->zebra_maps)
1227 wrbuf = zebra_replace(zh->reg->zebra_maps, reg_id, "",
1228 input_str, input_len);
1231 if (wrbuf_len(wrbuf) >= output_len)
1233 if (wrbuf_len(wrbuf))
1234 memcpy (output_str, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
1235 output_str[wrbuf_len(wrbuf)] = '\0';
1236 return wrbuf_len(wrbuf);
1240 int zebra_set_state (ZebraHandle zh, int val, int seqno)
1242 char state_fname[256];
1247 yaz_log(LOG_API,"zebra_set_state v=%d seq=%d", val, seqno);
1250 sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1251 fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1252 f = fopen (fname, "w");
1254 yaz_log (LOG_DEBUG, "%c %d %ld", val, seqno, p);
1255 fprintf (f, "%c %d %ld\n", val, seqno, p);
1261 int zebra_get_state (ZebraHandle zh, char *val, int *seqno)
1263 char state_fname[256];
1268 yaz_log(LOG_API,"zebra_get_state ");
1270 sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1271 fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1272 f = fopen (fname, "r");
1278 fscanf (f, "%c %d", val, seqno);
1285 int zebra_begin_read (ZebraHandle zh)
1287 return zebra_begin_trans(zh, 0);
1290 int zebra_end_read (ZebraHandle zh)
1292 return zebra_end_trans(zh);
1295 static void read_res_for_transaction(ZebraHandle zh)
1297 const char *group = res_get(zh->res, "group");
1300 zh->m_group = group;
1301 v = res_get_prefix(zh->res, "followLinks", group, "1");
1302 zh->m_follow_links = atoi(v);
1304 zh->m_record_id = res_get_prefix(zh->res, "recordId", group, 0);
1305 zh->m_record_type = res_get_prefix(zh->res, "recordType", group, 0);
1307 v = res_get_prefix(zh->res, "storeKeys", group, "1");
1308 zh->m_store_keys = atoi(v);
1310 v = res_get_prefix(zh->res, "storeData", group, "1");
1311 zh->m_store_data = atoi(v);
1313 v = res_get_prefix(zh->res, "explainDatabase", group, "0");
1314 zh->m_explain_database = atoi(v);
1316 v = res_get_prefix(zh->res, "openRW", group, "1");
1317 zh->m_flag_rw = atoi(v);
1319 v = res_get_prefix(zh->res, "fileVerboseLimit", group, "100000");
1320 zh->m_file_verbose_limit = atoi(v);
1323 int zebra_begin_trans (ZebraHandle zh, int rw)
1328 zh->errString = "zebra_begin_trans: no database selected";
1332 yaz_log(LOG_API,"zebra_begin_trans rw=%d",rw);
1336 if (rw && !strchr(zh->user_perm, 'w'))
1350 const char *rval = 0;
1355 read_res_for_transaction(zh);
1358 if (zh->trans_no != 1)
1361 zh->errString = "zebra_begin_trans: write trans not allowed within read trans";
1366 resultSetInvalidate (zh);
1367 zebra_register_close (zh->service, zh->reg);
1369 zh->trans_w_no = zh->trans_no;
1373 zh->records_inserted = 0;
1374 zh->records_updated = 0;
1375 zh->records_deleted = 0;
1376 zh->records_processed = 0;
1378 #if HAVE_SYS_TIMES_H
1382 if (zh->shadow_enable)
1383 rval = res_get (zh->res, "shadow");
1385 for (pass = 0; pass < 2; pass++)
1389 zebra_lock_r (zh->lock_normal);
1390 zebra_lock_w (zh->lock_shadow);
1394 zebra_lock_w (zh->lock_normal);
1395 zebra_lock_w (zh->lock_shadow);
1398 zebra_get_state (zh, &val, &seqno);
1401 yaz_log (LOG_WARN, "previous transaction didn't finish commit");
1402 zebra_unlock (zh->lock_shadow);
1403 zebra_unlock (zh->lock_normal);
1407 else if (val == 'd')
1411 BFiles bfs = bfs_create (res_get (zh->res, "shadow"),
1413 yaz_log (LOG_WARN, "previous transaction didn't reach commit");
1414 bf_commitClean (bfs, rval);
1419 yaz_log (LOG_WARN, "your previous transaction didn't finish");
1426 yaz_log (LOG_FATAL, "zebra_begin_trans couldn't finish commit");
1430 zebra_set_state (zh, 'd', seqno);
1432 zh->reg = zebra_register_open (zh->service, zh->reg_name,
1433 1, rval ? 1 : 0, zh->res,
1436 zh->reg->seqno = seqno;
1439 zebra_set_state (zh, 'o', seqno);
1441 zebra_unlock (zh->lock_shadow);
1442 zebra_unlock (zh->lock_normal);
1448 zh->errString = "zebra_begin_trans: cannot open register";
1449 yaz_log(LOG_FATAL, zh->errString);
1461 if (zh->trans_no != 1)
1463 zebra_flush_reg (zh);
1467 #if HAVE_SYS_TIMES_H
1476 if (!zh->lock_normal || !zh->lock_shadow)
1482 zebra_get_state (zh, &val, &seqno);
1488 else if (seqno != zh->reg->seqno)
1490 yaz_log (LOG_DEBUG, "reopen seqno cur/old %d/%d",
1491 seqno, zh->reg->seqno);
1494 else if (zh->reg->last_val != val)
1496 yaz_log (LOG_DEBUG, "reopen last cur/old %d/%d",
1497 val, zh->reg->last_val);
1504 zebra_lock_r (zh->lock_shadow);
1506 zebra_lock_r (zh->lock_normal);
1510 resultSetInvalidate (zh);
1511 zebra_register_close (zh->service, zh->reg);
1513 zh->reg = zebra_register_open (zh->service, zh->reg_name,
1514 0, val == 'c' ? 1 : 0,
1515 zh->res, zh->path_reg);
1518 zebra_unlock (zh->lock_normal);
1519 zebra_unlock (zh->lock_shadow);
1524 zh->reg->last_val = val;
1525 zh->reg->seqno = seqno;
1527 read_res_for_transaction(zh);
1531 int zebra_end_trans (ZebraHandle zh)
1533 ZebraTransactionStatus dummy;
1534 yaz_log(LOG_API,"zebra_end_trans");
1535 return zebra_end_transaction(zh, &dummy);
1538 int zebra_end_transaction (ZebraHandle zh, ZebraTransactionStatus *status)
1545 yaz_log(LOG_API,"zebra_end_transaction");
1547 status->processed = 0;
1548 status->inserted = 0;
1549 status->updated = 0;
1550 status->deleted = 0;
1554 if (!zh->res || !zh->reg)
1557 zh->errString = "zebra_end_trans: no open transaction";
1560 if (zh->trans_no != zh->trans_w_no)
1563 if (zh->trans_no != 0)
1566 /* release read lock */
1568 zebra_unlock (zh->lock_normal);
1569 zebra_unlock (zh->lock_shadow);
1572 { /* release write lock */
1576 yaz_log (LOG_DEBUG, "zebra_end_trans");
1577 rval = res_get (zh->res, "shadow");
1579 zebraExplain_runNumberIncrement (zh->reg->zei, 1);
1581 zebra_flush_reg (zh);
1583 resultSetInvalidate (zh);
1585 zebra_register_close (zh->service, zh->reg);
1588 yaz_log (LOG_LOG, "Records: "ZINT_FORMAT" i/u/d "
1589 ZINT_FORMAT"/"ZINT_FORMAT"/"ZINT_FORMAT,
1590 zh->records_processed, zh->records_inserted,
1591 zh->records_updated, zh->records_deleted);
1593 status->processed = zh->records_processed;
1594 status->inserted = zh->records_inserted;
1595 status->updated = zh->records_updated;
1596 status->deleted = zh->records_deleted;
1598 zebra_get_state (zh, &val, &seqno);
1601 BFiles bfs = bfs_create (rval, zh->path_reg);
1602 yaz_log (LOG_DEBUG, "deleting shadow val=%c", val);
1603 bf_commitClean (bfs, rval);
1608 zebra_set_state (zh, 'o', seqno);
1610 zebra_unlock (zh->lock_shadow);
1611 zebra_unlock (zh->lock_normal);
1614 #if HAVE_SYS_TIMES_H
1616 logf (LOG_LOG, "user/system: %ld/%ld",
1617 (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1618 (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1620 status->utime = (long) (zh->tms2.tms_utime - zh->tms1.tms_utime);
1621 status->stime = (long) (zh->tms2.tms_stime - zh->tms1.tms_stime);
1626 int zebra_repository_update (ZebraHandle zh, const char *path)
1630 logf (LOG_API, "updating %s", path);
1631 repositoryUpdate (zh, path);
1635 int zebra_repository_delete (ZebraHandle zh, const char *path)
1639 logf (LOG_API, "deleting %s", path);
1640 repositoryDelete (zh, path);
1644 int zebra_repository_show (ZebraHandle zh, const char *path)
1647 yaz_log(LOG_API,"zebra_repository_show");
1649 repositoryShow (zh, path);
1653 static int zebra_commit_ex (ZebraHandle zh, int clean_only)
1667 rval = res_get (zh->res, "shadow");
1670 logf (LOG_WARN, "Cannot perform commit");
1671 logf (LOG_WARN, "No shadow area defined");
1675 zebra_lock_w (zh->lock_normal);
1676 zebra_lock_r (zh->lock_shadow);
1678 bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1680 zebra_get_state (zh, &val, &seqno);
1683 bf_cache (bfs, rval);
1684 if (bf_commitExists (bfs))
1687 zebra_set_state (zh, 'd', seqno);
1690 zebra_set_state (zh, 'c', seqno);
1692 logf (LOG_DEBUG, "commit start");
1693 bf_commitExec (bfs);
1698 logf (LOG_DEBUG, "commit clean");
1699 bf_commitClean (bfs, rval);
1701 zebra_set_state (zh, 'o', seqno);
1705 logf (LOG_LOG, "nothing to commit");
1709 zebra_unlock (zh->lock_shadow);
1710 zebra_unlock (zh->lock_normal);
1714 int zebra_clean (ZebraHandle zh)
1716 yaz_log(LOG_API,"zebra_clean");
1717 return zebra_commit_ex(zh, 1);
1720 int zebra_commit (ZebraHandle zh)
1722 yaz_log(LOG_API,"zebra_commit");
1723 return zebra_commit_ex(zh, 0);
1726 int zebra_init (ZebraHandle zh)
1731 yaz_log(LOG_API,"zebra_init");
1739 rval = res_get (zh->res, "shadow");
1741 bfs = bfs_create (res_get (zh->service->global_res, "register"),
1746 bf_cache (bfs, rval);
1750 zebra_set_state (zh, 'o', 0);
1754 int zebra_compact (ZebraHandle zh)
1758 yaz_log(LOG_API,"zebra_compact");
1765 bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1771 int zebra_result (ZebraHandle zh, int *code, char **addinfo)
1774 yaz_log(LOG_API,"zebra_result");
1775 *code = zh->errCode;
1776 *addinfo = zh->errString;
1780 int zebra_shadow_enable (ZebraHandle zh, int value)
1783 yaz_log(LOG_API,"zebra_shadow_enable");
1785 zh->shadow_enable = value;
1789 int zebra_record_encoding (ZebraHandle zh, const char *encoding)
1792 yaz_log(LOG_API,"zebra_record_encoding");
1794 xfree (zh->record_encoding);
1798 * Something about charset aliases. Oleg???
1801 if (zh->iconv_to_utf8 != 0)
1802 yaz_iconv_close(zh->iconv_to_utf8);
1803 if (zh->iconv_from_utf8 != 0)
1804 yaz_iconv_close(zh->iconv_from_utf8);
1806 zh->record_encoding = xstrdup (encoding);
1808 logf(LOG_DEBUG, "Reset record encoding: %s", encoding);
1811 yaz_iconv_open ("UTF-8", encoding);
1812 if (zh->iconv_to_utf8 == 0)
1813 yaz_log (LOG_WARN, "iconv: %s to UTF-8 unsupported", encoding);
1814 zh->iconv_from_utf8 =
1815 yaz_iconv_open (encoding, "UTF-8");
1816 if (zh->iconv_to_utf8 == 0)
1817 yaz_log (LOG_WARN, "iconv: UTF-8 to %s unsupported", encoding);
1822 int zebra_set_resource(ZebraHandle zh, const char *name, const char *value)
1825 yaz_log(LOG_API,"zebra_set_resource %s:%s",name,value);
1827 res_set(zh->res, name, value);
1831 const char *zebra_get_resource(ZebraHandle zh,
1832 const char *name, const char *defaultvalue)
1836 v= res_get_def( zh->res, name, (char *)defaultvalue);
1838 yaz_log(LOG_API,"zebra_get_resource %s:%s",name,v);
1842 /* moved from zebra_api_ext.c by pop */
1843 /* FIXME: Should this really be public??? -Heikki */
1845 int zebra_trans_no (ZebraHandle zh)
1848 yaz_log(LOG_API,"zebra_trans_no");
1849 return zh->trans_no;
1852 int zebra_get_shadow_enable (ZebraHandle zh)
1854 yaz_log(LOG_API,"zebra_get_shadow_enable");
1855 return (zh->shadow_enable);
1858 int zebra_set_shadow_enable (ZebraHandle zh, int value)
1860 yaz_log(LOG_API,"zebra_set_shadow_enable %d",value);
1861 zh->shadow_enable = value;
1865 /* almost the same as zebra_records_retrieve ... but how did it work?
1866 I mean for multiple records ??? CHECK ??? */
1867 void api_records_retrieve (ZebraHandle zh, ODR stream,
1868 const char *setname, Z_RecordComposition *comp,
1869 oid_value input_format, int num_recs,
1870 ZebraRetrievalRecord *recs)
1874 yaz_log(LOG_API,"api_records_retrieve s=%s n=%d",setname,num_recs);
1879 zh->errString = odr_strdup (stream, setname);
1885 if (zebra_begin_read (zh))
1888 pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
1889 for (i = 0; i<num_recs; i++)
1890 pos_array[i] = recs[i].position;
1891 poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
1894 logf (LOG_DEBUG, "zebraPosSetCreate error");
1896 zh->errString = nmem_strdup (stream->mem, setname);
1900 for (i = 0; i<num_recs; i++)
1904 recs[i].errCode = 0;
1905 recs[i].format = VAL_SUTRS;
1906 recs[i].len = strlen(poset[i].term);
1907 recs[i].buf = poset[i].term;
1908 recs[i].base = poset[i].db;
1912 else if (poset[i].sysno)
1914 /* changed here ??? CHECK ??? */
1917 zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
1918 stream, input_format, comp,
1923 recs[i].buf = (char *) odr_malloc(stream,recs[i].len);
1924 memcpy(recs[i].buf, b, recs[i].len);
1925 recs[i].errString = 0; /* Hmmm !!! we should get this */
1926 recs[i].sysno = poset[i].sysno;
1927 recs[i].score = poset[i].score;
1933 sprintf (num_str, "%d", pos_array[i]);
1935 zh->errString = odr_strdup (stream, num_str);
1940 zebraPosSetDestroy (zh, poset, num_recs);
1942 zebra_end_read (zh);
1947 /* ---------------------------------------------------------------------------
1948 Record insert(=update), delete
1950 If sysno is provided, then it's used to identify the record.
1951 If not, and match_criteria is provided, then sysno is guessed
1952 If not, and a record is provided, then sysno is got from there
1953 NOTE: Now returns 0 at success and updates sysno, which is an int*
1957 int zebra_add_record(ZebraHandle zh,
1958 const char *buf, int buf_size)
1961 return zebra_update_record(zh, 0, &sysno, 0, 0, buf, buf_size, 0);
1964 int zebra_insert_record (ZebraHandle zh,
1965 const char *recordType,
1966 SYSNO *sysno, const char *match, const char *fname,
1967 const char *buf, int buf_size, int force_update)
1970 yaz_log(LOG_API, "zebra_insert_record sysno=" ZINT_FORMAT, *sysno);
1972 if (buf_size < 1) buf_size = strlen(buf);
1974 if (zebra_begin_trans(zh, 1))
1976 res = buffer_extract_record (zh, buf, buf_size,
1977 0, /* delete_flag */
1983 0); /* allow_update */
1984 zebra_end_trans(zh);
1988 int zebra_update_record (ZebraHandle zh,
1989 const char *recordType,
1990 SYSNO* sysno, const char *match, const char *fname,
1991 const char *buf, int buf_size,
1996 yaz_log(LOG_API, "zebra_update_record sysno=" ZINT_FORMAT, *sysno);
1998 if (buf_size < 1) buf_size = strlen(buf);
2000 if (zebra_begin_trans(zh, 1))
2002 res = buffer_extract_record (zh, buf, buf_size,
2003 0, /* delete_flag */
2009 1); /* allow_update */
2010 zebra_end_trans(zh);
2014 int zebra_delete_record (ZebraHandle zh,
2015 const char *recordType,
2016 SYSNO *sysno, const char *match, const char *fname,
2017 const char *buf, int buf_size,
2021 yaz_log(LOG_API, "zebra_delete_record sysno=" ZINT_FORMAT, *sysno);
2023 if (buf_size < 1) buf_size = strlen(buf);
2025 if (zebra_begin_trans(zh, 1))
2027 res = buffer_extract_record (zh, buf, buf_size,
2028 1, /* delete_flag */
2034 1); /* allow_update */
2035 zebra_end_trans(zh);
2039 /* ---------------------------------------------------------------------------
2043 int zebra_search_PQF (ZebraHandle zh, const char *pqf_query,
2044 const char *setname, int *numhits)
2049 ODR odr = odr_createmem(ODR_ENCODE);
2051 yaz_log(LOG_API,"zebra_search_PQF s=%s q=%s",setname, pqf_query);
2053 query = p_query_rpn (odr, PROTO_Z3950, pqf_query);
2056 yaz_log (LOG_WARN, "bad query %s\n", pqf_query);
2058 res=zebra_search_RPN (zh, odr, query, setname, &hits);
2062 yaz_log(LOG_API,"Hits: %d",hits);
2070 /* ---------------------------------------------------------------------------
2071 Sort - a simplified interface, with optional read locks.
2073 int zebra_sort_by_specstr (ZebraHandle zh,
2075 const char *sort_spec,
2076 const char *output_setname,
2077 const char **input_setnames)
2079 int num_input_setnames = 0;
2080 int sort_status = 0;
2081 Z_SortKeySpecList *sort_sequence = yaz_sort_spec (stream, sort_spec);
2082 yaz_log(LOG_API,"sort (FIXME) ");
2085 logf(LOG_WARN,"invalid sort specs '%s'", sort_spec);
2090 /* we can do this, since the perl typemap code for char** will
2091 put a NULL at the end of list */
2092 while (input_setnames[num_input_setnames]) num_input_setnames++;
2094 if (zebra_begin_read (zh))
2097 resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
2098 output_setname, sort_sequence, &sort_status);