1 /* $Id: zebraapi.c,v 1.133 2004-09-27 10:44:49 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");
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))
191 recTypeClass_info(zs->record_classes, cd, cb);
194 void zebra_pidfname(ZebraService zs, char *path)
196 zebra_lock_prefix (zs->global_res, path);
197 strcat(path, "zebrasrv.pid");
200 Dict dict_open_res (BFiles bfs, const char *name, int cache, int rw,
201 int compact_flag, Res res)
203 int page_size = 4096;
204 char resource_str[200];
206 sprintf (resource_str, "dict.%.100s.pagesize", name);
208 v = res_get(res, resource_str);
212 yaz_log(LOG_LOG, "Using custom dictionary page size %d for %s",
215 return dict_open(bfs, name, cache, rw, compact_flag, page_size);
220 struct zebra_register *zebra_register_open (ZebraService zs, const char *name,
221 int rw, int useshadow, Res res,
222 const char *reg_path)
224 struct zebra_register *reg;
225 int record_compression = REC_COMPRESS_NONE;
226 const char *recordCompression = 0;
227 const char *profilePath;
232 reg = xmalloc (sizeof(*reg));
235 reg->name = xstrdup (name);
242 yaz_log (LOG_DEBUG, "zebra_register_open rw=%d useshadow=%d p=%p n=%s rp=%s",
243 rw, useshadow, reg, name, reg_path ? reg_path : "(none)");
245 reg->dh = data1_createx (DATA1_FLAG_XML);
248 reg->bfs = bfs_create (res_get (res, "register"), reg_path);
251 data1_destroy(reg->dh);
255 bf_cache (reg->bfs, res_get (res, "shadow"));
257 getcwd(cwd, sizeof(cwd)-1);
258 profilePath = res_get_def(res, "profilePath", DEFAULT_PROFILE_PATH);
259 yaz_log(LOG_DEBUG, "profilePath=%s cwd=%s", profilePath, cwd);
261 data1_set_tabpath (reg->dh, profilePath);
262 data1_set_tabroot (reg->dh, reg_path);
263 reg->recTypes = recTypes_init (zs->record_classes, reg->dh);
265 reg->zebra_maps = zebra_maps_open (res, reg_path);
266 reg->rank_classes = NULL;
270 reg->keys.buf_max = 0;
272 reg->keys.codec_handle = iscz1_start();
274 reg->sortKeys.buf = 0;
275 reg->sortKeys.buf_max = 0;
286 reg->key_file_no = 0;
289 zebraRankInstall (reg, rank1_class);
290 zebraRankInstall (reg, rankzv_class);
291 zebraRankInstall (reg, rankliv_class);
293 recordCompression = res_get_def (res, "recordCompression", "none");
294 if (!strcmp (recordCompression, "none"))
295 record_compression = REC_COMPRESS_NONE;
296 if (!strcmp (recordCompression, "bzip2"))
297 record_compression = REC_COMPRESS_BZIP2;
299 if (!(reg->records = rec_open (reg->bfs, rw, record_compression)))
301 logf (LOG_WARN, "rec_open");
306 reg->matchDict = dict_open_res (reg->bfs, GMATCH_DICT, 20, 1, 0, res);
308 if (!(reg->dict = dict_open_res (reg->bfs, FNAME_DICT, 40, rw, 0, res)))
310 logf (LOG_WARN, "dict_open");
313 if (!(reg->sortIdx = sortIdx_open (reg->bfs, rw)))
315 logf (LOG_WARN, "sortIdx_open");
318 if (res_get_match (res, "isam", "s", ISAM_DEFAULT))
320 struct ISAMS_M_s isams_m;
321 if (!(reg->isams = isams_open (reg->bfs, FNAME_ISAMS, rw,
322 key_isams_m(res, &isams_m))))
324 logf (LOG_WARN, "isams_open");
328 if (res_get_match (res, "isam", "c", ISAM_DEFAULT))
330 struct ISAMC_M_s isamc_m;
331 if (!(reg->isamc = isc_open (reg->bfs, FNAME_ISAMC,
332 rw, key_isamc_m(res, &isamc_m))))
334 logf (LOG_WARN, "isc_open");
338 if (res_get_match (res, "isam", "b", ISAM_DEFAULT))
340 struct ISAMC_M_s isamc_m;
342 if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
343 rw, key_isamc_m(res, &isamc_m), 0)))
345 logf (LOG_WARN, "isamb_open");
349 if (res_get_match (res, "isam", "bc", ISAM_DEFAULT))
351 struct ISAMC_M_s isamc_m;
353 if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
354 rw, key_isamc_m(res, &isamc_m), 1)))
356 logf (LOG_WARN, "isamb_open");
360 if (res_get_match (res, "isam", "null", ISAM_DEFAULT))
362 struct ISAMC_M_s isamc_m;
364 if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
365 rw, key_isamc_m(res, &isamc_m), -1)))
367 logf (LOG_WARN, "isamb_open");
371 reg->zei = zebraExplain_open (reg->records, reg->dh,
376 logf (LOG_WARN, "Cannot obtain EXPLAIN information");
380 yaz_log (LOG_DEBUG, "zebra_register_open ok p=%p", reg);
384 int zebra_admin_shutdown (ZebraHandle zh)
387 yaz_log(LOG_API,"zebra_admin_shutdown");
390 zebra_mutex_cond_lock (&zh->service->session_lock);
391 zh->service->stop_flag = 1;
392 zebra_mutex_cond_unlock (&zh->service->session_lock);
396 int zebra_admin_start (ZebraHandle zh)
400 yaz_log(LOG_API,"zebra_admin_start");
403 zebra_mutex_cond_lock (&zs->session_lock);
404 zebra_mutex_cond_unlock (&zs->session_lock);
408 static void zebra_register_close (ZebraService zs, struct zebra_register *reg)
411 yaz_log(LOG_DEBUG, "zebra_register_close p=%p", reg);
416 zebraExplain_close (reg->zei);
417 dict_close (reg->dict);
419 dict_close (reg->matchDict);
420 sortIdx_close (reg->sortIdx);
422 isams_close (reg->isams);
424 isc_close (reg->isamc);
426 isamb_close (reg->isamb);
427 rec_close (®->records);
430 recTypes_destroy (reg->recTypes);
431 zebra_maps_close (reg->zebra_maps);
432 zebraRankDestroy (reg);
433 bfs_destroy (reg->bfs);
434 data1_destroy (reg->dh);
436 xfree (reg->sortKeys.buf);
437 xfree (reg->keys.buf);
438 if (reg->keys.codec_handle)
439 iscz1_stop(reg->keys.codec_handle);
440 xfree (reg->key_buf);
445 int zebra_stop(ZebraService zs)
449 yaz_log (LOG_API, "zebra_stop");
453 zebra_close (zs->sessions);
456 zebra_mutex_cond_destroy (&zs->session_lock);
459 passwd_db_close (zs->passwd_db);
461 recTypeClass_destroy(zs->record_classes);
462 nmem_destroy(zs->nmem);
463 res_close (zs->global_res);
464 xfree (zs->configName);
469 int zebra_close (ZebraHandle zh)
472 struct zebra_session **sp;
475 yaz_log(LOG_API,"zebra_close");
482 yaz_log (LOG_DEBUG, "zebra_close zh=%p", zh);
483 resultSetDestroy (zh, -1, 0, 0);
486 zebra_register_close (zh->service, zh->reg);
487 zebra_close_res (zh);
489 xfree (zh->record_encoding);
491 for (i = 0; i < zh->num_basenames; i++)
492 xfree (zh->basenames[i]);
493 xfree (zh->basenames);
495 if (zh->iconv_to_utf8 != 0)
496 yaz_iconv_close (zh->iconv_to_utf8);
497 if (zh->iconv_from_utf8 != 0)
498 yaz_iconv_close (zh->iconv_from_utf8);
500 zebra_mutex_cond_lock (&zs->session_lock);
501 zebra_lock_destroy (zh->lock_normal);
502 zebra_lock_destroy (zh->lock_shadow);
514 zebra_mutex_cond_unlock (&zs->session_lock);
515 xfree (zh->reg_name);
516 xfree (zh->user_perm);
517 zh->service=0; /* more likely to trigger an assert */
518 xfree (zh->path_reg);
523 struct map_baseinfo {
529 char **new_basenames;
533 static Res zebra_open_res (ZebraHandle zh)
542 sprintf (fname, "%.200s/zebra.cfg", zh->path_reg);
543 res = res_open (fname, zh->service->global_res, 0);
545 res = zh->service->global_res;
547 else if (*zh->reg_name == 0)
549 res = zh->service->global_res;
553 yaz_log (LOG_WARN, "no register root specified");
554 return 0; /* no path for register - fail! */
559 static void zebra_close_res (ZebraHandle zh)
563 if (zh->res != zh->service->global_res)
568 static int zebra_select_register (ZebraHandle zh, const char *new_reg)
572 if (zh->res && strcmp (zh->reg_name, new_reg) == 0)
576 assert (zh->reg == 0);
577 assert (*zh->reg_name == 0);
583 resultSetInvalidate (zh);
584 zebra_register_close (zh->service, zh->reg);
589 xfree (zh->reg_name);
590 zh->reg_name = xstrdup (new_reg);
592 xfree (zh->path_reg);
594 if (zh->service->path_root)
596 zh->path_reg = xmalloc (strlen(zh->service->path_root) +
597 strlen(zh->reg_name) + 3);
598 strcpy (zh->path_reg, zh->service->path_root);
601 strcat (zh->path_reg, "/");
602 strcat (zh->path_reg, zh->reg_name);
605 zh->res = zebra_open_res (zh);
608 zebra_lock_destroy (zh->lock_normal);
612 zebra_lock_destroy (zh->lock_shadow);
618 const char *lock_area =res_get (zh->res, "lockDir");
620 if (!lock_area && zh->path_reg)
621 res_set (zh->res, "lockDir", zh->path_reg);
622 sprintf (fname, "norm.%s.LCK", zh->reg_name);
624 zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
626 sprintf (fname, "shadow.%s.LCK", zh->reg_name);
628 zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
634 void map_basenames_func (void *vp, const char *name, const char *value)
636 struct map_baseinfo *p = (struct map_baseinfo *) vp;
638 char fromdb[128], todb[8][128];
641 sscanf (value, "%127s %127s %127s %127s %127s %127s %127s %127s %127s",
642 fromdb, todb[0], todb[1], todb[2], todb[3], todb[4],
643 todb[5], todb[6], todb[7]);
647 for (i = 0; i<p->num_bases; i++)
648 if (p->basenames[i] && !STRCASECMP (p->basenames[i], fromdb))
651 for (i = 0; i < no; i++)
653 if (p->new_num_bases == p->new_num_max)
655 p->new_basenames[(p->new_num_bases)++] =
656 nmem_strdup (p->mem, todb[i]);
662 void map_basenames (ZebraHandle zh, ODR stream,
663 int *num_bases, char ***basenames)
665 struct map_baseinfo info;
666 struct map_baseinfo *p = &info;
669 yaz_log(LOG_API,"map_basenames ");
673 info.num_bases = *num_bases;
674 info.basenames = *basenames;
675 info.new_num_max = 128;
676 info.new_num_bases = 0;
677 info.new_basenames = (char **)
678 odr_malloc (stream, sizeof(*info.new_basenames) * info.new_num_max);
679 info.mem = stream->mem;
681 res_trav (zh->service->global_res, "mapdb", &info, map_basenames_func);
683 for (i = 0; i<p->num_bases; i++)
684 if (p->basenames[i] && p->new_num_bases < p->new_num_max)
686 p->new_basenames[(p->new_num_bases)++] =
687 nmem_strdup (p->mem, p->basenames[i]);
689 *num_bases = info.new_num_bases;
690 *basenames = info.new_basenames;
691 for (i = 0; i<*num_bases; i++)
692 logf (LOG_DEBUG, "base %s", (*basenames)[i]);
695 int zebra_select_database (ZebraHandle zh, const char *basename)
698 yaz_log(LOG_API,"zebra_select_database %s",basename);
700 return zebra_select_databases (zh, 1, &basename);
703 int zebra_select_databases (ZebraHandle zh, int num_bases,
704 const char **basenames)
711 yaz_log(LOG_API,"zebra_select_databases n=%d [0]=%s",
712 num_bases,basenames[0]);
720 for (i = 0; i < zh->num_basenames; i++)
721 xfree (zh->basenames[i]);
722 xfree (zh->basenames);
724 zh->num_basenames = num_bases;
725 zh->basenames = xmalloc (zh->num_basenames * sizeof(*zh->basenames));
726 for (i = 0; i < zh->num_basenames; i++)
727 zh->basenames[i] = xstrdup (basenames[i]);
729 cp = strrchr(basenames[0], '/');
732 len = cp - basenames[0];
733 new_reg = xmalloc (len + 1);
734 memcpy (new_reg, basenames[0], len);
738 new_reg = xstrdup ("");
739 for (i = 1; i<num_bases; i++)
743 cp1 = strrchr (basenames[i], '/');
751 if (len != cp1 - basenames[i] ||
752 memcmp (basenames[i], new_reg, len))
767 zebra_select_register (zh, new_reg);
774 if (!zh->lock_normal || !zh->lock_shadow)
782 int zebra_search_RPN (ZebraHandle zh, ODR o,
783 Z_RPNQuery *query, const char *setname, int *hits)
788 yaz_log(LOG_API,"zebra_search_rpn");
793 if (zebra_begin_read (zh))
796 zebra_livcode_transform(zh, query);
798 resultSetAddRPN (zh, odr_extract_mem(o), query,
799 zh->num_basenames, zh->basenames, setname);
802 max = res_get (zh->res, "maxhits");
808 while (maxhits>100) { maxhits/=10; i++;}
809 while (i--) maxhits *= 10;
811 if (zh->hits > maxhits) { /* too large for yaz to handle */
812 logf(LOG_DEBUG,"limiting hits to "ZINT_FORMAT, maxhits);
813 *hits=maxhits; /* round it down to two digits, to look like rounded */
820 int zebra_records_retrieve (ZebraHandle zh, ODR stream,
821 const char *setname, Z_RecordComposition *comp,
822 oid_value input_format, int num_recs,
823 ZebraRetrievalRecord *recs)
826 int i, *pos_array, ret = 0;
828 yaz_log(LOG_API,"zebra_records_retrieve n=%d",num_recs);
834 zh->errString = odr_strdup (stream, setname);
840 if (zebra_begin_read (zh))
843 pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
844 for (i = 0; i<num_recs; i++)
845 pos_array[i] = recs[i].position;
846 poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
849 logf (LOG_DEBUG, "zebraPosSetCreate error");
851 zh->errString = nmem_strdup (stream->mem, setname);
856 for (i = 0; i<num_recs; i++)
861 recs[i].format = VAL_SUTRS;
862 recs[i].len = strlen(poset[i].term);
863 recs[i].buf = poset[i].term;
864 recs[i].base = poset[i].db;
866 else if (poset[i].sysno)
869 zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
870 stream, input_format, comp,
871 &recs[i].format, &recs[i].buf,
874 recs[i].errString = NULL;
880 sprintf (num_str, "%d", pos_array[i]);
882 zh->errString = odr_strdup (stream, num_str);
887 zebraPosSetDestroy (zh, poset, num_recs);
894 int zebra_scan (ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
895 oid_value attributeset,
896 int *position, int *num_entries, ZebraScanEntry **entries,
900 yaz_log(LOG_API,"zebra_scan");
902 if (zebra_begin_read (zh))
908 rpn_scan (zh, stream, zapt, attributeset,
909 zh->num_basenames, zh->basenames, position,
910 num_entries, entries, is_partial, 0, 0);
915 int zebra_sort (ZebraHandle zh, ODR stream,
916 int num_input_setnames, const char **input_setnames,
917 const char *output_setname, Z_SortKeySpecList *sort_sequence,
921 yaz_log(LOG_API,"zebra_sort");
923 if (zebra_begin_read (zh))
925 resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
926 output_setname, sort_sequence, sort_status);
931 int zebra_deleleResultSet(ZebraHandle zh, int function,
932 int num_setnames, char **setnames,
937 yaz_log(LOG_API,"zebra_deleleResultSet n=%d",num_setnames);
939 if (zebra_begin_read(zh))
940 return Z_DeleteStatus_systemProblemAtTarget;
943 case Z_DeleteResultSetRequest_list:
944 resultSetDestroy (zh, num_setnames, setnames, statuses);
946 case Z_DeleteResultSetRequest_all:
947 resultSetDestroy (zh, -1, 0, statuses);
951 status = Z_DeleteStatus_success;
952 for (i = 0; i<num_setnames; i++)
953 if (statuses[i] == Z_DeleteStatus_resultSetDidNotExist)
954 status = statuses[i];
958 int zebra_errCode (ZebraHandle zh)
962 yaz_log(LOG_API,"zebra_errCode: %d",zh->errCode);
965 yaz_log(LOG_API,"zebra_errCode: o");
969 const char *zebra_errString (ZebraHandle zh)
973 e= diagbib1_str (zh->errCode);
974 yaz_log(LOG_API,"zebra_errString: %s",e);
978 char *zebra_errAdd (ZebraHandle zh)
983 yaz_log(LOG_API,"zebra_errAdd: %s",a);
987 void zebra_clearError(ZebraHandle zh)
996 int zebra_auth (ZebraHandle zh, const char *user, const char *pass)
1006 sprintf(u, "perm.%.30s", user ? user : "anonymous");
1007 p = res_get(zs->global_res, u);
1008 xfree (zh->user_perm);
1009 zh->user_perm = xstrdup(p ? p : "r");
1011 /* users that don't require a password .. */
1012 if (zh->user_perm && strchr(zh->user_perm, 'a'))
1015 if (!zs->passwd_db || !passwd_db_auth (zs->passwd_db, user, pass))
1020 int zebra_admin_import_begin (ZebraHandle zh, const char *database,
1021 const char *record_type)
1024 yaz_log(LOG_API,"zebra_admin_import_begin db=%s rt=%s",
1025 database, record_type);
1027 if (zebra_select_database(zh, database))
1029 if (zebra_begin_trans (zh, 1))
1034 int zebra_admin_import_end (ZebraHandle zh)
1037 yaz_log(LOG_API,"zebra_admin_import_end");
1039 zebra_end_trans (zh);
1043 int zebra_admin_import_segment (ZebraHandle zh, Z_Segment *segment)
1048 yaz_log(LOG_API,"zebra_admin_import_segment");
1050 for (i = 0; i<segment->num_segmentRecords; i++)
1052 Z_NamePlusRecord *npr = segment->segmentRecords[i];
1054 printf ("--------------%d--------------------\n", i);
1055 if (npr->which == Z_NamePlusRecord_intermediateFragment)
1057 Z_FragmentSyntax *fragment = npr->u.intermediateFragment;
1058 if (fragment->which == Z_FragmentSyntax_notExternallyTagged)
1060 Odr_oct *oct = fragment->u.notExternallyTagged;
1061 printf ("%.*s", (oct->len > 100 ? 100 : oct->len) ,
1066 zebra_update_record(zh,
1067 0, /* record Type */
1079 int zebra_admin_exchange_record (ZebraHandle zh,
1080 const char *rec_buf,
1082 const char *recid_buf, size_t recid_len,
1084 /* 1 = insert. Fail it already exists */
1085 /* 2 = replace. Fail it does not exist */
1086 /* 3 = delete. Fail if does not exist */
1087 /* 4 = update. Insert/replace */
1093 yaz_log(LOG_API,"zebra_admin_exchange_record ac=%d", action);
1096 if (!recid_buf || recid_len <= 0 || recid_len >= sizeof(recid_z))
1098 memcpy (recid_z, recid_buf, recid_len);
1099 recid_z[recid_len] = 0;
1101 if (zebra_begin_trans(zh, 1))
1104 rinfo = dict_lookup (zh->reg->matchDict, recid_z);
1107 if (action == 1) /* fail if insert */
1109 zebra_end_trans(zh);
1113 memcpy (&sysno, rinfo+1, sizeof(sysno));
1117 if (action == 2 || action == 3) /* fail if delete or update */
1119 zebra_end_trans(zh);
1122 action = 1; /* make it an insert (if it's an update).. */
1124 buffer_extract_record (zh, rec_buf, rec_len,
1125 action == 3 ? 1 : 0 /* delete flag */,
1131 0, /* force update */
1132 1 /* allow update */
1136 dict_insert (zh->reg->matchDict, recid_z, sizeof(sysno), &sysno);
1138 else if (action == 3)
1140 dict_delete (zh->reg->matchDict, recid_z);
1142 zebra_end_trans(zh);
1146 int delete_w_handle(const char *info, void *handle)
1148 ZebraHandle zh = (ZebraHandle) handle;
1151 if (*info == sizeof(pos))
1153 memcpy (&pos, info+1, sizeof(pos));
1154 isamb_unlink(zh->reg->isamb, pos);
1159 static int delete_SU_handle(void *handle, int ord)
1161 ZebraHandle zh = (ZebraHandle) handle;
1165 ord_len = key_SU_encode (ord, ord_buf);
1166 ord_buf[ord_len] = '\0';
1168 assert (zh->reg->isamb);
1169 dict_delete_subtree(zh->reg->dict, ord_buf,
1170 zh, delete_w_handle);
1174 int zebra_drop_database (ZebraHandle zh, const char *database)
1178 yaz_log(LOG_API,"zebra_drop_database");
1181 if (zebra_select_database (zh, database))
1183 if (zebra_begin_trans (zh, 1))
1187 zebraExplain_curDatabase (zh->reg->zei, database);
1189 zebraExplain_trav_ord(zh->reg->zei, zh, delete_SU_handle);
1190 zebraExplain_removeDatabase(zh->reg->zei, zh);
1194 yaz_log(LOG_WARN, "drop database only supported for isam:b");
1197 zebra_end_trans (zh);
1201 int zebra_create_database (ZebraHandle zh, const char *database)
1204 yaz_log(LOG_API,"zebra_create_database");
1207 if (zebra_select_database (zh, database))
1209 if (zebra_begin_trans (zh, 1))
1212 /* announce database */
1213 if (zebraExplain_newDatabase (zh->reg->zei, database, 0
1214 /* explainDatabase */))
1216 zebra_end_trans (zh);
1218 zh->errString = "database already exist";
1221 zebra_end_trans (zh);
1225 int zebra_string_norm (ZebraHandle zh, unsigned reg_id,
1226 const char *input_str, int input_len,
1227 char *output_str, int output_len)
1231 yaz_log(LOG_API,"zebra_string_norm ");
1233 if (!zh->reg->zebra_maps)
1235 wrbuf = zebra_replace(zh->reg->zebra_maps, reg_id, "",
1236 input_str, input_len);
1239 if (wrbuf_len(wrbuf) >= output_len)
1241 if (wrbuf_len(wrbuf))
1242 memcpy (output_str, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
1243 output_str[wrbuf_len(wrbuf)] = '\0';
1244 return wrbuf_len(wrbuf);
1248 int zebra_set_state (ZebraHandle zh, int val, int seqno)
1250 char state_fname[256];
1255 yaz_log(LOG_API,"zebra_set_state v=%d seq=%d", val, seqno);
1258 sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1259 fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1260 f = fopen (fname, "w");
1262 yaz_log (LOG_DEBUG, "%c %d %ld", val, seqno, p);
1263 fprintf (f, "%c %d %ld\n", val, seqno, p);
1269 int zebra_get_state (ZebraHandle zh, char *val, int *seqno)
1271 char state_fname[256];
1276 yaz_log(LOG_API,"zebra_get_state ");
1278 sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1279 fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1280 f = fopen (fname, "r");
1286 fscanf (f, "%c %d", val, seqno);
1293 int zebra_begin_read (ZebraHandle zh)
1295 return zebra_begin_trans(zh, 0);
1298 int zebra_end_read (ZebraHandle zh)
1300 return zebra_end_trans(zh);
1303 static void read_res_for_transaction(ZebraHandle zh)
1305 const char *group = res_get(zh->res, "group");
1308 zh->m_group = group;
1309 v = res_get_prefix(zh->res, "followLinks", group, "1");
1310 zh->m_follow_links = atoi(v);
1312 zh->m_record_id = res_get_prefix(zh->res, "recordId", group, 0);
1313 zh->m_record_type = res_get_prefix(zh->res, "recordType", group, 0);
1315 v = res_get_prefix(zh->res, "storeKeys", group, "1");
1316 zh->m_store_keys = atoi(v);
1318 v = res_get_prefix(zh->res, "storeData", group, "1");
1319 zh->m_store_data = atoi(v);
1321 v = res_get_prefix(zh->res, "explainDatabase", group, "0");
1322 zh->m_explain_database = atoi(v);
1324 v = res_get_prefix(zh->res, "openRW", group, "1");
1325 zh->m_flag_rw = atoi(v);
1327 v = res_get_prefix(zh->res, "fileVerboseLimit", group, "100000");
1328 zh->m_file_verbose_limit = atoi(v);
1331 int zebra_begin_trans (ZebraHandle zh, int rw)
1336 zh->errString = "zebra_begin_trans: no database selected";
1340 yaz_log(LOG_API,"zebra_begin_trans rw=%d",rw);
1344 if (rw && !strchr(zh->user_perm, 'w'))
1358 const char *rval = 0;
1363 read_res_for_transaction(zh);
1366 if (zh->trans_no != 1)
1369 zh->errString = "zebra_begin_trans: write trans not allowed within read trans";
1374 resultSetInvalidate (zh);
1375 zebra_register_close (zh->service, zh->reg);
1377 zh->trans_w_no = zh->trans_no;
1381 zh->records_inserted = 0;
1382 zh->records_updated = 0;
1383 zh->records_deleted = 0;
1384 zh->records_processed = 0;
1386 #if HAVE_SYS_TIMES_H
1390 if (zh->shadow_enable)
1391 rval = res_get (zh->res, "shadow");
1393 for (pass = 0; pass < 2; pass++)
1397 zebra_lock_r (zh->lock_normal);
1398 zebra_lock_w (zh->lock_shadow);
1402 zebra_lock_w (zh->lock_normal);
1403 zebra_lock_w (zh->lock_shadow);
1406 zebra_get_state (zh, &val, &seqno);
1409 yaz_log (LOG_WARN, "previous transaction didn't finish commit");
1410 zebra_unlock (zh->lock_shadow);
1411 zebra_unlock (zh->lock_normal);
1415 else if (val == 'd')
1419 BFiles bfs = bfs_create (res_get (zh->res, "shadow"),
1421 yaz_log (LOG_WARN, "previous transaction didn't reach commit");
1422 bf_commitClean (bfs, rval);
1427 yaz_log (LOG_WARN, "your previous transaction didn't finish");
1434 yaz_log (LOG_FATAL, "zebra_begin_trans couldn't finish commit");
1438 zebra_set_state (zh, 'd', seqno);
1440 zh->reg = zebra_register_open (zh->service, zh->reg_name,
1441 1, rval ? 1 : 0, zh->res,
1444 zh->reg->seqno = seqno;
1447 zebra_set_state (zh, 'o', seqno);
1449 zebra_unlock (zh->lock_shadow);
1450 zebra_unlock (zh->lock_normal);
1456 zh->errString = "zebra_begin_trans: cannot open register";
1457 yaz_log(LOG_FATAL, zh->errString);
1469 if (zh->trans_no != 1)
1471 zebra_flush_reg (zh);
1475 #if HAVE_SYS_TIMES_H
1484 if (!zh->lock_normal || !zh->lock_shadow)
1490 zebra_get_state (zh, &val, &seqno);
1496 else if (seqno != zh->reg->seqno)
1498 yaz_log (LOG_DEBUG, "reopen seqno cur/old %d/%d",
1499 seqno, zh->reg->seqno);
1502 else if (zh->reg->last_val != val)
1504 yaz_log (LOG_DEBUG, "reopen last cur/old %d/%d",
1505 val, zh->reg->last_val);
1512 zebra_lock_r (zh->lock_shadow);
1514 zebra_lock_r (zh->lock_normal);
1518 resultSetInvalidate (zh);
1519 zebra_register_close (zh->service, zh->reg);
1521 zh->reg = zebra_register_open (zh->service, zh->reg_name,
1522 0, val == 'c' ? 1 : 0,
1523 zh->res, zh->path_reg);
1526 zebra_unlock (zh->lock_normal);
1527 zebra_unlock (zh->lock_shadow);
1532 zh->reg->last_val = val;
1533 zh->reg->seqno = seqno;
1535 read_res_for_transaction(zh);
1539 int zebra_end_trans (ZebraHandle zh)
1541 ZebraTransactionStatus dummy;
1542 yaz_log(LOG_API,"zebra_end_trans");
1543 return zebra_end_transaction(zh, &dummy);
1546 int zebra_end_transaction (ZebraHandle zh, ZebraTransactionStatus *status)
1553 yaz_log(LOG_API,"zebra_end_transaction");
1555 status->processed = 0;
1556 status->inserted = 0;
1557 status->updated = 0;
1558 status->deleted = 0;
1562 if (!zh->res || !zh->reg)
1565 zh->errString = "zebra_end_trans: no open transaction";
1568 if (zh->trans_no != zh->trans_w_no)
1571 if (zh->trans_no != 0)
1574 /* release read lock */
1576 zebra_unlock (zh->lock_normal);
1577 zebra_unlock (zh->lock_shadow);
1580 { /* release write lock */
1584 yaz_log (LOG_DEBUG, "zebra_end_trans");
1585 rval = res_get (zh->res, "shadow");
1587 zebraExplain_runNumberIncrement (zh->reg->zei, 1);
1589 zebra_flush_reg (zh);
1591 resultSetInvalidate (zh);
1593 zebra_register_close (zh->service, zh->reg);
1596 yaz_log (LOG_LOG, "Records: "ZINT_FORMAT" i/u/d "
1597 ZINT_FORMAT"/"ZINT_FORMAT"/"ZINT_FORMAT,
1598 zh->records_processed, zh->records_inserted,
1599 zh->records_updated, zh->records_deleted);
1601 status->processed = zh->records_processed;
1602 status->inserted = zh->records_inserted;
1603 status->updated = zh->records_updated;
1604 status->deleted = zh->records_deleted;
1606 zebra_get_state (zh, &val, &seqno);
1609 BFiles bfs = bfs_create (rval, zh->path_reg);
1610 yaz_log (LOG_DEBUG, "deleting shadow val=%c", val);
1611 bf_commitClean (bfs, rval);
1616 zebra_set_state (zh, 'o', seqno);
1618 zebra_unlock (zh->lock_shadow);
1619 zebra_unlock (zh->lock_normal);
1622 #if HAVE_SYS_TIMES_H
1624 logf (LOG_LOG, "user/system: %ld/%ld",
1625 (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1626 (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1628 status->utime = (long) (zh->tms2.tms_utime - zh->tms1.tms_utime);
1629 status->stime = (long) (zh->tms2.tms_stime - zh->tms1.tms_stime);
1634 int zebra_repository_update (ZebraHandle zh, const char *path)
1638 logf (LOG_API, "updating %s", path);
1639 repositoryUpdate (zh, path);
1643 int zebra_repository_delete (ZebraHandle zh, const char *path)
1647 logf (LOG_API, "deleting %s", path);
1648 repositoryDelete (zh, path);
1652 int zebra_repository_show (ZebraHandle zh, const char *path)
1655 yaz_log(LOG_API,"zebra_repository_show");
1657 repositoryShow (zh, path);
1661 static int zebra_commit_ex (ZebraHandle zh, int clean_only)
1675 rval = res_get (zh->res, "shadow");
1678 logf (LOG_WARN, "Cannot perform commit");
1679 logf (LOG_WARN, "No shadow area defined");
1683 zebra_lock_w (zh->lock_normal);
1684 zebra_lock_r (zh->lock_shadow);
1686 bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1688 zebra_get_state (zh, &val, &seqno);
1691 bf_cache (bfs, rval);
1692 if (bf_commitExists (bfs))
1695 zebra_set_state (zh, 'd', seqno);
1698 zebra_set_state (zh, 'c', seqno);
1700 logf (LOG_DEBUG, "commit start");
1701 bf_commitExec (bfs);
1706 logf (LOG_DEBUG, "commit clean");
1707 bf_commitClean (bfs, rval);
1709 zebra_set_state (zh, 'o', seqno);
1713 logf (LOG_LOG, "nothing to commit");
1717 zebra_unlock (zh->lock_shadow);
1718 zebra_unlock (zh->lock_normal);
1722 int zebra_clean (ZebraHandle zh)
1724 yaz_log(LOG_API,"zebra_clean");
1725 return zebra_commit_ex(zh, 1);
1728 int zebra_commit (ZebraHandle zh)
1730 yaz_log(LOG_API,"zebra_commit");
1731 return zebra_commit_ex(zh, 0);
1734 int zebra_init (ZebraHandle zh)
1739 yaz_log(LOG_API,"zebra_init");
1747 rval = res_get (zh->res, "shadow");
1749 bfs = bfs_create (res_get (zh->service->global_res, "register"),
1754 bf_cache (bfs, rval);
1758 zebra_set_state (zh, 'o', 0);
1762 int zebra_compact (ZebraHandle zh)
1766 yaz_log(LOG_API,"zebra_compact");
1773 bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1779 int zebra_result (ZebraHandle zh, int *code, char **addinfo)
1782 yaz_log(LOG_API,"zebra_result");
1783 *code = zh->errCode;
1784 *addinfo = zh->errString;
1788 int zebra_shadow_enable (ZebraHandle zh, int value)
1791 yaz_log(LOG_API,"zebra_shadow_enable");
1793 zh->shadow_enable = value;
1797 int zebra_record_encoding (ZebraHandle zh, const char *encoding)
1800 yaz_log(LOG_API,"zebra_record_encoding");
1802 xfree (zh->record_encoding);
1806 * Something about charset aliases. Oleg???
1809 if (zh->iconv_to_utf8 != 0)
1810 yaz_iconv_close(zh->iconv_to_utf8);
1811 if (zh->iconv_from_utf8 != 0)
1812 yaz_iconv_close(zh->iconv_from_utf8);
1814 zh->record_encoding = xstrdup (encoding);
1816 logf(LOG_DEBUG, "Reset record encoding: %s", encoding);
1819 yaz_iconv_open ("UTF-8", encoding);
1820 if (zh->iconv_to_utf8 == 0)
1821 yaz_log (LOG_WARN, "iconv: %s to UTF-8 unsupported", encoding);
1822 zh->iconv_from_utf8 =
1823 yaz_iconv_open (encoding, "UTF-8");
1824 if (zh->iconv_to_utf8 == 0)
1825 yaz_log (LOG_WARN, "iconv: UTF-8 to %s unsupported", encoding);
1830 int zebra_set_resource(ZebraHandle zh, const char *name, const char *value)
1833 yaz_log(LOG_API,"zebra_set_resource %s:%s",name,value);
1835 res_set(zh->res, name, value);
1839 const char *zebra_get_resource(ZebraHandle zh,
1840 const char *name, const char *defaultvalue)
1844 v= res_get_def( zh->res, name, (char *)defaultvalue);
1846 yaz_log(LOG_API,"zebra_get_resource %s:%s",name,v);
1850 /* moved from zebra_api_ext.c by pop */
1851 /* FIXME: Should this really be public??? -Heikki */
1853 int zebra_trans_no (ZebraHandle zh)
1856 yaz_log(LOG_API,"zebra_trans_no");
1857 return zh->trans_no;
1860 int zebra_get_shadow_enable (ZebraHandle zh)
1862 yaz_log(LOG_API,"zebra_get_shadow_enable");
1863 return (zh->shadow_enable);
1866 int zebra_set_shadow_enable (ZebraHandle zh, int value)
1868 yaz_log(LOG_API,"zebra_set_shadow_enable %d",value);
1869 zh->shadow_enable = value;
1873 /* almost the same as zebra_records_retrieve ... but how did it work?
1874 I mean for multiple records ??? CHECK ??? */
1875 void api_records_retrieve (ZebraHandle zh, ODR stream,
1876 const char *setname, Z_RecordComposition *comp,
1877 oid_value input_format, int num_recs,
1878 ZebraRetrievalRecord *recs)
1882 yaz_log(LOG_API,"api_records_retrieve s=%s n=%d",setname,num_recs);
1887 zh->errString = odr_strdup (stream, setname);
1893 if (zebra_begin_read (zh))
1896 pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
1897 for (i = 0; i<num_recs; i++)
1898 pos_array[i] = recs[i].position;
1899 poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
1902 logf (LOG_DEBUG, "zebraPosSetCreate error");
1904 zh->errString = nmem_strdup (stream->mem, setname);
1908 for (i = 0; i<num_recs; i++)
1912 recs[i].errCode = 0;
1913 recs[i].format = VAL_SUTRS;
1914 recs[i].len = strlen(poset[i].term);
1915 recs[i].buf = poset[i].term;
1916 recs[i].base = poset[i].db;
1920 else if (poset[i].sysno)
1922 /* changed here ??? CHECK ??? */
1925 zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
1926 stream, input_format, comp,
1931 recs[i].buf = (char *) odr_malloc(stream,recs[i].len);
1932 memcpy(recs[i].buf, b, recs[i].len);
1933 recs[i].errString = 0; /* Hmmm !!! we should get this */
1934 recs[i].sysno = poset[i].sysno;
1935 recs[i].score = poset[i].score;
1941 sprintf (num_str, "%d", pos_array[i]);
1943 zh->errString = odr_strdup (stream, num_str);
1948 zebraPosSetDestroy (zh, poset, num_recs);
1950 zebra_end_read (zh);
1955 /* ---------------------------------------------------------------------------
1956 Record insert(=update), delete
1958 If sysno is provided, then it's used to identify the record.
1959 If not, and match_criteria is provided, then sysno is guessed
1960 If not, and a record is provided, then sysno is got from there
1961 NOTE: Now returns 0 at success and updates sysno, which is an int*
1965 int zebra_add_record(ZebraHandle zh,
1966 const char *buf, int buf_size)
1969 return zebra_update_record(zh, 0, &sysno, 0, 0, buf, buf_size, 0);
1972 int zebra_insert_record (ZebraHandle zh,
1973 const char *recordType,
1974 SYSNO *sysno, const char *match, const char *fname,
1975 const char *buf, int buf_size, int force_update)
1978 yaz_log(LOG_API, "zebra_insert_record sysno=" ZINT_FORMAT, *sysno);
1980 if (buf_size < 1) buf_size = strlen(buf);
1982 if (zebra_begin_trans(zh, 1))
1984 res = buffer_extract_record (zh, buf, buf_size,
1985 0, /* delete_flag */
1991 0); /* allow_update */
1992 zebra_end_trans(zh);
1996 int zebra_update_record (ZebraHandle zh,
1997 const char *recordType,
1998 SYSNO* sysno, const char *match, const char *fname,
1999 const char *buf, int buf_size,
2004 yaz_log(LOG_API, "zebra_update_record sysno=" ZINT_FORMAT, *sysno);
2006 if (buf_size < 1) buf_size = strlen(buf);
2008 if (zebra_begin_trans(zh, 1))
2010 res = buffer_extract_record (zh, buf, buf_size,
2011 0, /* delete_flag */
2017 1); /* allow_update */
2018 zebra_end_trans(zh);
2022 int zebra_delete_record (ZebraHandle zh,
2023 const char *recordType,
2024 SYSNO *sysno, const char *match, const char *fname,
2025 const char *buf, int buf_size,
2029 yaz_log(LOG_API, "zebra_delete_record sysno=" ZINT_FORMAT, *sysno);
2031 if (buf_size < 1) buf_size = strlen(buf);
2033 if (zebra_begin_trans(zh, 1))
2035 res = buffer_extract_record (zh, buf, buf_size,
2036 1, /* delete_flag */
2042 1); /* allow_update */
2043 zebra_end_trans(zh);
2047 /* ---------------------------------------------------------------------------
2051 int zebra_search_PQF (ZebraHandle zh, const char *pqf_query,
2052 const char *setname, int *numhits)
2057 ODR odr = odr_createmem(ODR_ENCODE);
2059 yaz_log(LOG_API,"zebra_search_PQF s=%s q=%s",setname, pqf_query);
2061 query = p_query_rpn (odr, PROTO_Z3950, pqf_query);
2064 yaz_log (LOG_WARN, "bad query %s\n", pqf_query);
2066 res=zebra_search_RPN (zh, odr, query, setname, &hits);
2070 yaz_log(LOG_API,"Hits: %d",hits);
2078 /* ---------------------------------------------------------------------------
2079 Sort - a simplified interface, with optional read locks.
2081 int zebra_sort_by_specstr (ZebraHandle zh,
2083 const char *sort_spec,
2084 const char *output_setname,
2085 const char **input_setnames)
2087 int num_input_setnames = 0;
2088 int sort_status = 0;
2089 Z_SortKeySpecList *sort_sequence = yaz_sort_spec (stream, sort_spec);
2090 yaz_log(LOG_API,"sort (FIXME) ");
2093 logf(LOG_WARN,"invalid sort specs '%s'", sort_spec);
2098 /* we can do this, since the perl typemap code for char** will
2099 put a NULL at the end of list */
2100 while (input_setnames[num_input_setnames]) num_input_setnames++;
2102 if (zebra_begin_read (zh))
2105 resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
2106 output_setname, sort_sequence, &sort_status);