1 /* $Id: zebraapi.c,v 1.134 2004-10-01 15:36:15 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);
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)
791 yaz_log(LOG_API,"zebra_search_rpn");
796 if (zebra_begin_read (zh))
799 zebra_livcode_transform(zh, query);
801 resultSetAddRPN (zh, odr_extract_mem(o), query,
802 zh->num_basenames, zh->basenames, setname);
805 max = res_get (zh->res, "maxhits");
811 while (maxhits>100) { maxhits/=10; i++;}
812 while (i--) maxhits *= 10;
814 if (zh->hits > maxhits) { /* too large for yaz to handle */
815 logf(LOG_DEBUG,"limiting hits to "ZINT_FORMAT, maxhits);
816 *hits=maxhits; /* round it down to two digits, to look like rounded */
823 int zebra_records_retrieve (ZebraHandle zh, ODR stream,
824 const char *setname, Z_RecordComposition *comp,
825 oid_value input_format, int num_recs,
826 ZebraRetrievalRecord *recs)
829 int i, *pos_array, ret = 0;
831 yaz_log(LOG_API,"zebra_records_retrieve n=%d",num_recs);
837 zh->errString = odr_strdup (stream, setname);
843 if (zebra_begin_read (zh))
846 pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
847 for (i = 0; i<num_recs; i++)
848 pos_array[i] = recs[i].position;
849 poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
852 logf (LOG_DEBUG, "zebraPosSetCreate error");
854 zh->errString = nmem_strdup (stream->mem, setname);
859 for (i = 0; i<num_recs; i++)
864 recs[i].format = VAL_SUTRS;
865 recs[i].len = strlen(poset[i].term);
866 recs[i].buf = poset[i].term;
867 recs[i].base = poset[i].db;
869 else if (poset[i].sysno)
872 zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
873 stream, input_format, comp,
874 &recs[i].format, &recs[i].buf,
877 recs[i].errString = NULL;
883 sprintf (num_str, "%d", pos_array[i]);
885 zh->errString = odr_strdup (stream, num_str);
890 zebraPosSetDestroy (zh, poset, num_recs);
897 int zebra_scan (ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
898 oid_value attributeset,
899 int *position, int *num_entries, ZebraScanEntry **entries,
903 yaz_log(LOG_API,"zebra_scan");
905 if (zebra_begin_read (zh))
911 rpn_scan (zh, stream, zapt, attributeset,
912 zh->num_basenames, zh->basenames, position,
913 num_entries, entries, is_partial, 0, 0);
918 int zebra_sort (ZebraHandle zh, ODR stream,
919 int num_input_setnames, const char **input_setnames,
920 const char *output_setname, Z_SortKeySpecList *sort_sequence,
924 yaz_log(LOG_API,"zebra_sort");
926 if (zebra_begin_read (zh))
928 resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
929 output_setname, sort_sequence, sort_status);
934 int zebra_deleleResultSet(ZebraHandle zh, int function,
935 int num_setnames, char **setnames,
940 yaz_log(LOG_API,"zebra_deleleResultSet n=%d",num_setnames);
942 if (zebra_begin_read(zh))
943 return Z_DeleteStatus_systemProblemAtTarget;
946 case Z_DeleteResultSetRequest_list:
947 resultSetDestroy (zh, num_setnames, setnames, statuses);
949 case Z_DeleteResultSetRequest_all:
950 resultSetDestroy (zh, -1, 0, statuses);
954 status = Z_DeleteStatus_success;
955 for (i = 0; i<num_setnames; i++)
956 if (statuses[i] == Z_DeleteStatus_resultSetDidNotExist)
957 status = statuses[i];
961 int zebra_errCode (ZebraHandle zh)
965 yaz_log(LOG_API,"zebra_errCode: %d",zh->errCode);
968 yaz_log(LOG_API,"zebra_errCode: o");
972 const char *zebra_errString (ZebraHandle zh)
976 e= diagbib1_str (zh->errCode);
977 yaz_log(LOG_API,"zebra_errString: %s",e);
981 char *zebra_errAdd (ZebraHandle zh)
986 yaz_log(LOG_API,"zebra_errAdd: %s",a);
990 void zebra_clearError(ZebraHandle zh)
999 int zebra_auth (ZebraHandle zh, const char *user, const char *pass)
1009 sprintf(u, "perm.%.30s", user ? user : "anonymous");
1010 p = res_get(zs->global_res, u);
1011 xfree (zh->user_perm);
1012 zh->user_perm = xstrdup(p ? p : "r");
1014 /* users that don't require a password .. */
1015 if (zh->user_perm && strchr(zh->user_perm, 'a'))
1018 if (!zs->passwd_db || !passwd_db_auth (zs->passwd_db, user, pass))
1023 int zebra_admin_import_begin (ZebraHandle zh, const char *database,
1024 const char *record_type)
1027 yaz_log(LOG_API,"zebra_admin_import_begin db=%s rt=%s",
1028 database, record_type);
1030 if (zebra_select_database(zh, database))
1032 if (zebra_begin_trans (zh, 1))
1037 int zebra_admin_import_end (ZebraHandle zh)
1040 yaz_log(LOG_API,"zebra_admin_import_end");
1042 zebra_end_trans (zh);
1046 int zebra_admin_import_segment (ZebraHandle zh, Z_Segment *segment)
1051 yaz_log(LOG_API,"zebra_admin_import_segment");
1053 for (i = 0; i<segment->num_segmentRecords; i++)
1055 Z_NamePlusRecord *npr = segment->segmentRecords[i];
1057 printf ("--------------%d--------------------\n", i);
1058 if (npr->which == Z_NamePlusRecord_intermediateFragment)
1060 Z_FragmentSyntax *fragment = npr->u.intermediateFragment;
1061 if (fragment->which == Z_FragmentSyntax_notExternallyTagged)
1063 Odr_oct *oct = fragment->u.notExternallyTagged;
1064 printf ("%.*s", (oct->len > 100 ? 100 : oct->len) ,
1069 zebra_update_record(zh,
1070 0, /* record Type */
1082 int zebra_admin_exchange_record (ZebraHandle zh,
1083 const char *rec_buf,
1085 const char *recid_buf, size_t recid_len,
1087 /* 1 = insert. Fail it already exists */
1088 /* 2 = replace. Fail it does not exist */
1089 /* 3 = delete. Fail if does not exist */
1090 /* 4 = update. Insert/replace */
1096 yaz_log(LOG_API,"zebra_admin_exchange_record ac=%d", action);
1099 if (!recid_buf || recid_len <= 0 || recid_len >= sizeof(recid_z))
1101 memcpy (recid_z, recid_buf, recid_len);
1102 recid_z[recid_len] = 0;
1104 if (zebra_begin_trans(zh, 1))
1107 rinfo = dict_lookup (zh->reg->matchDict, recid_z);
1110 if (action == 1) /* fail if insert */
1112 zebra_end_trans(zh);
1116 memcpy (&sysno, rinfo+1, sizeof(sysno));
1120 if (action == 2 || action == 3) /* fail if delete or update */
1122 zebra_end_trans(zh);
1125 action = 1; /* make it an insert (if it's an update).. */
1127 buffer_extract_record (zh, rec_buf, rec_len,
1128 action == 3 ? 1 : 0 /* delete flag */,
1134 0, /* force update */
1135 1 /* allow update */
1139 dict_insert (zh->reg->matchDict, recid_z, sizeof(sysno), &sysno);
1141 else if (action == 3)
1143 dict_delete (zh->reg->matchDict, recid_z);
1145 zebra_end_trans(zh);
1149 int delete_w_handle(const char *info, void *handle)
1151 ZebraHandle zh = (ZebraHandle) handle;
1154 if (*info == sizeof(pos))
1156 memcpy (&pos, info+1, sizeof(pos));
1157 isamb_unlink(zh->reg->isamb, pos);
1162 static int delete_SU_handle(void *handle, int ord)
1164 ZebraHandle zh = (ZebraHandle) handle;
1168 ord_len = key_SU_encode (ord, ord_buf);
1169 ord_buf[ord_len] = '\0';
1171 assert (zh->reg->isamb);
1172 dict_delete_subtree(zh->reg->dict, ord_buf,
1173 zh, delete_w_handle);
1177 int zebra_drop_database (ZebraHandle zh, const char *database)
1181 yaz_log(LOG_API,"zebra_drop_database");
1184 if (zebra_select_database (zh, database))
1186 if (zebra_begin_trans (zh, 1))
1190 zebraExplain_curDatabase (zh->reg->zei, database);
1192 zebraExplain_trav_ord(zh->reg->zei, zh, delete_SU_handle);
1193 zebraExplain_removeDatabase(zh->reg->zei, zh);
1197 yaz_log(LOG_WARN, "drop database only supported for isam:b");
1200 zebra_end_trans (zh);
1204 int zebra_create_database (ZebraHandle zh, const char *database)
1207 yaz_log(LOG_API,"zebra_create_database");
1210 if (zebra_select_database (zh, database))
1212 if (zebra_begin_trans (zh, 1))
1215 /* announce database */
1216 if (zebraExplain_newDatabase (zh->reg->zei, database, 0
1217 /* explainDatabase */))
1219 zebra_end_trans (zh);
1221 zh->errString = "database already exist";
1224 zebra_end_trans (zh);
1228 int zebra_string_norm (ZebraHandle zh, unsigned reg_id,
1229 const char *input_str, int input_len,
1230 char *output_str, int output_len)
1234 yaz_log(LOG_API,"zebra_string_norm ");
1236 if (!zh->reg->zebra_maps)
1238 wrbuf = zebra_replace(zh->reg->zebra_maps, reg_id, "",
1239 input_str, input_len);
1242 if (wrbuf_len(wrbuf) >= output_len)
1244 if (wrbuf_len(wrbuf))
1245 memcpy (output_str, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
1246 output_str[wrbuf_len(wrbuf)] = '\0';
1247 return wrbuf_len(wrbuf);
1251 int zebra_set_state (ZebraHandle zh, int val, int seqno)
1253 char state_fname[256];
1258 yaz_log(LOG_API,"zebra_set_state v=%d seq=%d", val, seqno);
1261 sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1262 fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1263 f = fopen (fname, "w");
1265 yaz_log (LOG_DEBUG, "%c %d %ld", val, seqno, p);
1266 fprintf (f, "%c %d %ld\n", val, seqno, p);
1272 int zebra_get_state (ZebraHandle zh, char *val, int *seqno)
1274 char state_fname[256];
1279 yaz_log(LOG_API,"zebra_get_state ");
1281 sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1282 fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1283 f = fopen (fname, "r");
1289 fscanf (f, "%c %d", val, seqno);
1296 int zebra_begin_read (ZebraHandle zh)
1298 return zebra_begin_trans(zh, 0);
1301 int zebra_end_read (ZebraHandle zh)
1303 return zebra_end_trans(zh);
1306 static void read_res_for_transaction(ZebraHandle zh)
1308 const char *group = res_get(zh->res, "group");
1311 zh->m_group = group;
1312 v = res_get_prefix(zh->res, "followLinks", group, "1");
1313 zh->m_follow_links = atoi(v);
1315 zh->m_record_id = res_get_prefix(zh->res, "recordId", group, 0);
1316 zh->m_record_type = res_get_prefix(zh->res, "recordType", group, 0);
1318 v = res_get_prefix(zh->res, "storeKeys", group, "1");
1319 zh->m_store_keys = atoi(v);
1321 v = res_get_prefix(zh->res, "storeData", group, "1");
1322 zh->m_store_data = atoi(v);
1324 v = res_get_prefix(zh->res, "explainDatabase", group, "0");
1325 zh->m_explain_database = atoi(v);
1327 v = res_get_prefix(zh->res, "openRW", group, "1");
1328 zh->m_flag_rw = atoi(v);
1330 v = res_get_prefix(zh->res, "fileVerboseLimit", group, "100000");
1331 zh->m_file_verbose_limit = atoi(v);
1334 int zebra_begin_trans (ZebraHandle zh, int rw)
1339 zh->errString = "zebra_begin_trans: no database selected";
1343 yaz_log(LOG_API,"zebra_begin_trans rw=%d",rw);
1347 if (rw && !strchr(zh->user_perm, 'w'))
1361 const char *rval = 0;
1366 read_res_for_transaction(zh);
1369 if (zh->trans_no != 1)
1372 zh->errString = "zebra_begin_trans: write trans not allowed within read trans";
1377 resultSetInvalidate (zh);
1378 zebra_register_close (zh->service, zh->reg);
1380 zh->trans_w_no = zh->trans_no;
1384 zh->records_inserted = 0;
1385 zh->records_updated = 0;
1386 zh->records_deleted = 0;
1387 zh->records_processed = 0;
1389 #if HAVE_SYS_TIMES_H
1393 if (zh->shadow_enable)
1394 rval = res_get (zh->res, "shadow");
1396 for (pass = 0; pass < 2; pass++)
1400 zebra_lock_r (zh->lock_normal);
1401 zebra_lock_w (zh->lock_shadow);
1405 zebra_lock_w (zh->lock_normal);
1406 zebra_lock_w (zh->lock_shadow);
1409 zebra_get_state (zh, &val, &seqno);
1412 yaz_log (LOG_WARN, "previous transaction didn't finish commit");
1413 zebra_unlock (zh->lock_shadow);
1414 zebra_unlock (zh->lock_normal);
1418 else if (val == 'd')
1422 BFiles bfs = bfs_create (res_get (zh->res, "shadow"),
1424 yaz_log (LOG_WARN, "previous transaction didn't reach commit");
1425 bf_commitClean (bfs, rval);
1430 yaz_log (LOG_WARN, "your previous transaction didn't finish");
1437 yaz_log (LOG_FATAL, "zebra_begin_trans couldn't finish commit");
1441 zebra_set_state (zh, 'd', seqno);
1443 zh->reg = zebra_register_open (zh->service, zh->reg_name,
1444 1, rval ? 1 : 0, zh->res,
1447 zh->reg->seqno = seqno;
1450 zebra_set_state (zh, 'o', seqno);
1452 zebra_unlock (zh->lock_shadow);
1453 zebra_unlock (zh->lock_normal);
1459 zh->errString = "zebra_begin_trans: cannot open register";
1460 yaz_log(LOG_FATAL, zh->errString);
1472 if (zh->trans_no != 1)
1474 zebra_flush_reg (zh);
1478 #if HAVE_SYS_TIMES_H
1487 if (!zh->lock_normal || !zh->lock_shadow)
1493 zebra_get_state (zh, &val, &seqno);
1499 else if (seqno != zh->reg->seqno)
1501 yaz_log (LOG_DEBUG, "reopen seqno cur/old %d/%d",
1502 seqno, zh->reg->seqno);
1505 else if (zh->reg->last_val != val)
1507 yaz_log (LOG_DEBUG, "reopen last cur/old %d/%d",
1508 val, zh->reg->last_val);
1515 zebra_lock_r (zh->lock_shadow);
1517 zebra_lock_r (zh->lock_normal);
1521 resultSetInvalidate (zh);
1522 zebra_register_close (zh->service, zh->reg);
1524 zh->reg = zebra_register_open (zh->service, zh->reg_name,
1525 0, val == 'c' ? 1 : 0,
1526 zh->res, zh->path_reg);
1529 zebra_unlock (zh->lock_normal);
1530 zebra_unlock (zh->lock_shadow);
1535 zh->reg->last_val = val;
1536 zh->reg->seqno = seqno;
1538 read_res_for_transaction(zh);
1542 int zebra_end_trans (ZebraHandle zh)
1544 ZebraTransactionStatus dummy;
1545 yaz_log(LOG_API,"zebra_end_trans");
1546 return zebra_end_transaction(zh, &dummy);
1549 int zebra_end_transaction (ZebraHandle zh, ZebraTransactionStatus *status)
1556 yaz_log(LOG_API,"zebra_end_transaction");
1558 status->processed = 0;
1559 status->inserted = 0;
1560 status->updated = 0;
1561 status->deleted = 0;
1565 if (!zh->res || !zh->reg)
1568 zh->errString = "zebra_end_trans: no open transaction";
1571 if (zh->trans_no != zh->trans_w_no)
1574 if (zh->trans_no != 0)
1577 /* release read lock */
1579 zebra_unlock (zh->lock_normal);
1580 zebra_unlock (zh->lock_shadow);
1583 { /* release write lock */
1587 yaz_log (LOG_DEBUG, "zebra_end_trans");
1588 rval = res_get (zh->res, "shadow");
1590 zebraExplain_runNumberIncrement (zh->reg->zei, 1);
1592 zebra_flush_reg (zh);
1594 resultSetInvalidate (zh);
1596 zebra_register_close (zh->service, zh->reg);
1599 yaz_log (LOG_LOG, "Records: "ZINT_FORMAT" i/u/d "
1600 ZINT_FORMAT"/"ZINT_FORMAT"/"ZINT_FORMAT,
1601 zh->records_processed, zh->records_inserted,
1602 zh->records_updated, zh->records_deleted);
1604 status->processed = zh->records_processed;
1605 status->inserted = zh->records_inserted;
1606 status->updated = zh->records_updated;
1607 status->deleted = zh->records_deleted;
1609 zebra_get_state (zh, &val, &seqno);
1612 BFiles bfs = bfs_create (rval, zh->path_reg);
1613 yaz_log (LOG_DEBUG, "deleting shadow val=%c", val);
1614 bf_commitClean (bfs, rval);
1619 zebra_set_state (zh, 'o', seqno);
1621 zebra_unlock (zh->lock_shadow);
1622 zebra_unlock (zh->lock_normal);
1625 #if HAVE_SYS_TIMES_H
1627 logf (LOG_LOG, "user/system: %ld/%ld",
1628 (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1629 (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1631 status->utime = (long) (zh->tms2.tms_utime - zh->tms1.tms_utime);
1632 status->stime = (long) (zh->tms2.tms_stime - zh->tms1.tms_stime);
1637 int zebra_repository_update (ZebraHandle zh, const char *path)
1641 logf (LOG_API, "updating %s", path);
1642 repositoryUpdate (zh, path);
1646 int zebra_repository_delete (ZebraHandle zh, const char *path)
1650 logf (LOG_API, "deleting %s", path);
1651 repositoryDelete (zh, path);
1655 int zebra_repository_show (ZebraHandle zh, const char *path)
1658 yaz_log(LOG_API,"zebra_repository_show");
1660 repositoryShow (zh, path);
1664 static int zebra_commit_ex (ZebraHandle zh, int clean_only)
1678 rval = res_get (zh->res, "shadow");
1681 logf (LOG_WARN, "Cannot perform commit");
1682 logf (LOG_WARN, "No shadow area defined");
1686 zebra_lock_w (zh->lock_normal);
1687 zebra_lock_r (zh->lock_shadow);
1689 bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1691 zebra_get_state (zh, &val, &seqno);
1694 bf_cache (bfs, rval);
1695 if (bf_commitExists (bfs))
1698 zebra_set_state (zh, 'd', seqno);
1701 zebra_set_state (zh, 'c', seqno);
1703 logf (LOG_DEBUG, "commit start");
1704 bf_commitExec (bfs);
1709 logf (LOG_DEBUG, "commit clean");
1710 bf_commitClean (bfs, rval);
1712 zebra_set_state (zh, 'o', seqno);
1716 logf (LOG_LOG, "nothing to commit");
1720 zebra_unlock (zh->lock_shadow);
1721 zebra_unlock (zh->lock_normal);
1725 int zebra_clean (ZebraHandle zh)
1727 yaz_log(LOG_API,"zebra_clean");
1728 return zebra_commit_ex(zh, 1);
1731 int zebra_commit (ZebraHandle zh)
1733 yaz_log(LOG_API,"zebra_commit");
1734 return zebra_commit_ex(zh, 0);
1737 int zebra_init (ZebraHandle zh)
1742 yaz_log(LOG_API,"zebra_init");
1750 rval = res_get (zh->res, "shadow");
1752 bfs = bfs_create (res_get (zh->service->global_res, "register"),
1757 bf_cache (bfs, rval);
1761 zebra_set_state (zh, 'o', 0);
1765 int zebra_compact (ZebraHandle zh)
1769 yaz_log(LOG_API,"zebra_compact");
1776 bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1782 int zebra_result (ZebraHandle zh, int *code, char **addinfo)
1785 yaz_log(LOG_API,"zebra_result");
1786 *code = zh->errCode;
1787 *addinfo = zh->errString;
1791 int zebra_shadow_enable (ZebraHandle zh, int value)
1794 yaz_log(LOG_API,"zebra_shadow_enable");
1796 zh->shadow_enable = value;
1800 int zebra_record_encoding (ZebraHandle zh, const char *encoding)
1803 yaz_log(LOG_API,"zebra_record_encoding");
1805 xfree (zh->record_encoding);
1809 * Something about charset aliases. Oleg???
1812 if (zh->iconv_to_utf8 != 0)
1813 yaz_iconv_close(zh->iconv_to_utf8);
1814 if (zh->iconv_from_utf8 != 0)
1815 yaz_iconv_close(zh->iconv_from_utf8);
1817 zh->record_encoding = xstrdup (encoding);
1819 logf(LOG_DEBUG, "Reset record encoding: %s", encoding);
1822 yaz_iconv_open ("UTF-8", encoding);
1823 if (zh->iconv_to_utf8 == 0)
1824 yaz_log (LOG_WARN, "iconv: %s to UTF-8 unsupported", encoding);
1825 zh->iconv_from_utf8 =
1826 yaz_iconv_open (encoding, "UTF-8");
1827 if (zh->iconv_to_utf8 == 0)
1828 yaz_log (LOG_WARN, "iconv: UTF-8 to %s unsupported", encoding);
1833 int zebra_set_resource(ZebraHandle zh, const char *name, const char *value)
1836 yaz_log(LOG_API,"zebra_set_resource %s:%s",name,value);
1838 res_set(zh->res, name, value);
1842 const char *zebra_get_resource(ZebraHandle zh,
1843 const char *name, const char *defaultvalue)
1847 v= res_get_def( zh->res, name, (char *)defaultvalue);
1849 yaz_log(LOG_API,"zebra_get_resource %s:%s",name,v);
1853 /* moved from zebra_api_ext.c by pop */
1854 /* FIXME: Should this really be public??? -Heikki */
1856 int zebra_trans_no (ZebraHandle zh)
1859 yaz_log(LOG_API,"zebra_trans_no");
1860 return zh->trans_no;
1863 int zebra_get_shadow_enable (ZebraHandle zh)
1865 yaz_log(LOG_API,"zebra_get_shadow_enable");
1866 return (zh->shadow_enable);
1869 int zebra_set_shadow_enable (ZebraHandle zh, int value)
1871 yaz_log(LOG_API,"zebra_set_shadow_enable %d",value);
1872 zh->shadow_enable = value;
1876 /* almost the same as zebra_records_retrieve ... but how did it work?
1877 I mean for multiple records ??? CHECK ??? */
1878 void api_records_retrieve (ZebraHandle zh, ODR stream,
1879 const char *setname, Z_RecordComposition *comp,
1880 oid_value input_format, int num_recs,
1881 ZebraRetrievalRecord *recs)
1885 yaz_log(LOG_API,"api_records_retrieve s=%s n=%d",setname,num_recs);
1890 zh->errString = odr_strdup (stream, setname);
1896 if (zebra_begin_read (zh))
1899 pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
1900 for (i = 0; i<num_recs; i++)
1901 pos_array[i] = recs[i].position;
1902 poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
1905 logf (LOG_DEBUG, "zebraPosSetCreate error");
1907 zh->errString = nmem_strdup (stream->mem, setname);
1911 for (i = 0; i<num_recs; i++)
1915 recs[i].errCode = 0;
1916 recs[i].format = VAL_SUTRS;
1917 recs[i].len = strlen(poset[i].term);
1918 recs[i].buf = poset[i].term;
1919 recs[i].base = poset[i].db;
1923 else if (poset[i].sysno)
1925 /* changed here ??? CHECK ??? */
1928 zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
1929 stream, input_format, comp,
1934 recs[i].buf = (char *) odr_malloc(stream,recs[i].len);
1935 memcpy(recs[i].buf, b, recs[i].len);
1936 recs[i].errString = 0; /* Hmmm !!! we should get this */
1937 recs[i].sysno = poset[i].sysno;
1938 recs[i].score = poset[i].score;
1944 sprintf (num_str, "%d", pos_array[i]);
1946 zh->errString = odr_strdup (stream, num_str);
1951 zebraPosSetDestroy (zh, poset, num_recs);
1953 zebra_end_read (zh);
1958 /* ---------------------------------------------------------------------------
1959 Record insert(=update), delete
1961 If sysno is provided, then it's used to identify the record.
1962 If not, and match_criteria is provided, then sysno is guessed
1963 If not, and a record is provided, then sysno is got from there
1964 NOTE: Now returns 0 at success and updates sysno, which is an int*
1968 int zebra_add_record(ZebraHandle zh,
1969 const char *buf, int buf_size)
1972 return zebra_update_record(zh, 0, &sysno, 0, 0, buf, buf_size, 0);
1975 int zebra_insert_record (ZebraHandle zh,
1976 const char *recordType,
1977 SYSNO *sysno, const char *match, const char *fname,
1978 const char *buf, int buf_size, int force_update)
1981 yaz_log(LOG_API, "zebra_insert_record sysno=" ZINT_FORMAT, *sysno);
1983 if (buf_size < 1) buf_size = strlen(buf);
1985 if (zebra_begin_trans(zh, 1))
1987 res = buffer_extract_record (zh, buf, buf_size,
1988 0, /* delete_flag */
1994 0); /* allow_update */
1995 zebra_end_trans(zh);
1999 int zebra_update_record (ZebraHandle zh,
2000 const char *recordType,
2001 SYSNO* sysno, const char *match, const char *fname,
2002 const char *buf, int buf_size,
2007 yaz_log(LOG_API, "zebra_update_record sysno=" ZINT_FORMAT, *sysno);
2009 if (buf_size < 1) buf_size = strlen(buf);
2011 if (zebra_begin_trans(zh, 1))
2013 res = buffer_extract_record (zh, buf, buf_size,
2014 0, /* delete_flag */
2020 1); /* allow_update */
2021 zebra_end_trans(zh);
2025 int zebra_delete_record (ZebraHandle zh,
2026 const char *recordType,
2027 SYSNO *sysno, const char *match, const char *fname,
2028 const char *buf, int buf_size,
2032 yaz_log(LOG_API, "zebra_delete_record sysno=" ZINT_FORMAT, *sysno);
2034 if (buf_size < 1) buf_size = strlen(buf);
2036 if (zebra_begin_trans(zh, 1))
2038 res = buffer_extract_record (zh, buf, buf_size,
2039 1, /* delete_flag */
2045 1); /* allow_update */
2046 zebra_end_trans(zh);
2050 /* ---------------------------------------------------------------------------
2054 int zebra_search_PQF (ZebraHandle zh, const char *pqf_query,
2055 const char *setname, int *numhits)
2060 ODR odr = odr_createmem(ODR_ENCODE);
2062 yaz_log(LOG_API,"zebra_search_PQF s=%s q=%s",setname, pqf_query);
2064 query = p_query_rpn (odr, PROTO_Z3950, pqf_query);
2067 yaz_log (LOG_WARN, "bad query %s\n", pqf_query);
2069 res=zebra_search_RPN (zh, odr, query, setname, &hits);
2073 yaz_log(LOG_API,"Hits: %d",hits);
2081 /* ---------------------------------------------------------------------------
2082 Sort - a simplified interface, with optional read locks.
2084 int zebra_sort_by_specstr (ZebraHandle zh,
2086 const char *sort_spec,
2087 const char *output_setname,
2088 const char **input_setnames)
2090 int num_input_setnames = 0;
2091 int sort_status = 0;
2092 Z_SortKeySpecList *sort_sequence = yaz_sort_spec (stream, sort_spec);
2093 yaz_log(LOG_API,"sort (FIXME) ");
2096 logf(LOG_WARN,"invalid sort specs '%s'", sort_spec);
2101 /* we can do this, since the perl typemap code for char** will
2102 put a NULL at the end of list */
2103 while (input_setnames[num_input_setnames]) num_input_setnames++;
2105 if (zebra_begin_read (zh))
2108 resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
2109 output_setname, sort_sequence, &sort_status);