1 /* $Id: zebraapi.c,v 1.135 2004-10-07 14:18:23 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;
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);
157 if ((res = res_open (configName, def_res, over_res)))
159 ZebraService zh = xmalloc (sizeof(*zh));
161 yaz_log (LOG_DEBUG, "Read resources `%s'", configName);
163 zh->global_res = res;
164 zh->configName = xstrdup(configName);
169 zebra_mutex_cond_init (&zh->session_lock);
170 if (!res_get (zh->global_res, "passwd"))
171 zh->passwd_db = NULL;
174 zh->passwd_db = passwd_db_open ();
176 logf (LOG_WARN|LOG_ERRNO, "passwd_db_open failed");
178 passwd_db_file (zh->passwd_db,
179 res_get (zh->global_res, "passwd"));
181 zh->path_root = res_get (zh->global_res, "root");
182 zh->nmem = nmem_create();
183 zh->record_classes = recTypeClass_create (zh->global_res, zh->nmem);
189 void zebra_filter_info(ZebraService zs, void *cd,
190 void (*cb)(void *cd, const char *name))
194 recTypeClass_info(zs->record_classes, cd, cb);
197 void zebra_pidfname(ZebraService zs, char *path)
200 zebra_lock_prefix (zs->global_res, path);
201 strcat(path, "zebrasrv.pid");
204 Dict dict_open_res (BFiles bfs, const char *name, int cache, int rw,
205 int compact_flag, Res res)
207 int page_size = 4096;
208 char resource_str[200];
210 sprintf (resource_str, "dict.%.100s.pagesize", name);
214 v = res_get(res, resource_str);
218 yaz_log(LOG_LOG, "Using custom dictionary page size %d for %s",
221 return dict_open(bfs, name, cache, rw, compact_flag, page_size);
226 struct zebra_register *zebra_register_open (ZebraService zs, const char *name,
227 int rw, int useshadow, Res res,
228 const char *reg_path)
230 struct zebra_register *reg;
231 int record_compression = REC_COMPRESS_NONE;
232 const char *recordCompression = 0;
233 const char *profilePath;
238 reg = xmalloc (sizeof(*reg));
241 reg->name = xstrdup (name);
248 yaz_log (LOG_DEBUG, "zebra_register_open rw=%d useshadow=%d p=%p n=%s rp=%s",
249 rw, useshadow, reg, name, reg_path ? reg_path : "(none)");
251 reg->dh = data1_createx (DATA1_FLAG_XML);
254 reg->bfs = bfs_create (res_get (res, "register"), reg_path);
257 data1_destroy(reg->dh);
261 bf_cache (reg->bfs, res_get (res, "shadow"));
263 getcwd(cwd, sizeof(cwd)-1);
264 profilePath = res_get_def(res, "profilePath", DEFAULT_PROFILE_PATH);
265 yaz_log(LOG_DEBUG, "profilePath=%s cwd=%s", profilePath, cwd);
267 data1_set_tabpath (reg->dh, profilePath);
268 data1_set_tabroot (reg->dh, reg_path);
269 reg->recTypes = recTypes_init (zs->record_classes, reg->dh);
271 reg->zebra_maps = zebra_maps_open (res, reg_path);
272 reg->rank_classes = NULL;
276 reg->keys.buf_max = 0;
278 reg->keys.codec_handle = iscz1_start();
280 reg->sortKeys.buf = 0;
281 reg->sortKeys.buf_max = 0;
292 reg->key_file_no = 0;
295 zebraRankInstall (reg, rank1_class);
296 zebraRankInstall (reg, rankzv_class);
297 zebraRankInstall (reg, rankliv_class);
299 recordCompression = res_get_def (res, "recordCompression", "none");
300 if (!strcmp (recordCompression, "none"))
301 record_compression = REC_COMPRESS_NONE;
302 if (!strcmp (recordCompression, "bzip2"))
303 record_compression = REC_COMPRESS_BZIP2;
305 if (!(reg->records = rec_open (reg->bfs, rw, record_compression)))
307 logf (LOG_WARN, "rec_open");
312 reg->matchDict = dict_open_res (reg->bfs, GMATCH_DICT, 20, 1, 0, res);
314 if (!(reg->dict = dict_open_res (reg->bfs, FNAME_DICT, 40, rw, 0, res)))
316 logf (LOG_WARN, "dict_open");
319 if (!(reg->sortIdx = sortIdx_open (reg->bfs, rw)))
321 logf (LOG_WARN, "sortIdx_open");
324 if (res_get_match (res, "isam", "s", ISAM_DEFAULT))
326 struct ISAMS_M_s isams_m;
327 if (!(reg->isams = isams_open (reg->bfs, FNAME_ISAMS, rw,
328 key_isams_m(res, &isams_m))))
330 logf (LOG_WARN, "isams_open");
334 if (res_get_match (res, "isam", "c", ISAM_DEFAULT))
336 struct ISAMC_M_s isamc_m;
337 if (!(reg->isamc = isc_open (reg->bfs, FNAME_ISAMC,
338 rw, key_isamc_m(res, &isamc_m))))
340 logf (LOG_WARN, "isc_open");
344 if (res_get_match (res, "isam", "b", ISAM_DEFAULT))
346 struct ISAMC_M_s isamc_m;
348 if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
349 rw, key_isamc_m(res, &isamc_m), 0)))
351 logf (LOG_WARN, "isamb_open");
355 if (res_get_match (res, "isam", "bc", ISAM_DEFAULT))
357 struct ISAMC_M_s isamc_m;
359 if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
360 rw, key_isamc_m(res, &isamc_m), 1)))
362 logf (LOG_WARN, "isamb_open");
366 if (res_get_match (res, "isam", "null", ISAM_DEFAULT))
368 struct ISAMC_M_s isamc_m;
370 if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
371 rw, key_isamc_m(res, &isamc_m), -1)))
373 logf (LOG_WARN, "isamb_open");
377 reg->zei = zebraExplain_open (reg->records, reg->dh,
382 logf (LOG_WARN, "Cannot obtain EXPLAIN information");
386 yaz_log (LOG_DEBUG, "zebra_register_open ok p=%p", reg);
390 int zebra_admin_shutdown (ZebraHandle zh)
393 yaz_log(LOG_API,"zebra_admin_shutdown");
396 zebra_mutex_cond_lock (&zh->service->session_lock);
397 zh->service->stop_flag = 1;
398 zebra_mutex_cond_unlock (&zh->service->session_lock);
402 int zebra_admin_start (ZebraHandle zh)
406 yaz_log(LOG_API,"zebra_admin_start");
409 zebra_mutex_cond_lock (&zs->session_lock);
410 zebra_mutex_cond_unlock (&zs->session_lock);
414 static void zebra_register_close (ZebraService zs, struct zebra_register *reg)
418 yaz_log(LOG_DEBUG, "zebra_register_close p=%p", reg);
423 zebraExplain_close (reg->zei);
424 dict_close (reg->dict);
426 dict_close (reg->matchDict);
427 sortIdx_close (reg->sortIdx);
429 isams_close (reg->isams);
431 isc_close (reg->isamc);
433 isamb_close (reg->isamb);
434 rec_close (®->records);
437 recTypes_destroy (reg->recTypes);
438 zebra_maps_close (reg->zebra_maps);
439 zebraRankDestroy (reg);
440 bfs_destroy (reg->bfs);
441 data1_destroy (reg->dh);
443 xfree (reg->sortKeys.buf);
444 xfree (reg->keys.buf);
445 if (reg->keys.codec_handle)
446 iscz1_stop(reg->keys.codec_handle);
447 xfree (reg->key_buf);
452 int zebra_stop(ZebraService zs)
456 yaz_log (LOG_API, "zebra_stop");
460 zebra_close (zs->sessions);
463 zebra_mutex_cond_destroy (&zs->session_lock);
466 passwd_db_close (zs->passwd_db);
468 recTypeClass_destroy(zs->record_classes);
469 nmem_destroy(zs->nmem);
470 res_close (zs->global_res);
471 xfree (zs->configName);
476 int zebra_close (ZebraHandle zh)
479 struct zebra_session **sp;
482 yaz_log(LOG_API,"zebra_close");
489 yaz_log (LOG_DEBUG, "zebra_close zh=%p", zh);
490 resultSetDestroy (zh, -1, 0, 0);
493 zebra_register_close (zh->service, zh->reg);
494 zebra_close_res (zh);
496 xfree (zh->record_encoding);
498 for (i = 0; i < zh->num_basenames; i++)
499 xfree (zh->basenames[i]);
500 xfree (zh->basenames);
502 if (zh->iconv_to_utf8 != 0)
503 yaz_iconv_close (zh->iconv_to_utf8);
504 if (zh->iconv_from_utf8 != 0)
505 yaz_iconv_close (zh->iconv_from_utf8);
507 zebra_mutex_cond_lock (&zs->session_lock);
508 zebra_lock_destroy (zh->lock_normal);
509 zebra_lock_destroy (zh->lock_shadow);
521 zebra_mutex_cond_unlock (&zs->session_lock);
522 xfree (zh->reg_name);
523 xfree (zh->user_perm);
524 zh->service=0; /* more likely to trigger an assert */
525 xfree (zh->path_reg);
530 struct map_baseinfo {
536 char **new_basenames;
540 static Res zebra_open_res (ZebraHandle zh)
549 sprintf (fname, "%.200s/zebra.cfg", zh->path_reg);
550 res = res_open (fname, zh->service->global_res, 0);
552 res = zh->service->global_res;
554 else if (*zh->reg_name == 0)
556 res = zh->service->global_res;
560 yaz_log (LOG_WARN, "no register root specified");
561 return 0; /* no path for register - fail! */
566 static void zebra_close_res (ZebraHandle zh)
570 if (zh->res != zh->service->global_res)
575 static int zebra_select_register (ZebraHandle zh, const char *new_reg)
579 if (zh->res && strcmp (zh->reg_name, new_reg) == 0)
583 assert (zh->reg == 0);
584 assert (*zh->reg_name == 0);
590 resultSetInvalidate (zh);
591 zebra_register_close (zh->service, zh->reg);
596 xfree (zh->reg_name);
597 zh->reg_name = xstrdup (new_reg);
599 xfree (zh->path_reg);
601 if (zh->service->path_root)
603 zh->path_reg = xmalloc (strlen(zh->service->path_root) +
604 strlen(zh->reg_name) + 3);
605 strcpy (zh->path_reg, zh->service->path_root);
608 strcat (zh->path_reg, "/");
609 strcat (zh->path_reg, zh->reg_name);
612 zh->res = zebra_open_res (zh);
615 zebra_lock_destroy (zh->lock_normal);
619 zebra_lock_destroy (zh->lock_shadow);
625 const char *lock_area =res_get (zh->res, "lockDir");
627 if (!lock_area && zh->path_reg)
628 res_set (zh->res, "lockDir", zh->path_reg);
629 sprintf (fname, "norm.%s.LCK", zh->reg_name);
631 zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
633 sprintf (fname, "shadow.%s.LCK", zh->reg_name);
635 zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
641 void map_basenames_func (void *vp, const char *name, const char *value)
643 struct map_baseinfo *p = (struct map_baseinfo *) vp;
645 char fromdb[128], todb[8][128];
652 sscanf (value, "%127s %127s %127s %127s %127s %127s %127s %127s %127s",
653 fromdb, todb[0], todb[1], todb[2], todb[3], todb[4],
654 todb[5], todb[6], todb[7]);
658 for (i = 0; i<p->num_bases; i++)
659 if (p->basenames[i] && !STRCASECMP (p->basenames[i], fromdb))
662 for (i = 0; i < no; i++)
664 if (p->new_num_bases == p->new_num_max)
666 p->new_basenames[(p->new_num_bases)++] =
667 nmem_strdup (p->mem, todb[i]);
673 void map_basenames (ZebraHandle zh, ODR stream,
674 int *num_bases, char ***basenames)
676 struct map_baseinfo info;
677 struct map_baseinfo *p = &info;
680 yaz_log(LOG_API,"map_basenames ");
686 info.num_bases = *num_bases;
687 info.basenames = *basenames;
688 info.new_num_max = 128;
689 info.new_num_bases = 0;
690 info.new_basenames = (char **)
691 odr_malloc (stream, sizeof(*info.new_basenames) * info.new_num_max);
692 info.mem = stream->mem;
694 res_trav (zh->service->global_res, "mapdb", &info, map_basenames_func);
696 for (i = 0; i<p->num_bases; i++)
697 if (p->basenames[i] && p->new_num_bases < p->new_num_max)
699 p->new_basenames[(p->new_num_bases)++] =
700 nmem_strdup (p->mem, p->basenames[i]);
702 *num_bases = info.new_num_bases;
703 *basenames = info.new_basenames;
704 for (i = 0; i<*num_bases; i++)
705 logf (LOG_DEBUG, "base %s", (*basenames)[i]);
708 int zebra_select_database (ZebraHandle zh, const char *basename)
711 yaz_log(LOG_API,"zebra_select_database %s",basename);
714 return zebra_select_databases (zh, 1, &basename);
717 int zebra_select_databases (ZebraHandle zh, int num_bases,
718 const char **basenames)
727 yaz_log(LOG_API,"zebra_select_databases n=%d [0]=%s",
728 num_bases,basenames[0]);
736 for (i = 0; i < zh->num_basenames; i++)
737 xfree (zh->basenames[i]);
738 xfree (zh->basenames);
740 zh->num_basenames = num_bases;
741 zh->basenames = xmalloc (zh->num_basenames * sizeof(*zh->basenames));
742 for (i = 0; i < zh->num_basenames; i++)
743 zh->basenames[i] = xstrdup (basenames[i]);
745 cp = strrchr(basenames[0], '/');
748 len = cp - basenames[0];
749 new_reg = xmalloc (len + 1);
750 memcpy (new_reg, basenames[0], len);
754 new_reg = xstrdup ("");
755 for (i = 1; i<num_bases; i++)
759 cp1 = strrchr (basenames[i], '/');
767 if (len != cp1 - basenames[i] ||
768 memcmp (basenames[i], new_reg, len))
783 zebra_select_register (zh, new_reg);
790 if (!zh->lock_normal || !zh->lock_shadow)
798 int zebra_search_RPN (ZebraHandle zh, ODR o,
799 Z_RPNQuery *query, const char *setname, int *hits)
808 yaz_log(LOG_API,"zebra_search_rpn");
813 if (zebra_begin_read (zh))
816 zebra_livcode_transform(zh, query);
818 resultSetAddRPN (zh, odr_extract_mem(o), query,
819 zh->num_basenames, zh->basenames, setname);
822 max = res_get (zh->res, "maxhits");
827 maxhits=INT_MAX; /* properly rounded, to make it look like a limit*/
828 while (maxhits>100) { maxhits/=10; i++;}
829 while (i--) maxhits *= 10;
831 if (zh->hits > maxhits) { /* too large for yaz to handle */
832 logf(LOG_DEBUG,"limiting hits to "ZINT_FORMAT, maxhits);
840 int zebra_records_retrieve (ZebraHandle zh, ODR stream,
841 const char *setname, Z_RecordComposition *comp,
842 oid_value input_format, int num_recs,
843 ZebraRetrievalRecord *recs)
846 int i, *pos_array, ret = 0;
853 yaz_log(LOG_API,"zebra_records_retrieve n=%d",num_recs);
859 zh->errString = odr_strdup (stream, setname);
865 if (zebra_begin_read (zh))
868 pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
869 for (i = 0; i<num_recs; i++)
870 pos_array[i] = recs[i].position;
871 poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
874 logf (LOG_DEBUG, "zebraPosSetCreate error");
876 zh->errString = nmem_strdup (stream->mem, setname);
881 for (i = 0; i<num_recs; i++)
886 recs[i].format = VAL_SUTRS;
887 recs[i].len = strlen(poset[i].term);
888 recs[i].buf = poset[i].term;
889 recs[i].base = poset[i].db;
891 else if (poset[i].sysno)
894 zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
895 stream, input_format, comp,
896 &recs[i].format, &recs[i].buf,
899 recs[i].errString = NULL;
905 sprintf (num_str, "%d", pos_array[i]);
907 zh->errString = odr_strdup (stream, num_str);
912 zebraPosSetDestroy (zh, poset, num_recs);
919 int zebra_scan (ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
920 oid_value attributeset,
921 int *position, int *num_entries, ZebraScanEntry **entries,
931 yaz_log(LOG_API,"zebra_scan");
933 if (zebra_begin_read (zh))
939 rpn_scan (zh, stream, zapt, attributeset,
940 zh->num_basenames, zh->basenames, position,
941 num_entries, entries, is_partial, 0, 0);
946 int zebra_sort (ZebraHandle zh, ODR stream,
947 int num_input_setnames, const char **input_setnames,
948 const char *output_setname, Z_SortKeySpecList *sort_sequence,
953 assert(num_input_setnames>0);
954 assert(input_setnames);
955 assert(sort_sequence);
957 yaz_log(LOG_API,"zebra_sort");
959 if (zebra_begin_read (zh))
961 resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
962 output_setname, sort_sequence, sort_status);
967 int zebra_deleleResultSet(ZebraHandle zh, int function,
968 int num_setnames, char **setnames,
973 assert(num_setnames>0);
976 yaz_log(LOG_API,"zebra_deleleResultSet n=%d",num_setnames);
978 if (zebra_begin_read(zh))
979 return Z_DeleteStatus_systemProblemAtTarget;
982 case Z_DeleteResultSetRequest_list:
983 resultSetDestroy (zh, num_setnames, setnames, statuses);
985 case Z_DeleteResultSetRequest_all:
986 resultSetDestroy (zh, -1, 0, statuses);
990 status = Z_DeleteStatus_success;
991 for (i = 0; i<num_setnames; i++)
992 if (statuses[i] == Z_DeleteStatus_resultSetDidNotExist)
993 status = statuses[i];
997 int zebra_errCode (ZebraHandle zh)
1001 yaz_log(LOG_API,"zebra_errCode: %d",zh->errCode);
1004 yaz_log(LOG_API,"zebra_errCode: o");
1008 const char *zebra_errString (ZebraHandle zh)
1012 e= diagbib1_str (zh->errCode);
1013 yaz_log(LOG_API,"zebra_errString: %s",e);
1017 char *zebra_errAdd (ZebraHandle zh)
1022 yaz_log(LOG_API,"zebra_errAdd: %s",a);
1026 void zebra_clearError(ZebraHandle zh)
1035 int zebra_auth (ZebraHandle zh, const char *user, const char *pass)
1045 sprintf(u, "perm.%.30s", user ? user : "anonymous");
1046 p = res_get(zs->global_res, u);
1047 xfree (zh->user_perm);
1048 zh->user_perm = xstrdup(p ? p : "r");
1050 /* users that don't require a password .. */
1051 if (zh->user_perm && strchr(zh->user_perm, 'a'))
1054 if (!zs->passwd_db || !passwd_db_auth (zs->passwd_db, user, pass))
1059 int zebra_admin_import_begin (ZebraHandle zh, const char *database,
1060 const char *record_type)
1063 yaz_log(LOG_API,"zebra_admin_import_begin db=%s rt=%s",
1064 database, record_type);
1066 if (zebra_select_database(zh, database))
1068 if (zebra_begin_trans (zh, 1))
1073 int zebra_admin_import_end (ZebraHandle zh)
1076 yaz_log(LOG_API,"zebra_admin_import_end");
1078 zebra_end_trans (zh);
1082 int zebra_admin_import_segment (ZebraHandle zh, Z_Segment *segment)
1087 yaz_log(LOG_API,"zebra_admin_import_segment");
1089 for (i = 0; i<segment->num_segmentRecords; i++)
1091 Z_NamePlusRecord *npr = segment->segmentRecords[i];
1093 printf ("--------------%d--------------------\n", i);
1094 /* FIXME - What! printing on stdout ??? */
1095 if (npr->which == Z_NamePlusRecord_intermediateFragment)
1097 Z_FragmentSyntax *fragment = npr->u.intermediateFragment;
1098 if (fragment->which == Z_FragmentSyntax_notExternallyTagged)
1100 Odr_oct *oct = fragment->u.notExternallyTagged;
1101 printf ("%.*s", (oct->len > 100 ? 100 : oct->len) ,
1106 zebra_update_record(zh,
1107 0, /* record Type */
1119 int zebra_admin_exchange_record (ZebraHandle zh,
1120 const char *rec_buf,
1122 const char *recid_buf, size_t recid_len,
1124 /* 1 = insert. Fail it already exists */
1125 /* 2 = replace. Fail it does not exist */
1126 /* 3 = delete. Fail if does not exist */
1127 /* 4 = update. Insert/replace */
1133 assert(action>0 && action <=4);
1136 yaz_log(LOG_API,"zebra_admin_exchange_record ac=%d", action);
1139 if (!recid_buf || recid_len <= 0 || recid_len >= sizeof(recid_z))
1141 memcpy (recid_z, recid_buf, recid_len);
1142 recid_z[recid_len] = 0;
1144 if (zebra_begin_trans(zh, 1))
1147 rinfo = dict_lookup (zh->reg->matchDict, recid_z);
1150 if (action == 1) /* fail if insert */
1152 zebra_end_trans(zh);
1156 memcpy (&sysno, rinfo+1, sizeof(sysno));
1160 if (action == 2 || action == 3) /* fail if delete or update */
1162 zebra_end_trans(zh);
1165 action = 1; /* make it an insert (if it's an update).. */
1167 buffer_extract_record (zh, rec_buf, rec_len,
1168 action == 3 ? 1 : 0 /* delete flag */,
1174 0, /* force update */
1175 1 /* allow update */
1179 dict_insert (zh->reg->matchDict, recid_z, sizeof(sysno), &sysno);
1181 else if (action == 3)
1183 dict_delete (zh->reg->matchDict, recid_z);
1185 zebra_end_trans(zh);
1189 int delete_w_handle(const char *info, void *handle)
1191 ZebraHandle zh = (ZebraHandle) handle;
1195 if (*info == sizeof(pos))
1197 memcpy (&pos, info+1, sizeof(pos));
1198 isamb_unlink(zh->reg->isamb, pos);
1203 static int delete_SU_handle(void *handle, int ord)
1205 ZebraHandle zh = (ZebraHandle) handle;
1209 ord_len = key_SU_encode (ord, ord_buf);
1210 ord_buf[ord_len] = '\0';
1212 assert (zh->reg->isamb);
1213 dict_delete_subtree(zh->reg->dict, ord_buf,
1214 zh, delete_w_handle);
1218 int zebra_drop_database (ZebraHandle zh, const char *database)
1222 yaz_log(LOG_API,"zebra_drop_database");
1225 if (zebra_select_database (zh, database))
1227 if (zebra_begin_trans (zh, 1))
1231 zebraExplain_curDatabase (zh->reg->zei, database);
1233 zebraExplain_trav_ord(zh->reg->zei, zh, delete_SU_handle);
1234 zebraExplain_removeDatabase(zh->reg->zei, zh);
1238 yaz_log(LOG_WARN, "drop database only supported for isam:b");
1241 zebra_end_trans (zh);
1245 int zebra_create_database (ZebraHandle zh, const char *database)
1248 yaz_log(LOG_API,"zebra_create_database %s",database);
1252 if (zebra_select_database (zh, database))
1254 if (zebra_begin_trans (zh, 1))
1257 /* announce database */
1258 if (zebraExplain_newDatabase (zh->reg->zei, database, 0
1259 /* explainDatabase */))
1261 zebra_end_trans (zh);
1263 zh->errString = "database already exist";
1266 zebra_end_trans (zh);
1270 int zebra_string_norm (ZebraHandle zh, unsigned reg_id,
1271 const char *input_str, int input_len,
1272 char *output_str, int output_len)
1278 yaz_log(LOG_API,"zebra_string_norm ");
1280 if (!zh->reg->zebra_maps)
1282 wrbuf = zebra_replace(zh->reg->zebra_maps, reg_id, "",
1283 input_str, input_len);
1286 if (wrbuf_len(wrbuf) >= output_len)
1288 if (wrbuf_len(wrbuf))
1289 memcpy (output_str, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
1290 output_str[wrbuf_len(wrbuf)] = '\0';
1291 return wrbuf_len(wrbuf);
1295 int zebra_set_state (ZebraHandle zh, int val, int seqno)
1296 /* FIXME - zint seqno ?? */
1298 char state_fname[256];
1303 yaz_log(LOG_API,"zebra_set_state v=%d seq=%d", val, seqno);
1306 sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1307 fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1308 f = fopen (fname, "w");
1310 yaz_log (LOG_DEBUG, "zebra_set_state: %c %d %ld", val, seqno, p);
1311 fprintf (f, "%c %d %ld\n", val, seqno, p);
1317 int zebra_get_state (ZebraHandle zh, char *val, int *seqno)
1319 char state_fname[256];
1324 yaz_log(LOG_API,"zebra_get_state ");
1326 sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1327 fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1328 f = fopen (fname, "r");
1334 fscanf (f, "%c %d", val, seqno);
1341 int zebra_begin_read (ZebraHandle zh)
1343 return zebra_begin_trans(zh, 0);
1346 int zebra_end_read (ZebraHandle zh)
1348 return zebra_end_trans(zh);
1351 static void read_res_for_transaction(ZebraHandle zh)
1353 const char *group = res_get(zh->res, "group");
1355 /* FIXME - do we still use groups ?? */
1357 zh->m_group = group;
1358 v = res_get_prefix(zh->res, "followLinks", group, "1");
1359 zh->m_follow_links = atoi(v);
1361 zh->m_record_id = res_get_prefix(zh->res, "recordId", group, 0);
1362 zh->m_record_type = res_get_prefix(zh->res, "recordType", group, 0);
1364 v = res_get_prefix(zh->res, "storeKeys", group, "1");
1365 zh->m_store_keys = atoi(v);
1367 v = res_get_prefix(zh->res, "storeData", group, "1");
1368 zh->m_store_data = atoi(v);
1370 v = res_get_prefix(zh->res, "explainDatabase", group, "0");
1371 zh->m_explain_database = atoi(v);
1373 v = res_get_prefix(zh->res, "openRW", group, "1");
1374 zh->m_flag_rw = atoi(v);
1376 v = res_get_prefix(zh->res, "fileVerboseLimit", group, "100000");
1377 zh->m_file_verbose_limit = atoi(v);
1380 int zebra_begin_trans (ZebraHandle zh, int rw)
1386 zh->errString = "zebra_begin_trans: no database selected";
1390 yaz_log(LOG_API,"zebra_begin_trans rw=%d",rw);
1394 if (rw && !strchr(zh->user_perm, 'w'))
1408 const char *rval = 0;
1413 read_res_for_transaction(zh);
1416 if (zh->trans_no != 1)
1419 zh->errString = "zebra_begin_trans: write trans not allowed within read trans";
1424 resultSetInvalidate (zh);
1425 zebra_register_close (zh->service, zh->reg);
1427 zh->trans_w_no = zh->trans_no;
1431 zh->records_inserted = 0;
1432 zh->records_updated = 0;
1433 zh->records_deleted = 0;
1434 zh->records_processed = 0;
1436 #if HAVE_SYS_TIMES_H
1440 if (zh->shadow_enable)
1441 rval = res_get (zh->res, "shadow");
1443 for (pass = 0; pass < 2; pass++)
1447 zebra_lock_r (zh->lock_normal);
1448 zebra_lock_w (zh->lock_shadow);
1452 zebra_lock_w (zh->lock_normal);
1453 zebra_lock_w (zh->lock_shadow);
1456 zebra_get_state (zh, &val, &seqno);
1459 yaz_log (LOG_WARN, "previous transaction didn't finish commit");
1460 zebra_unlock (zh->lock_shadow);
1461 zebra_unlock (zh->lock_normal);
1465 else if (val == 'd')
1469 BFiles bfs = bfs_create (res_get (zh->res, "shadow"),
1471 yaz_log (LOG_WARN, "previous transaction didn't reach commit");
1472 bf_commitClean (bfs, rval);
1477 yaz_log (LOG_WARN, "your previous transaction didn't finish");
1484 yaz_log (LOG_FATAL, "zebra_begin_trans couldn't finish commit");
1488 zebra_set_state (zh, 'd', seqno);
1490 zh->reg = zebra_register_open (zh->service, zh->reg_name,
1491 1, rval ? 1 : 0, zh->res,
1494 zh->reg->seqno = seqno;
1497 zebra_set_state (zh, 'o', seqno);
1499 zebra_unlock (zh->lock_shadow);
1500 zebra_unlock (zh->lock_normal);
1506 zh->errString = "zebra_begin_trans: cannot open register";
1507 yaz_log(LOG_FATAL, zh->errString);
1519 if (zh->trans_no != 1)
1521 zebra_flush_reg (zh);
1525 #if HAVE_SYS_TIMES_H
1534 if (!zh->lock_normal || !zh->lock_shadow)
1540 zebra_get_state (zh, &val, &seqno);
1546 else if (seqno != zh->reg->seqno)
1548 yaz_log (LOG_DEBUG, "reopen seqno cur/old %d/%d",
1549 seqno, zh->reg->seqno);
1552 else if (zh->reg->last_val != val)
1554 yaz_log (LOG_DEBUG, "reopen last cur/old %d/%d",
1555 val, zh->reg->last_val);
1562 zebra_lock_r (zh->lock_shadow);
1564 zebra_lock_r (zh->lock_normal);
1568 resultSetInvalidate (zh);
1569 zebra_register_close (zh->service, zh->reg);
1571 zh->reg = zebra_register_open (zh->service, zh->reg_name,
1572 0, val == 'c' ? 1 : 0,
1573 zh->res, zh->path_reg);
1576 zebra_unlock (zh->lock_normal);
1577 zebra_unlock (zh->lock_shadow);
1582 zh->reg->last_val = val;
1583 zh->reg->seqno = seqno;
1585 read_res_for_transaction(zh);
1589 int zebra_end_trans (ZebraHandle zh)
1592 ZebraTransactionStatus dummy;
1593 yaz_log(LOG_API,"zebra_end_trans");
1594 return zebra_end_transaction(zh, &dummy);
1597 int zebra_end_transaction (ZebraHandle zh, ZebraTransactionStatus *status)
1605 yaz_log(LOG_API,"zebra_end_transaction");
1607 status->processed = 0;
1608 status->inserted = 0;
1609 status->updated = 0;
1610 status->deleted = 0;
1614 if (!zh->res || !zh->reg)
1617 zh->errString = "zebra_end_trans: no open transaction";
1620 if (zh->trans_no != zh->trans_w_no)
1623 if (zh->trans_no != 0)
1626 /* release read lock */
1628 zebra_unlock (zh->lock_normal);
1629 zebra_unlock (zh->lock_shadow);
1632 { /* release write lock */
1636 yaz_log (LOG_DEBUG, "zebra_end_trans");
1637 rval = res_get (zh->res, "shadow");
1639 zebraExplain_runNumberIncrement (zh->reg->zei, 1);
1641 zebra_flush_reg (zh);
1643 resultSetInvalidate (zh);
1645 zebra_register_close (zh->service, zh->reg);
1648 yaz_log (LOG_LOG, "Records: "ZINT_FORMAT" i/u/d "
1649 ZINT_FORMAT"/"ZINT_FORMAT"/"ZINT_FORMAT,
1650 zh->records_processed, zh->records_inserted,
1651 zh->records_updated, zh->records_deleted);
1653 status->processed = zh->records_processed;
1654 status->inserted = zh->records_inserted;
1655 status->updated = zh->records_updated;
1656 status->deleted = zh->records_deleted;
1658 zebra_get_state (zh, &val, &seqno);
1661 BFiles bfs = bfs_create (rval, zh->path_reg);
1662 yaz_log (LOG_DEBUG, "deleting shadow val=%c", val);
1663 bf_commitClean (bfs, rval);
1668 zebra_set_state (zh, 'o', seqno);
1670 zebra_unlock (zh->lock_shadow);
1671 zebra_unlock (zh->lock_normal);
1674 #if HAVE_SYS_TIMES_H
1676 logf (LOG_LOG, "user/system: %ld/%ld",
1677 (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1678 (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1680 status->utime = (long) (zh->tms2.tms_utime - zh->tms1.tms_utime);
1681 status->stime = (long) (zh->tms2.tms_stime - zh->tms1.tms_stime);
1686 int zebra_repository_update (ZebraHandle zh, const char *path)
1691 logf (LOG_API, "updating %s", path);
1692 repositoryUpdate (zh, path);
1696 int zebra_repository_delete (ZebraHandle zh, const char *path)
1701 logf (LOG_API, "deleting %s", path);
1702 repositoryDelete (zh, path);
1706 int zebra_repository_show (ZebraHandle zh, const char *path)
1710 yaz_log(LOG_API,"zebra_repository_show");
1712 repositoryShow (zh, path);
1716 static int zebra_commit_ex (ZebraHandle zh, int clean_only)
1730 rval = res_get (zh->res, "shadow");
1733 logf (LOG_WARN, "Cannot perform commit");
1734 logf (LOG_WARN, "No shadow area defined");
1738 zebra_lock_w (zh->lock_normal);
1739 zebra_lock_r (zh->lock_shadow);
1741 bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1743 zebra_get_state (zh, &val, &seqno);
1746 bf_cache (bfs, rval);
1747 if (bf_commitExists (bfs))
1750 zebra_set_state (zh, 'd', seqno);
1753 zebra_set_state (zh, 'c', seqno);
1755 logf (LOG_DEBUG, "commit start");
1756 bf_commitExec (bfs);
1761 logf (LOG_DEBUG, "commit clean");
1762 bf_commitClean (bfs, rval);
1764 zebra_set_state (zh, 'o', seqno);
1768 logf (LOG_LOG, "nothing to commit");
1772 zebra_unlock (zh->lock_shadow);
1773 zebra_unlock (zh->lock_normal);
1777 int zebra_clean (ZebraHandle zh)
1780 yaz_log(LOG_API,"zebra_clean");
1781 return zebra_commit_ex(zh, 1);
1784 int zebra_commit (ZebraHandle zh)
1787 yaz_log(LOG_API,"zebra_commit");
1788 return zebra_commit_ex(zh, 0);
1791 int zebra_init (ZebraHandle zh)
1796 yaz_log(LOG_API,"zebra_init");
1804 rval = res_get (zh->res, "shadow");
1806 bfs = bfs_create (res_get (zh->service->global_res, "register"),
1811 bf_cache (bfs, rval);
1815 zebra_set_state (zh, 'o', 0);
1819 int zebra_compact (ZebraHandle zh)
1823 yaz_log(LOG_API,"zebra_compact");
1830 bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1836 int zebra_result (ZebraHandle zh, int *code, char **addinfo)
1839 yaz_log(LOG_API,"zebra_result");
1840 *code = zh->errCode;
1841 *addinfo = zh->errString;
1845 int zebra_shadow_enable (ZebraHandle zh, int value)
1848 yaz_log(LOG_API,"zebra_shadow_enable");
1850 zh->shadow_enable = value;
1854 int zebra_record_encoding (ZebraHandle zh, const char *encoding)
1858 yaz_log(LOG_API,"zebra_record_encoding");
1860 xfree (zh->record_encoding);
1864 * Something about charset aliases. Oleg???
1867 if (zh->iconv_to_utf8 != 0)
1868 yaz_iconv_close(zh->iconv_to_utf8);
1869 if (zh->iconv_from_utf8 != 0)
1870 yaz_iconv_close(zh->iconv_from_utf8);
1872 zh->record_encoding = xstrdup (encoding);
1874 logf(LOG_DEBUG, "Reset record encoding: %s", encoding);
1877 yaz_iconv_open ("UTF-8", encoding);
1878 if (zh->iconv_to_utf8 == 0)
1879 yaz_log (LOG_WARN, "iconv: %s to UTF-8 unsupported", encoding);
1880 zh->iconv_from_utf8 =
1881 yaz_iconv_open (encoding, "UTF-8");
1882 if (zh->iconv_to_utf8 == 0)
1883 yaz_log (LOG_WARN, "iconv: UTF-8 to %s unsupported", encoding);
1888 int zebra_set_resource(ZebraHandle zh, const char *name, const char *value)
1893 yaz_log(LOG_API,"zebra_set_resource %s:%s",name,value);
1895 res_set(zh->res, name, value);
1899 const char *zebra_get_resource(ZebraHandle zh,
1900 const char *name, const char *defaultvalue)
1905 assert(defaultvalue);
1906 v= res_get_def( zh->res, name, (char *)defaultvalue);
1908 yaz_log(LOG_API,"zebra_get_resource %s:%s",name,v);
1912 /* moved from zebra_api_ext.c by pop */
1913 /* FIXME: Should this really be public??? -Heikki */
1915 int zebra_trans_no (ZebraHandle zh)
1918 yaz_log(LOG_API,"zebra_trans_no");
1919 return zh->trans_no;
1922 int zebra_get_shadow_enable (ZebraHandle zh)
1925 yaz_log(LOG_API,"zebra_get_shadow_enable");
1926 return (zh->shadow_enable);
1929 int zebra_set_shadow_enable (ZebraHandle zh, int value)
1932 yaz_log(LOG_API,"zebra_set_shadow_enable %d",value);
1933 zh->shadow_enable = value;
1937 /* almost the same as zebra_records_retrieve ... but how did it work?
1938 I mean for multiple records ??? CHECK ??? */
1939 void api_records_retrieve (ZebraHandle zh, ODR stream,
1940 const char *setname, Z_RecordComposition *comp,
1941 oid_value input_format, int num_recs,
1942 ZebraRetrievalRecord *recs)
1952 yaz_log(LOG_API,"api_records_retrieve s=%s n=%d",setname,num_recs);
1957 zh->errString = odr_strdup (stream, setname);
1963 if (zebra_begin_read (zh))
1966 pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
1967 for (i = 0; i<num_recs; i++)
1968 pos_array[i] = recs[i].position;
1969 poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
1972 logf (LOG_DEBUG, "zebraPosSetCreate error");
1974 zh->errString = nmem_strdup (stream->mem, setname);
1978 for (i = 0; i<num_recs; i++)
1982 recs[i].errCode = 0;
1983 recs[i].format = VAL_SUTRS;
1984 recs[i].len = strlen(poset[i].term);
1985 recs[i].buf = poset[i].term;
1986 recs[i].base = poset[i].db;
1990 else if (poset[i].sysno)
1992 /* changed here ??? CHECK ??? */
1995 zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
1996 stream, input_format, comp,
2001 recs[i].buf = (char *) odr_malloc(stream,recs[i].len);
2002 memcpy(recs[i].buf, b, recs[i].len);
2003 recs[i].errString = 0; /* Hmmm !!! we should get this */
2004 recs[i].sysno = poset[i].sysno;
2005 recs[i].score = poset[i].score;
2011 sprintf (num_str, "%d", pos_array[i]);
2013 zh->errString = odr_strdup (stream, num_str);
2018 zebraPosSetDestroy (zh, poset, num_recs);
2020 zebra_end_read (zh);
2025 /* ---------------------------------------------------------------------------
2026 Record insert(=update), delete
2028 If sysno is provided, then it's used to identify the record.
2029 If not, and match_criteria is provided, then sysno is guessed
2030 If not, and a record is provided, then sysno is got from there
2031 NOTE: Now returns 0 at success and updates sysno, which is an int*
2035 int zebra_add_record(ZebraHandle zh,
2036 const char *buf, int buf_size)
2039 return zebra_update_record(zh, 0, &sysno, 0, 0, buf, buf_size, 0);
2042 int zebra_insert_record (ZebraHandle zh,
2043 const char *recordType,
2044 SYSNO *sysno, const char *match, const char *fname,
2045 const char *buf, int buf_size, int force_update)
2051 yaz_log(LOG_API, "zebra_insert_record sysno=" ZINT_FORMAT, *sysno);
2053 if (buf_size < 1) buf_size = strlen(buf);
2055 if (zebra_begin_trans(zh, 1))
2057 res = buffer_extract_record (zh, buf, buf_size,
2058 0, /* delete_flag */
2064 0); /* allow_update */
2065 zebra_end_trans(zh);
2069 int zebra_update_record (ZebraHandle zh,
2070 const char *recordType,
2071 SYSNO* sysno, const char *match, const char *fname,
2072 const char *buf, int buf_size,
2080 yaz_log(LOG_API, "zebra_update_record sysno=" ZINT_FORMAT, *sysno);
2082 if (buf_size < 1) buf_size = strlen(buf);
2084 if (zebra_begin_trans(zh, 1))
2086 res = buffer_extract_record (zh, buf, buf_size,
2087 0, /* delete_flag */
2093 1); /* allow_update */
2094 zebra_end_trans(zh);
2098 int zebra_delete_record (ZebraHandle zh,
2099 const char *recordType,
2100 SYSNO *sysno, const char *match, const char *fname,
2101 const char *buf, int buf_size,
2108 yaz_log(LOG_API, "zebra_delete_record sysno=" ZINT_FORMAT, *sysno);
2110 if (buf_size < 1) buf_size = strlen(buf);
2112 if (zebra_begin_trans(zh, 1))
2114 res = buffer_extract_record (zh, buf, buf_size,
2115 1, /* delete_flag */
2121 1); /* allow_update */
2122 zebra_end_trans(zh);
2126 /* ---------------------------------------------------------------------------
2130 int zebra_search_PQF (ZebraHandle zh, const char *pqf_query,
2131 const char *setname, int *numhits)
2136 ODR odr = odr_createmem(ODR_ENCODE);
2141 yaz_log(LOG_API,"zebra_search_PQF s=%s q=%s",setname, pqf_query);
2143 query = p_query_rpn (odr, PROTO_Z3950, pqf_query);
2146 yaz_log (LOG_WARN, "bad query %s\n", pqf_query);
2148 res=zebra_search_RPN (zh, odr, query, setname, &hits);
2152 yaz_log(LOG_API,"Hits: %d",hits);
2160 /* ---------------------------------------------------------------------------
2161 Sort - a simplified interface, with optional read locks.
2163 int zebra_sort_by_specstr (ZebraHandle zh,
2165 const char *sort_spec,
2166 const char *output_setname,
2167 const char **input_setnames)
2169 int num_input_setnames = 0;
2170 int sort_status = 0;
2171 Z_SortKeySpecList *sort_sequence;
2175 assert(output_setname);
2176 assert(input_setnames);
2177 sort_sequence = yaz_sort_spec (stream, sort_spec);
2178 yaz_log(LOG_API,"sort (FIXME) ");
2181 logf(LOG_WARN,"invalid sort specs '%s'", sort_spec);
2186 /* we can do this, since the perl typemap code for char** will
2187 put a NULL at the end of list */
2188 while (input_setnames[num_input_setnames]) num_input_setnames++;
2190 if (zebra_begin_read (zh))
2193 resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
2194 output_setname, sort_sequence, &sort_status);