1 /* $Id: zebraapi.c,v 1.126 2004-08-10 15:21:48 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>
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 /* A simple log macro */
47 /* don't break with older yazen that lack log_app2 */
49 #define LOG_API LOG_APP2
51 #define LOG_API LOG_DEBUG
54 static Res zebra_open_res (ZebraHandle zh);
55 static void zebra_close_res (ZebraHandle zh);
58 static void zebra_chdir (ZebraService zs)
62 yaz_log(LOG_API,"zebra_chdir");
63 dir = res_get (zs->global_res, "chdir");
66 logf (LOG_DEBUG, "chdir %s", dir);
74 static void zebra_flush_reg (ZebraHandle zh)
77 yaz_log(LOG_API,"zebra_flush_reg");
79 zebraExplain_flush (zh->reg->zei, zh);
81 extract_flushWriteKeys (zh,1 /* final */);
82 zebra_index_merge (zh );
85 static struct zebra_register *zebra_register_open (ZebraService zs,
87 int rw, int useshadow,
89 const char *reg_path);
90 static void zebra_register_close (ZebraService zs, struct zebra_register *reg);
92 ZebraHandle zebra_open (ZebraService zs)
95 const char *default_encoding;
97 yaz_log(LOG_API,"zebra_open");
102 zh = (ZebraHandle) xmalloc (sizeof(*zh));
103 yaz_log (LOG_DEBUG, "zebra_open zs=%p returns %p", zs, zh);
106 zh->reg = 0; /* no register attached yet */
114 zh->reg_name = xstrdup ("");
116 zh->num_basenames = 0;
125 zh->shadow_enable = 1;
127 default_encoding = res_get_def(zs->global_res, "encoding", "ISO-8859-1");
128 zh->record_encoding = xstrdup (default_encoding);
131 yaz_iconv_open ("UTF-8", default_encoding);
132 if (zh->iconv_to_utf8 == 0)
133 yaz_log (LOG_WARN, "iconv: %s to UTF-8 unsupported",
135 zh->iconv_from_utf8 =
136 yaz_iconv_open (default_encoding, "UTF-8");
137 if (zh->iconv_to_utf8 == 0)
138 yaz_log (LOG_WARN, "iconv: UTF-8 to %s unsupported",
141 zebra_mutex_cond_lock (&zs->session_lock);
143 zh->next = zs->sessions;
146 zebra_mutex_cond_unlock (&zs->session_lock);
151 ZebraService zebra_start (const char *configName)
153 return zebra_start_res(configName, 0, 0);
156 ZebraService zebra_start_res (const char *configName, Res def_res, Res over_res)
160 yaz_log(LOG_API|LOG_LOG,"zebra_start %s",configName);
162 if ((res = res_open (configName, def_res, over_res)))
164 ZebraService zh = xmalloc (sizeof(*zh));
166 yaz_log (LOG_DEBUG, "Read resources `%s'", configName);
168 zh->global_res = res;
169 zh->configName = xstrdup(configName);
174 zebra_mutex_cond_init (&zh->session_lock);
175 if (!res_get (zh->global_res, "passwd"))
176 zh->passwd_db = NULL;
179 zh->passwd_db = passwd_db_open ();
181 logf (LOG_WARN|LOG_ERRNO, "passwd_db_open failed");
183 passwd_db_file (zh->passwd_db,
184 res_get (zh->global_res, "passwd"));
186 zh->path_root = res_get (zh->global_res, "root");
193 void zebra_pidfname(ZebraService zs, char *path)
195 zebra_lock_prefix (zs->global_res, path);
196 strcat(path, "zebrasrv.pid");
200 struct zebra_register *zebra_register_open (ZebraService zs, const char *name,
201 int rw, int useshadow, Res res,
202 const char *reg_path)
204 struct zebra_register *reg;
205 int record_compression = REC_COMPRESS_NONE;
206 const char *recordCompression = 0;
207 const char *profilePath;
212 reg = xmalloc (sizeof(*reg));
215 reg->name = xstrdup (name);
222 yaz_log (LOG_LOG|LOG_API, "zebra_register_open rw = %d useshadow=%d p=%p,n=%s,rp=%s",
223 rw, useshadow, reg, name, reg_path ? reg_path : "(none)");
225 reg->dh = data1_createx (DATA1_FLAG_XML);
228 reg->bfs = bfs_create (res_get (res, "register"), reg_path);
231 data1_destroy(reg->dh);
235 bf_cache (reg->bfs, res_get (res, "shadow"));
237 getcwd(cwd, sizeof(cwd)-1);
238 profilePath = res_get_def(res, "profilePath", DEFAULT_PROFILE_PATH);
239 yaz_log(LOG_LOG, "profilePath=%s cwd=%s", profilePath, cwd);
241 data1_set_tabpath (reg->dh, profilePath);
242 data1_set_tabroot (reg->dh, reg_path);
243 reg->recTypes = recTypes_init (reg->dh);
244 recTypes_default_handlers (reg->recTypes);
246 reg->zebra_maps = zebra_maps_open (res, reg_path);
247 reg->rank_classes = NULL;
251 reg->keys.buf_max = 0;
254 reg->keys.codec_handle = iscz1_start();
257 reg->sortKeys.buf = 0;
258 reg->sortKeys.buf_max = 0;
269 reg->key_file_no = 0;
272 zebraRankInstall (reg, rank1_class);
273 zebraRankInstall (reg, rankzv_class);
274 zebraRankInstall (reg, rankliv_class);
276 recordCompression = res_get_def (res, "recordCompression", "none");
277 if (!strcmp (recordCompression, "none"))
278 record_compression = REC_COMPRESS_NONE;
279 if (!strcmp (recordCompression, "bzip2"))
280 record_compression = REC_COMPRESS_BZIP2;
282 if (!(reg->records = rec_open (reg->bfs, rw, record_compression)))
284 logf (LOG_WARN, "rec_open");
289 reg->matchDict = dict_open (reg->bfs, GMATCH_DICT, 20, 1, 0);
291 if (!(reg->dict = dict_open (reg->bfs, FNAME_DICT, 40, rw, 0)))
293 logf (LOG_WARN, "dict_open");
296 if (!(reg->sortIdx = sortIdx_open (reg->bfs, rw)))
298 logf (LOG_WARN, "sortIdx_open");
301 if (res_get_match (res, "isam", "s", ISAM_DEFAULT))
303 struct ISAMS_M_s isams_m;
304 if (!(reg->isams = isams_open (reg->bfs, FNAME_ISAMS, rw,
305 key_isams_m(res, &isams_m))))
307 logf (LOG_WARN, "isams_open");
311 if (res_get_match (res, "isam", "c", ISAM_DEFAULT))
313 struct ISAMC_M_s isamc_m;
314 if (!(reg->isamc = isc_open (reg->bfs, FNAME_ISAMC,
315 rw, key_isamc_m(res, &isamc_m))))
317 logf (LOG_WARN, "isc_open");
321 if (res_get_match (res, "isam", "b", ISAM_DEFAULT))
323 struct ISAMC_M_s isamc_m;
325 if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
326 rw, key_isamc_m(res, &isamc_m), 0)))
328 logf (LOG_WARN, "isamb_open");
332 if (res_get_match (res, "isam", "bc", ISAM_DEFAULT))
334 struct ISAMC_M_s isamc_m;
336 if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
337 rw, key_isamc_m(res, &isamc_m), 1)))
339 logf (LOG_WARN, "isamb_open");
343 if (res_get_match (res, "isam", "null", ISAM_DEFAULT))
345 struct ISAMC_M_s isamc_m;
347 if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
348 rw, key_isamc_m(res, &isamc_m), -1)))
350 logf (LOG_WARN, "isamb_open");
354 reg->zei = zebraExplain_open (reg->records, reg->dh,
359 logf (LOG_WARN, "Cannot obtain EXPLAIN information");
363 yaz_log (LOG_DEBUG, "zebra_register_open ok p=%p", reg);
367 int zebra_admin_shutdown (ZebraHandle zh)
370 yaz_log(LOG_API,"zebra_admin_shutdown");
373 zebra_mutex_cond_lock (&zh->service->session_lock);
374 zh->service->stop_flag = 1;
375 zebra_mutex_cond_unlock (&zh->service->session_lock);
379 int zebra_admin_start (ZebraHandle zh)
383 yaz_log(LOG_API,"zebra_admin_start");
386 zebra_mutex_cond_lock (&zs->session_lock);
387 zebra_mutex_cond_unlock (&zs->session_lock);
391 static void zebra_register_close (ZebraService zs, struct zebra_register *reg)
394 yaz_log(LOG_LOG|LOG_API, "zebra_register_close p=%p", reg);
399 zebraExplain_close (reg->zei);
400 dict_close (reg->dict);
402 dict_close (reg->matchDict);
403 sortIdx_close (reg->sortIdx);
405 isams_close (reg->isams);
407 isc_close (reg->isamc);
409 isamb_close (reg->isamb);
410 rec_close (®->records);
413 recTypes_destroy (reg->recTypes);
414 zebra_maps_close (reg->zebra_maps);
415 zebraRankDestroy (reg);
416 bfs_destroy (reg->bfs);
417 data1_destroy (reg->dh);
419 xfree (reg->sortKeys.buf);
420 xfree (reg->keys.buf);
422 if (reg->keys.codec_handle)
423 iscz1_stop(reg->keys.codec_handle);
426 xfree (reg->key_buf);
431 int zebra_stop(ZebraService zs)
435 yaz_log (LOG_LOG|LOG_API, "zebra_stop");
439 zebra_close (zs->sessions);
442 zebra_mutex_cond_destroy (&zs->session_lock);
445 passwd_db_close (zs->passwd_db);
447 res_close (zs->global_res);
448 xfree (zs->configName);
453 int zebra_close (ZebraHandle zh)
456 struct zebra_session **sp;
459 yaz_log(LOG_API,"zebra_close");
466 yaz_log (LOG_DEBUG, "zebra_close zh=%p", zh);
467 resultSetDestroy (zh, -1, 0, 0);
470 zebra_register_close (zh->service, zh->reg);
471 zebra_close_res (zh);
473 xfree (zh->record_encoding);
475 for (i = 0; i < zh->num_basenames; i++)
476 xfree (zh->basenames[i]);
477 xfree (zh->basenames);
479 if (zh->iconv_to_utf8 != 0)
480 yaz_iconv_close (zh->iconv_to_utf8);
481 if (zh->iconv_from_utf8 != 0)
482 yaz_iconv_close (zh->iconv_from_utf8);
484 zebra_mutex_cond_lock (&zs->session_lock);
485 zebra_lock_destroy (zh->lock_normal);
486 zebra_lock_destroy (zh->lock_shadow);
498 zebra_mutex_cond_unlock (&zs->session_lock);
499 xfree (zh->reg_name);
500 xfree (zh->user_perm);
501 zh->service=0; /* more likely to trigger an assert */
502 xfree (zh->path_reg);
507 struct map_baseinfo {
513 char **new_basenames;
517 static Res zebra_open_res (ZebraHandle zh)
526 sprintf (fname, "%.200s/zebra.cfg", zh->path_reg);
527 res = res_open (fname, zh->service->global_res, 0);
529 res = zh->service->global_res;
531 else if (*zh->reg_name == 0)
533 res = zh->service->global_res;
537 yaz_log (LOG_WARN, "no register root specified");
538 return 0; /* no path for register - fail! */
543 static void zebra_close_res (ZebraHandle zh)
547 if (zh->res != zh->service->global_res)
552 static int zebra_select_register (ZebraHandle zh, const char *new_reg)
556 if (zh->res && strcmp (zh->reg_name, new_reg) == 0)
560 assert (zh->reg == 0);
561 assert (*zh->reg_name == 0);
567 resultSetInvalidate (zh);
568 zebra_register_close (zh->service, zh->reg);
573 xfree (zh->reg_name);
574 zh->reg_name = xstrdup (new_reg);
576 xfree (zh->path_reg);
578 if (zh->service->path_root)
580 zh->path_reg = xmalloc (strlen(zh->service->path_root) +
581 strlen(zh->reg_name) + 3);
582 strcpy (zh->path_reg, zh->service->path_root);
585 strcat (zh->path_reg, "/");
586 strcat (zh->path_reg, zh->reg_name);
589 zh->res = zebra_open_res (zh);
592 zebra_lock_destroy (zh->lock_normal);
596 zebra_lock_destroy (zh->lock_shadow);
602 const char *lock_area =res_get (zh->res, "lockDir");
604 if (!lock_area && zh->path_reg)
605 res_set (zh->res, "lockDir", zh->path_reg);
606 sprintf (fname, "norm.%s.LCK", zh->reg_name);
608 zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
610 sprintf (fname, "shadow.%s.LCK", zh->reg_name);
612 zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
618 void map_basenames_func (void *vp, const char *name, const char *value)
620 struct map_baseinfo *p = (struct map_baseinfo *) vp;
622 char fromdb[128], todb[8][128];
625 sscanf (value, "%127s %127s %127s %127s %127s %127s %127s %127s %127s",
626 fromdb, todb[0], todb[1], todb[2], todb[3], todb[4],
627 todb[5], todb[6], todb[7]);
631 for (i = 0; i<p->num_bases; i++)
632 if (p->basenames[i] && !STRCASECMP (p->basenames[i], fromdb))
635 for (i = 0; i < no; i++)
637 if (p->new_num_bases == p->new_num_max)
639 p->new_basenames[(p->new_num_bases)++] =
640 nmem_strdup (p->mem, todb[i]);
646 void map_basenames (ZebraHandle zh, ODR stream,
647 int *num_bases, char ***basenames)
649 struct map_baseinfo info;
650 struct map_baseinfo *p = &info;
653 yaz_log(LOG_API,"map_basenames ");
657 info.num_bases = *num_bases;
658 info.basenames = *basenames;
659 info.new_num_max = 128;
660 info.new_num_bases = 0;
661 info.new_basenames = (char **)
662 odr_malloc (stream, sizeof(*info.new_basenames) * info.new_num_max);
663 info.mem = stream->mem;
665 res_trav (zh->service->global_res, "mapdb", &info, map_basenames_func);
667 for (i = 0; i<p->num_bases; i++)
668 if (p->basenames[i] && p->new_num_bases < p->new_num_max)
670 p->new_basenames[(p->new_num_bases)++] =
671 nmem_strdup (p->mem, p->basenames[i]);
673 *num_bases = info.new_num_bases;
674 *basenames = info.new_basenames;
675 for (i = 0; i<*num_bases; i++)
676 logf (LOG_LOG, "base %s", (*basenames)[i]);
679 int zebra_select_database (ZebraHandle zh, const char *basename)
682 yaz_log(LOG_API,"zebra_select_database %s",basename);
684 return zebra_select_databases (zh, 1, &basename);
687 int zebra_select_databases (ZebraHandle zh, int num_bases,
688 const char **basenames)
695 yaz_log(LOG_API,"zebra_select_databases n=%d [0]=%s",
696 num_bases,basenames[0]);
704 for (i = 0; i < zh->num_basenames; i++)
705 xfree (zh->basenames[i]);
706 xfree (zh->basenames);
708 zh->num_basenames = num_bases;
709 zh->basenames = xmalloc (zh->num_basenames * sizeof(*zh->basenames));
710 for (i = 0; i < zh->num_basenames; i++)
711 zh->basenames[i] = xstrdup (basenames[i]);
713 cp = strrchr(basenames[0], '/');
716 len = cp - basenames[0];
717 new_reg = xmalloc (len + 1);
718 memcpy (new_reg, basenames[0], len);
722 new_reg = xstrdup ("");
723 for (i = 1; i<num_bases; i++)
727 cp1 = strrchr (basenames[i], '/');
735 if (len != cp1 - basenames[i] ||
736 memcmp (basenames[i], new_reg, len))
751 zebra_select_register (zh, new_reg);
758 if (!zh->lock_normal || !zh->lock_shadow)
766 int zebra_search_RPN (ZebraHandle zh, ODR o,
767 Z_RPNQuery *query, const char *setname, int *hits)
772 yaz_log(LOG_API,"zebra_search_rpn");
777 if (zebra_begin_read (zh))
780 zebra_livcode_transform(zh, query);
782 resultSetAddRPN (zh, odr_extract_mem(o), query,
783 zh->num_basenames, zh->basenames, setname);
786 max = res_get (zh->res, "maxhits");
792 while (maxhits>100) { maxhits/=10; i++;}
793 while (i--) maxhits *= 10;
795 if (zh->hits > maxhits) { /* too large for yaz to handle */
796 logf(LOG_LOG,"limiting hits to "ZINT_FORMAT, maxhits);
797 *hits=maxhits; /* round it down to two digits, to look like rounded */
804 int zebra_records_retrieve (ZebraHandle zh, ODR stream,
805 const char *setname, Z_RecordComposition *comp,
806 oid_value input_format, int num_recs,
807 ZebraRetrievalRecord *recs)
810 int i, *pos_array, ret = 0;
812 yaz_log(LOG_API,"zebra_records_retrieve n=%d",num_recs);
818 zh->errString = odr_strdup (stream, setname);
824 if (zebra_begin_read (zh))
827 pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
828 for (i = 0; i<num_recs; i++)
829 pos_array[i] = recs[i].position;
830 poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
833 logf (LOG_DEBUG, "zebraPosSetCreate error");
835 zh->errString = nmem_strdup (stream->mem, setname);
840 for (i = 0; i<num_recs; i++)
845 recs[i].format = VAL_SUTRS;
846 recs[i].len = strlen(poset[i].term);
847 recs[i].buf = poset[i].term;
848 recs[i].base = poset[i].db;
850 else if (poset[i].sysno)
853 zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
854 stream, input_format, comp,
855 &recs[i].format, &recs[i].buf,
858 recs[i].errString = NULL;
864 sprintf (num_str, "%d", pos_array[i]);
866 zh->errString = odr_strdup (stream, num_str);
871 zebraPosSetDestroy (zh, poset, num_recs);
878 int zebra_scan (ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
879 oid_value attributeset,
880 int *position, int *num_entries, ZebraScanEntry **entries,
884 yaz_log(LOG_API,"zebra_scan");
886 if (zebra_begin_read (zh))
892 rpn_scan (zh, stream, zapt, attributeset,
893 zh->num_basenames, zh->basenames, position,
894 num_entries, entries, is_partial, 0, 0);
899 int zebra_sort (ZebraHandle zh, ODR stream,
900 int num_input_setnames, const char **input_setnames,
901 const char *output_setname, Z_SortKeySpecList *sort_sequence,
905 yaz_log(LOG_API,"zebra_sort");
907 if (zebra_begin_read (zh))
909 resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
910 output_setname, sort_sequence, sort_status);
915 int zebra_deleleResultSet(ZebraHandle zh, int function,
916 int num_setnames, char **setnames,
921 yaz_log(LOG_API,"zebra_deleleResultSet n=%d",num_setnames);
923 if (zebra_begin_read(zh))
924 return Z_DeleteStatus_systemProblemAtTarget;
927 case Z_DeleteResultSetRequest_list:
928 resultSetDestroy (zh, num_setnames, setnames, statuses);
930 case Z_DeleteResultSetRequest_all:
931 resultSetDestroy (zh, -1, 0, statuses);
935 status = Z_DeleteStatus_success;
936 for (i = 0; i<num_setnames; i++)
937 if (statuses[i] == Z_DeleteStatus_resultSetDidNotExist)
938 status = statuses[i];
942 int zebra_errCode (ZebraHandle zh)
946 yaz_log(LOG_API,"zebra_errCode: %d",zh->errCode);
949 yaz_log(LOG_API,"zebra_errCode: o");
953 const char *zebra_errString (ZebraHandle zh)
957 e= diagbib1_str (zh->errCode);
958 yaz_log(LOG_API,"zebra_errString: %s",e);
962 char *zebra_errAdd (ZebraHandle zh)
967 yaz_log(LOG_API,"zebra_errAdd: %s",a);
971 void zebra_clearError(ZebraHandle zh)
980 int zebra_auth (ZebraHandle zh, const char *user, const char *pass)
990 sprintf(u, "perm.%.30s", user ? user : "anonymous");
991 p = res_get(zs->global_res, u);
992 xfree (zh->user_perm);
993 zh->user_perm = xstrdup(p ? p : "r");
995 /* users that don't require a password .. */
996 if (zh->user_perm && strchr(zh->user_perm, 'a'))
999 if (!zs->passwd_db || !passwd_db_auth (zs->passwd_db, user, pass))
1004 int zebra_admin_import_begin (ZebraHandle zh, const char *database,
1005 const char *record_type)
1008 yaz_log(LOG_API,"zebra_admin_import_begin db=%s rt=%s",
1009 database, record_type);
1011 if (zebra_select_database(zh, database))
1013 if (zebra_begin_trans (zh, 1))
1018 int zebra_admin_import_end (ZebraHandle zh)
1021 yaz_log(LOG_API,"zebra_admin_import_end");
1023 zebra_end_trans (zh);
1027 int zebra_admin_import_segment (ZebraHandle zh, Z_Segment *segment)
1032 yaz_log(LOG_API,"zebra_admin_import_segment");
1034 for (i = 0; i<segment->num_segmentRecords; i++)
1036 Z_NamePlusRecord *npr = segment->segmentRecords[i];
1038 printf ("--------------%d--------------------\n", i);
1039 if (npr->which == Z_NamePlusRecord_intermediateFragment)
1041 Z_FragmentSyntax *fragment = npr->u.intermediateFragment;
1042 if (fragment->which == Z_FragmentSyntax_notExternallyTagged)
1044 Odr_oct *oct = fragment->u.notExternallyTagged;
1045 printf ("%.*s", (oct->len > 100 ? 100 : oct->len) ,
1050 zebra_update_record(zh,
1051 0, /* record Type */
1063 int zebra_admin_exchange_record (ZebraHandle zh,
1064 const char *rec_buf,
1066 const char *recid_buf, size_t recid_len,
1068 /* 1 = insert. Fail it already exists */
1069 /* 2 = replace. Fail it does not exist */
1070 /* 3 = delete. Fail if does not exist */
1071 /* 4 = update. Insert/replace */
1077 yaz_log(LOG_API,"zebra_admin_exchange_record ac=%d", action);
1080 if (!recid_buf || recid_len <= 0 || recid_len >= sizeof(recid_z))
1082 memcpy (recid_z, recid_buf, recid_len);
1083 recid_z[recid_len] = 0;
1085 if (zebra_begin_trans(zh, 1))
1088 rinfo = dict_lookup (zh->reg->matchDict, recid_z);
1091 if (action == 1) /* fail if insert */
1093 zebra_end_trans(zh);
1097 memcpy (&sysno, rinfo+1, sizeof(sysno));
1101 if (action == 2 || action == 3) /* fail if delete or update */
1103 zebra_end_trans(zh);
1106 action = 1; /* make it an insert (if it's an update).. */
1108 buffer_extract_record (zh, rec_buf, rec_len,
1109 action == 3 ? 1 : 0 /* delete flag */,
1115 0, /* force update */
1116 1 /* allow update */
1120 dict_insert (zh->reg->matchDict, recid_z, sizeof(sysno), &sysno);
1122 else if (action == 3)
1124 dict_delete (zh->reg->matchDict, recid_z);
1126 zebra_end_trans(zh);
1130 int delete_w_handle(const char *info, void *handle)
1132 ZebraHandle zh = (ZebraHandle) handle;
1135 if (*info == sizeof(pos))
1137 memcpy (&pos, info+1, sizeof(pos));
1138 isamb_unlink(zh->reg->isamb, pos);
1143 static int delete_SU_handle(void *handle, int ord)
1145 ZebraHandle zh = (ZebraHandle) handle;
1149 ord_len = key_SU_encode (ord, ord_buf);
1150 ord_buf[ord_len] = '\0';
1152 assert (zh->reg->isamb);
1153 dict_delete_subtree(zh->reg->dict, ord_buf,
1154 zh, delete_w_handle);
1158 int zebra_drop_database (ZebraHandle zh, const char *database)
1162 yaz_log(LOG_API,"zebra_drop_database");
1165 if (zebra_select_database (zh, database))
1167 if (zebra_begin_trans (zh, 1))
1171 zebraExplain_curDatabase (zh->reg->zei, database);
1173 zebraExplain_trav_ord(zh->reg->zei, zh, delete_SU_handle);
1174 zebraExplain_removeDatabase(zh->reg->zei, zh);
1178 yaz_log(LOG_WARN, "drop database only supported for isam:b");
1181 zebra_end_trans (zh);
1185 int zebra_create_database (ZebraHandle zh, const char *database)
1188 yaz_log(LOG_API,"zebra_create_database");
1191 if (zebra_select_database (zh, database))
1193 if (zebra_begin_trans (zh, 1))
1196 /* announce database */
1197 if (zebraExplain_newDatabase (zh->reg->zei, database, 0
1198 /* explainDatabase */))
1200 zebra_end_trans (zh);
1202 zh->errString = "database already exist";
1205 zebra_end_trans (zh);
1209 int zebra_string_norm (ZebraHandle zh, unsigned reg_id,
1210 const char *input_str, int input_len,
1211 char *output_str, int output_len)
1215 yaz_log(LOG_API,"zebra_string_norm ");
1217 if (!zh->reg->zebra_maps)
1219 wrbuf = zebra_replace(zh->reg->zebra_maps, reg_id, "",
1220 input_str, input_len);
1223 if (wrbuf_len(wrbuf) >= output_len)
1225 if (wrbuf_len(wrbuf))
1226 memcpy (output_str, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
1227 output_str[wrbuf_len(wrbuf)] = '\0';
1228 return wrbuf_len(wrbuf);
1232 int zebra_set_state (ZebraHandle zh, int val, int seqno)
1234 char state_fname[256];
1239 yaz_log(LOG_API,"zebra_set_state v=%d seq=%d", val, seqno);
1242 sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1243 fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1244 f = fopen (fname, "w");
1246 yaz_log (LOG_DEBUG, "%c %d %ld", val, seqno, p);
1247 fprintf (f, "%c %d %ld\n", val, seqno, p);
1253 int zebra_get_state (ZebraHandle zh, char *val, int *seqno)
1255 char state_fname[256];
1260 yaz_log(LOG_API,"zebra_get_state ");
1262 sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1263 fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1264 f = fopen (fname, "r");
1270 fscanf (f, "%c %d", val, seqno);
1277 int zebra_begin_read (ZebraHandle zh)
1279 return zebra_begin_trans(zh, 0);
1282 int zebra_end_read (ZebraHandle zh)
1284 return zebra_end_trans(zh);
1287 static void read_res_for_transaction(ZebraHandle zh)
1289 const char *group = res_get(zh->res, "group");
1292 zh->m_group = group;
1293 v = res_get_prefix(zh->res, "followLinks", group, "1");
1294 zh->m_follow_links = atoi(v);
1296 zh->m_record_id = res_get_prefix(zh->res, "recordId", group, 0);
1297 zh->m_record_type = res_get_prefix(zh->res, "recordType", group, 0);
1299 v = res_get_prefix(zh->res, "storeKeys", group, "1");
1300 zh->m_store_keys = atoi(v);
1302 v = res_get_prefix(zh->res, "storeData", group, "1");
1303 zh->m_store_data = atoi(v);
1305 v = res_get_prefix(zh->res, "explainDatabase", group, "0");
1306 zh->m_explain_database = atoi(v);
1308 v = res_get_prefix(zh->res, "openRW", group, "1");
1309 zh->m_flag_rw = atoi(v);
1311 v = res_get_prefix(zh->res, "fileVerboseLimit", group, "100000");
1312 zh->m_file_verbose_limit = atoi(v);
1315 int zebra_begin_trans (ZebraHandle zh, int rw)
1320 zh->errString = "zebra_begin_trans: no database selected";
1324 yaz_log(LOG_API,"zebra_begin_trans rw=%d",rw);
1328 if (rw && !strchr(zh->user_perm, 'w'))
1342 const char *rval = 0;
1347 read_res_for_transaction(zh);
1350 if (zh->trans_no != 1)
1353 zh->errString = "zebra_begin_trans: write trans not allowed within read trans";
1358 resultSetInvalidate (zh);
1359 zebra_register_close (zh->service, zh->reg);
1361 zh->trans_w_no = zh->trans_no;
1365 zh->records_inserted = 0;
1366 zh->records_updated = 0;
1367 zh->records_deleted = 0;
1368 zh->records_processed = 0;
1370 #if HAVE_SYS_TIMES_H
1374 if (zh->shadow_enable)
1375 rval = res_get (zh->res, "shadow");
1377 for (pass = 0; pass < 2; pass++)
1381 zebra_lock_r (zh->lock_normal);
1382 zebra_lock_w (zh->lock_shadow);
1386 zebra_lock_w (zh->lock_normal);
1387 zebra_lock_w (zh->lock_shadow);
1390 zebra_get_state (zh, &val, &seqno);
1393 yaz_log (LOG_LOG, "previous transaction didn't finish commit");
1394 zebra_unlock (zh->lock_shadow);
1395 zebra_unlock (zh->lock_normal);
1399 else if (val == 'd')
1403 BFiles bfs = bfs_create (res_get (zh->res, "shadow"),
1405 yaz_log (LOG_LOG, "previous transaction didn't reach commit");
1406 bf_commitClean (bfs, rval);
1411 yaz_log (LOG_WARN, "your previous transaction didn't finish");
1418 yaz_log (LOG_FATAL, "zebra_begin_trans couldn't finish commit");
1422 zebra_set_state (zh, 'd', seqno);
1424 zh->reg = zebra_register_open (zh->service, zh->reg_name,
1425 1, rval ? 1 : 0, zh->res,
1428 zh->reg->seqno = seqno;
1431 zebra_set_state (zh, 'o', seqno);
1433 zebra_unlock (zh->lock_shadow);
1434 zebra_unlock (zh->lock_normal);
1440 zh->errString = "zebra_begin_trans: cannot open register";
1441 yaz_log(LOG_FATAL, zh->errString);
1453 if (zh->trans_no != 1)
1455 zebra_flush_reg (zh);
1459 #if HAVE_SYS_TIMES_H
1468 if (!zh->lock_normal || !zh->lock_shadow)
1474 zebra_get_state (zh, &val, &seqno);
1480 else if (seqno != zh->reg->seqno)
1482 yaz_log (LOG_LOG, "reopen seqno cur/old %d/%d",
1483 seqno, zh->reg->seqno);
1486 else if (zh->reg->last_val != val)
1488 yaz_log (LOG_LOG, "reopen last cur/old %d/%d",
1489 val, zh->reg->last_val);
1496 zebra_lock_r (zh->lock_shadow);
1498 zebra_lock_r (zh->lock_normal);
1502 resultSetInvalidate (zh);
1503 zebra_register_close (zh->service, zh->reg);
1505 zh->reg = zebra_register_open (zh->service, zh->reg_name,
1506 0, val == 'c' ? 1 : 0,
1507 zh->res, zh->path_reg);
1510 zebra_unlock (zh->lock_normal);
1511 zebra_unlock (zh->lock_shadow);
1516 zh->reg->last_val = val;
1517 zh->reg->seqno = seqno;
1519 read_res_for_transaction(zh);
1523 int zebra_end_trans (ZebraHandle zh)
1525 ZebraTransactionStatus dummy;
1526 yaz_log(LOG_API,"zebra_end_trans");
1527 return zebra_end_transaction(zh, &dummy);
1530 int zebra_end_transaction (ZebraHandle zh, ZebraTransactionStatus *status)
1537 yaz_log(LOG_API,"zebra_end_transaction");
1539 status->processed = 0;
1540 status->inserted = 0;
1541 status->updated = 0;
1542 status->deleted = 0;
1546 if (!zh->res || !zh->reg)
1549 zh->errString = "zebra_end_trans: no open transaction";
1552 if (zh->trans_no != zh->trans_w_no)
1555 if (zh->trans_no != 0)
1558 /* release read lock */
1560 zebra_unlock (zh->lock_normal);
1561 zebra_unlock (zh->lock_shadow);
1564 { /* release write lock */
1568 yaz_log (LOG_LOG, "zebra_end_trans");
1569 rval = res_get (zh->res, "shadow");
1571 zebraExplain_runNumberIncrement (zh->reg->zei, 1);
1573 zebra_flush_reg (zh);
1575 resultSetInvalidate (zh);
1577 zebra_register_close (zh->service, zh->reg);
1580 yaz_log (LOG_LOG, "Records: "ZINT_FORMAT" i/u/d "
1581 ZINT_FORMAT"/"ZINT_FORMAT"/"ZINT_FORMAT,
1582 zh->records_processed, zh->records_inserted,
1583 zh->records_updated, zh->records_deleted);
1585 status->processed = zh->records_processed;
1586 status->inserted = zh->records_inserted;
1587 status->updated = zh->records_updated;
1588 status->deleted = zh->records_deleted;
1590 zebra_get_state (zh, &val, &seqno);
1593 BFiles bfs = bfs_create (rval, zh->path_reg);
1594 yaz_log (LOG_LOG, "deleting shadow stuff val=%c", val);
1595 bf_commitClean (bfs, rval);
1600 zebra_set_state (zh, 'o', seqno);
1602 zebra_unlock (zh->lock_shadow);
1603 zebra_unlock (zh->lock_normal);
1606 #if HAVE_SYS_TIMES_H
1608 logf (LOG_LOG, "user/system: %ld/%ld",
1609 (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1610 (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1612 status->utime = (long) (zh->tms2.tms_utime - zh->tms1.tms_utime);
1613 status->stime = (long) (zh->tms2.tms_stime - zh->tms1.tms_stime);
1618 int zebra_repository_update (ZebraHandle zh, const char *path)
1622 logf (LOG_LOG|LOG_API, "updating %s", path);
1623 repositoryUpdate (zh, path);
1627 int zebra_repository_delete (ZebraHandle zh, const char *path)
1631 logf (LOG_LOG|LOG_API, "deleting %s", path);
1632 repositoryDelete (zh, path);
1636 int zebra_repository_show (ZebraHandle zh, const char *path)
1639 yaz_log(LOG_API,"zebra_repository_show");
1641 repositoryShow (zh, path);
1645 static int zebra_commit_ex (ZebraHandle zh, int clean_only)
1659 rval = res_get (zh->res, "shadow");
1662 logf (LOG_WARN, "Cannot perform commit");
1663 logf (LOG_WARN, "No shadow area defined");
1667 zebra_lock_w (zh->lock_normal);
1668 zebra_lock_r (zh->lock_shadow);
1670 bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1672 zebra_get_state (zh, &val, &seqno);
1675 bf_cache (bfs, rval);
1676 if (bf_commitExists (bfs))
1679 zebra_set_state (zh, 'd', seqno);
1682 zebra_set_state (zh, 'c', seqno);
1684 logf (LOG_LOG, "commit start");
1685 bf_commitExec (bfs);
1690 logf (LOG_LOG, "commit clean");
1691 bf_commitClean (bfs, rval);
1693 zebra_set_state (zh, 'o', seqno);
1697 logf (LOG_LOG, "nothing to commit");
1701 zebra_unlock (zh->lock_shadow);
1702 zebra_unlock (zh->lock_normal);
1706 int zebra_clean (ZebraHandle zh)
1708 yaz_log(LOG_API,"zebra_clean");
1709 return zebra_commit_ex(zh, 1);
1712 int zebra_commit (ZebraHandle zh)
1714 yaz_log(LOG_API,"zebra_commit");
1715 return zebra_commit_ex(zh, 0);
1718 int zebra_init (ZebraHandle zh)
1723 yaz_log(LOG_API,"zebra_init");
1731 rval = res_get (zh->res, "shadow");
1733 bfs = bfs_create (res_get (zh->service->global_res, "register"),
1736 bf_cache (bfs, rval);
1740 zebra_set_state (zh, 'o', 0);
1744 int zebra_compact (ZebraHandle zh)
1748 yaz_log(LOG_API,"zebra_compact");
1755 bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1761 int zebra_result (ZebraHandle zh, int *code, char **addinfo)
1764 yaz_log(LOG_API,"zebra_result");
1765 *code = zh->errCode;
1766 *addinfo = zh->errString;
1770 int zebra_shadow_enable (ZebraHandle zh, int value)
1773 yaz_log(LOG_API,"zebra_shadow_enable");
1775 zh->shadow_enable = value;
1779 int zebra_record_encoding (ZebraHandle zh, const char *encoding)
1782 yaz_log(LOG_API,"zebra_record_encoding");
1784 xfree (zh->record_encoding);
1788 * Something about charset aliases. Oleg???
1791 if (zh->iconv_to_utf8 != 0)
1792 yaz_iconv_close(zh->iconv_to_utf8);
1793 if (zh->iconv_from_utf8 != 0)
1794 yaz_iconv_close(zh->iconv_from_utf8);
1796 zh->record_encoding = xstrdup (encoding);
1798 logf(LOG_DEBUG, "Reset record encoding: %s", encoding);
1801 yaz_iconv_open ("UTF-8", encoding);
1802 if (zh->iconv_to_utf8 == 0)
1803 yaz_log (LOG_WARN, "iconv: %s to UTF-8 unsupported", encoding);
1804 zh->iconv_from_utf8 =
1805 yaz_iconv_open (encoding, "UTF-8");
1806 if (zh->iconv_to_utf8 == 0)
1807 yaz_log (LOG_WARN, "iconv: UTF-8 to %s unsupported", encoding);
1812 int zebra_set_resource(ZebraHandle zh, const char *name, const char *value)
1815 yaz_log(LOG_API,"zebra_set_resource %s:%s",name,value);
1817 res_set(zh->res, name, value);
1821 const char *zebra_get_resource(ZebraHandle zh,
1822 const char *name, const char *defaultvalue)
1826 v= res_get_def( zh->res, name, (char *)defaultvalue);
1828 yaz_log(LOG_API,"zebra_get_resource %s:%s",name,v);
1832 /* moved from zebra_api_ext.c by pop */
1833 /* FIXME: Should this really be public??? -Heikki */
1835 int zebra_trans_no (ZebraHandle zh)
1838 yaz_log(LOG_API,"zebra_trans_no");
1839 return zh->trans_no;
1842 int zebra_get_shadow_enable (ZebraHandle zh)
1844 yaz_log(LOG_API,"zebra_get_shadow_enable");
1845 return (zh->shadow_enable);
1848 int zebra_set_shadow_enable (ZebraHandle zh, int value)
1850 yaz_log(LOG_API,"zebra_set_shadow_enable %d",value);
1851 zh->shadow_enable = value;
1855 /* almost the same as zebra_records_retrieve ... but how did it work?
1856 I mean for multiple records ??? CHECK ??? */
1857 void api_records_retrieve (ZebraHandle zh, ODR stream,
1858 const char *setname, Z_RecordComposition *comp,
1859 oid_value input_format, int num_recs,
1860 ZebraRetrievalRecord *recs)
1864 yaz_log(LOG_API,"api_records_retrieve s=%s n=%d",setname,num_recs);
1869 zh->errString = odr_strdup (stream, setname);
1875 if (zebra_begin_read (zh))
1878 pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
1879 for (i = 0; i<num_recs; i++)
1880 pos_array[i] = recs[i].position;
1881 poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
1884 logf (LOG_DEBUG, "zebraPosSetCreate error");
1886 zh->errString = nmem_strdup (stream->mem, setname);
1890 for (i = 0; i<num_recs; i++)
1894 recs[i].errCode = 0;
1895 recs[i].format = VAL_SUTRS;
1896 recs[i].len = strlen(poset[i].term);
1897 recs[i].buf = poset[i].term;
1898 recs[i].base = poset[i].db;
1902 else if (poset[i].sysno)
1904 /* changed here ??? CHECK ??? */
1907 zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
1908 stream, input_format, comp,
1913 recs[i].buf = (char *) odr_malloc(stream,recs[i].len);
1914 memcpy(recs[i].buf, b, recs[i].len);
1915 recs[i].errString = 0; /* Hmmm !!! we should get this */
1916 recs[i].sysno = poset[i].sysno;
1917 recs[i].score = poset[i].score;
1923 sprintf (num_str, "%d", pos_array[i]);
1925 zh->errString = odr_strdup (stream, num_str);
1930 zebraPosSetDestroy (zh, poset, num_recs);
1932 zebra_end_read (zh);
1937 /* ---------------------------------------------------------------------------
1938 Record insert(=update), delete
1940 If sysno is provided, then it's used to identify the record.
1941 If not, and match_criteria is provided, then sysno is guessed
1942 If not, and a record is provided, then sysno is got from there
1943 NOTE: Now returns 0 at success and updates sysno, which is an int*
1947 int zebra_add_record(ZebraHandle zh,
1948 const char *buf, int buf_size)
1951 return zebra_update_record(zh, 0, &sysno, 0, 0, buf, buf_size, 0);
1954 int zebra_insert_record (ZebraHandle zh,
1955 const char *recordType,
1956 SYSNO *sysno, const char *match, const char *fname,
1957 const char *buf, int buf_size, int force_update)
1960 yaz_log(LOG_API,"zebra_insert_record sysno=" ZINT_FORMAT, *sysno);
1962 if (buf_size < 1) buf_size = strlen(buf);
1964 if (zebra_begin_trans(zh, 1))
1966 res = buffer_extract_record (zh, buf, buf_size,
1967 0, /* delete_flag */
1973 0); /* allow_update */
1974 zebra_end_trans(zh);
1978 int zebra_update_record (ZebraHandle zh,
1979 const char *recordType,
1980 SYSNO* sysno, const char *match, const char *fname,
1981 const char *buf, int buf_size,
1986 yaz_log(LOG_API,"zebra_update_record sysno=" ZINT_FORMAT, *sysno);
1988 if (buf_size < 1) buf_size = strlen(buf);
1990 if (zebra_begin_trans(zh, 1))
1992 res = buffer_extract_record (zh, buf, buf_size,
1993 0, /* delete_flag */
1999 1); /* allow_update */
2000 zebra_end_trans(zh);
2004 int zebra_delete_record (ZebraHandle zh,
2005 const char *recordType,
2006 SYSNO *sysno, const char *match, const char *fname,
2007 const char *buf, int buf_size,
2011 yaz_log(LOG_API,"zebra_delete_record sysno=" ZINT_FORMAT, *sysno);
2013 if (buf_size < 1) buf_size = strlen(buf);
2015 if (zebra_begin_trans(zh, 1))
2017 res = buffer_extract_record (zh, buf, buf_size,
2018 1, /* delete_flag */
2024 1); /* allow_update */
2025 zebra_end_trans(zh);
2029 /* ---------------------------------------------------------------------------
2033 int zebra_search_PQF (ZebraHandle zh, const char *pqf_query,
2034 const char *setname, int *numhits)
2039 ODR odr = odr_createmem(ODR_ENCODE);
2041 yaz_log(LOG_API,"zebra_search_PQF s=%s q=%s",setname, pqf_query);
2043 query = p_query_rpn (odr, PROTO_Z3950, pqf_query);
2046 yaz_log (LOG_WARN, "bad query %s\n", pqf_query);
2048 res=zebra_search_RPN (zh, odr, query, setname, &hits);
2052 yaz_log(LOG_API,"Hits: %d",hits);
2060 /* ---------------------------------------------------------------------------
2061 Sort - a simplified interface, with optional read locks.
2062 FIXME - This is a horrible name, will conflict with half the applications
2064 int zebra_sort_by_specstr (ZebraHandle zh,
2066 const char *sort_spec,
2067 const char *output_setname,
2068 const char **input_setnames)
2070 int num_input_setnames = 0;
2071 int sort_status = 0;
2072 Z_SortKeySpecList *sort_sequence = yaz_sort_spec (stream, sort_spec);
2073 yaz_log(LOG_API,"sort (FIXME) ");
2076 logf(LOG_WARN,"invalid sort specs '%s'", sort_spec);
2081 /* we can do this, since the perl typemap code for char** will
2082 put a NULL at the end of list */
2083 while (input_setnames[num_input_setnames]) num_input_setnames++;
2085 if (zebra_begin_read (zh))
2088 resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
2089 output_setname, sort_sequence, &sort_status);