1 /* $Id: zebraapi.c,v 1.120.2.11 2006-03-24 13:47:29 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>
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;
95 zh = (ZebraHandle) xmalloc (sizeof(*zh));
96 yaz_log (LOG_DEBUG, "zebra_open zs=%p returns %p", zs, zh);
99 zh->reg = 0; /* no register attached yet */
107 zh->reg_name = xstrdup ("");
109 zh->num_basenames = 0;
118 zh->shadow_enable = 1;
120 default_encoding = res_get_def(zs->global_res, "encoding", "ISO-8859-1");
121 zh->record_encoding = xstrdup (default_encoding);
124 yaz_iconv_open ("UTF-8", default_encoding);
125 if (zh->iconv_to_utf8 == 0)
126 yaz_log (LOG_WARN, "iconv: %s to UTF-8 unsupported",
128 zh->iconv_from_utf8 =
129 yaz_iconv_open (default_encoding, "UTF-8");
130 if (zh->iconv_to_utf8 == 0)
131 yaz_log (LOG_WARN, "iconv: UTF-8 to %s unsupported",
134 zebra_mutex_cond_lock (&zs->session_lock);
136 zh->next = zs->sessions;
139 zebra_mutex_cond_unlock (&zs->session_lock);
144 ZebraService zebra_start (const char *configName)
146 return zebra_start_res(configName, 0, 0);
149 ZebraService zebra_start_res (const char *configName, Res def_res, Res over_res)
153 yaz_log(LOG_LOG,"zebra_start %s %s", configName, ZEBRAVER);
155 if ((res = res_open (configName, def_res, over_res)))
157 const char *passwd_plain = 0;
158 const char *passwd_encrypt = 0;
159 ZebraService zh = xmalloc (sizeof(*zh));
161 yaz_log (LOG_DEBUG, "Read resources `%s'", configName);
163 zh->global_res = res;
164 zh->configName = xstrdup(configName);
169 zebra_mutex_cond_init (&zh->session_lock);
170 passwd_plain = res_get (zh->global_res, "passwd");
171 passwd_encrypt = res_get (zh->global_res, "passwd.c");
173 if (!passwd_plain && !passwd_encrypt)
174 zh->passwd_db = NULL;
177 zh->passwd_db = passwd_db_open();
179 logf (LOG_WARN|LOG_ERRNO, "passwd_db_open failed");
183 if (passwd_db_file_plain(zh->passwd_db, passwd_plain))
186 "Failed to read passwords %s (or unsupported)",
191 if (passwd_db_file_crypt(zh->passwd_db, passwd_encrypt))
194 "Failed to read encrypted pwds %s "
195 "(or unsupported)", passwd_encrypt);
201 zh->path_root = res_get (zh->global_res, "root");
208 void zebra_pidfname(ZebraService zs, char *path)
210 zebra_lock_prefix (zs->global_res, path);
211 strcat(path, "zebrasrv.pid");
215 struct zebra_register *zebra_register_open (ZebraService zs, const char *name,
216 int rw, int useshadow, Res res,
217 const char *reg_path)
219 struct zebra_register *reg;
220 int record_compression = REC_COMPRESS_NONE;
221 const char *recordCompression = 0;
222 const char *profilePath;
227 reg = xmalloc (sizeof(*reg));
230 reg->name = xstrdup (name);
237 yaz_log (LOG_LOG|LOG_API, "zebra_register_open rw = %d useshadow=%d p=%p,n=%s,rp=%s",
238 rw, useshadow, reg, name, reg_path ? reg_path : "(none)");
240 reg->dh = data1_createx (DATA1_FLAG_XML);
243 reg->bfs = bfs_create (res_get (res, "register"), reg_path);
246 data1_destroy(reg->dh);
250 bf_cache (reg->bfs, res_get (res, "shadow"));
252 getcwd(cwd, sizeof(cwd)-1);
253 profilePath = res_get_def(res, "profilePath", DEFAULT_PROFILE_PATH);
254 yaz_log(LOG_LOG, "profilePath=%s cwd=%s", profilePath, cwd);
256 data1_set_tabpath (reg->dh, profilePath);
257 data1_set_tabroot (reg->dh, reg_path);
258 reg->recTypes = recTypes_init (reg->dh);
259 recTypes_default_handlers (reg->recTypes);
261 reg->zebra_maps = zebra_maps_open (res, reg_path);
262 reg->rank_classes = NULL;
266 reg->keys.buf_max = 0;
268 reg->sortKeys.buf = 0;
269 reg->sortKeys.buf_max = 0;
282 reg->key_file_no = 0;
285 zebraRankInstall (reg, rank1_class);
286 zebraRankInstall (reg, rankzv_class);
287 zebraRankInstall (reg, rankliv_class);
289 recordCompression = res_get_def (res, "recordCompression", "none");
290 if (!strcmp (recordCompression, "none"))
291 record_compression = REC_COMPRESS_NONE;
292 if (!strcmp (recordCompression, "bzip2"))
293 record_compression = REC_COMPRESS_BZIP2;
295 if (!(reg->records = rec_open (reg->bfs, rw, record_compression)))
297 logf (LOG_WARN, "rec_open");
302 reg->matchDict = dict_open (reg->bfs, GMATCH_DICT, 20, 1, 0);
304 if (!(reg->dict = dict_open (reg->bfs, FNAME_DICT, 40, rw, 0)))
306 logf (LOG_WARN, "dict_open");
309 if (!(reg->sortIdx = sortIdx_open (reg->bfs, rw)))
311 logf (LOG_WARN, "sortIdx_open");
314 if (res_get_match (res, "isam", "s", ISAM_DEFAULT))
316 struct ISAMS_M_s isams_m;
317 if (!(reg->isams = isams_open (reg->bfs, FNAME_ISAMS, rw,
318 key_isams_m(res, &isams_m))))
320 logf (LOG_WARN, "isams_open");
324 if (res_get_match (res, "isam", "i", ISAM_DEFAULT))
326 if (!(reg->isam = is_open (reg->bfs, FNAME_ISAM, key_compare, rw,
327 sizeof (struct it_key), res)))
329 logf (LOG_WARN, "is_open");
333 if (res_get_match (res, "isam", "c", ISAM_DEFAULT))
335 struct ISAMC_M_s isamc_m;
336 if (!(reg->isamc = isc_open (reg->bfs, FNAME_ISAMC,
337 rw, key_isamc_m(res, &isamc_m))))
339 logf (LOG_WARN, "isc_open");
343 if (res_get_match (res, "isam", "d", ISAM_DEFAULT))
345 struct ISAMD_M_s isamd_m;
347 if (!(reg->isamd = isamd_open (reg->bfs, FNAME_ISAMD,
348 rw, key_isamd_m(res, &isamd_m))))
350 logf (LOG_WARN, "isamd_open");
354 if (res_get_match (res, "isam", "b", ISAM_DEFAULT))
356 struct ISAMC_M_s isamc_m;
358 if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
359 rw, key_isamc_m(res, &isamc_m), 0)))
361 logf (LOG_WARN, "isamb_open");
365 if (res_get_match (res, "isam", "bc", ISAM_DEFAULT))
367 struct ISAMC_M_s isamc_m;
369 if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
370 rw, key_isamc_m(res, &isamc_m), 1)))
372 logf (LOG_WARN, "isamb_open");
376 if (res_get_match (res, "isam", "null", ISAM_DEFAULT))
378 struct ISAMC_M_s isamc_m;
380 if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
381 rw, key_isamc_m(res, &isamc_m), -1)))
383 logf (LOG_WARN, "isamb_open");
387 reg->zei = zebraExplain_open (reg->records, reg->dh,
392 logf (LOG_WARN, "Cannot obtain EXPLAIN information");
396 yaz_log (LOG_DEBUG, "zebra_register_open ok p=%p", reg);
400 int zebra_admin_shutdown (ZebraHandle zh)
403 yaz_log(LOG_API,"zebra_admin_shutdown");
406 zebra_mutex_cond_lock (&zh->service->session_lock);
407 zh->service->stop_flag = 1;
408 zebra_mutex_cond_unlock (&zh->service->session_lock);
412 int zebra_admin_start (ZebraHandle zh)
416 yaz_log(LOG_API,"zebra_admin_start");
419 zebra_mutex_cond_lock (&zs->session_lock);
420 zebra_mutex_cond_unlock (&zs->session_lock);
424 static void zebra_register_close (ZebraService zs, struct zebra_register *reg)
427 yaz_log(LOG_LOG|LOG_API, "zebra_register_close p=%p", reg);
432 zebraExplain_close (reg->zei);
433 dict_close (reg->dict);
435 dict_close (reg->matchDict);
436 sortIdx_close (reg->sortIdx);
438 isams_close (reg->isams);
440 is_close (reg->isam);
442 isc_close (reg->isamc);
444 isamd_close (reg->isamd);
446 isamb_close (reg->isamb);
447 rec_close (®->records);
450 recTypes_destroy (reg->recTypes);
451 zebra_maps_close (reg->zebra_maps);
452 zebraRankDestroy (reg);
453 bfs_destroy (reg->bfs);
454 data1_destroy (reg->dh);
456 xfree (reg->sortKeys.buf);
457 xfree (reg->keys.buf);
459 xfree (reg->key_buf);
464 int zebra_stop(ZebraService zs)
468 yaz_log (LOG_LOG|LOG_API, "zebra_stop");
472 zebra_close (zs->sessions);
475 zebra_mutex_cond_destroy (&zs->session_lock);
478 passwd_db_close (zs->passwd_db);
480 res_close (zs->global_res);
481 xfree (zs->configName);
486 int zebra_close (ZebraHandle zh)
489 struct zebra_session **sp;
492 yaz_log(LOG_API,"zebra_close");
499 yaz_log (LOG_DEBUG, "zebra_close zh=%p", zh);
500 resultSetDestroy (zh, -1, 0, 0);
503 zebra_register_close (zh->service, zh->reg);
504 zebra_close_res (zh);
506 xfree (zh->record_encoding);
508 for (i = 0; i < zh->num_basenames; i++)
509 xfree (zh->basenames[i]);
510 xfree (zh->basenames);
512 if (zh->iconv_to_utf8 != 0)
513 yaz_iconv_close (zh->iconv_to_utf8);
514 if (zh->iconv_from_utf8 != 0)
515 yaz_iconv_close (zh->iconv_from_utf8);
517 zebra_mutex_cond_lock (&zs->session_lock);
518 zebra_lock_destroy (zh->lock_normal);
519 zebra_lock_destroy (zh->lock_shadow);
531 zebra_mutex_cond_unlock (&zs->session_lock);
532 xfree (zh->reg_name);
533 xfree (zh->user_perm);
534 zh->service=0; /* more likely to trigger an assert */
535 xfree (zh->path_reg);
540 struct map_baseinfo {
546 char **new_basenames;
550 static Res zebra_open_res (ZebraHandle zh)
559 sprintf (fname, "%.200s/zebra.cfg", zh->path_reg);
560 res = res_open (fname, zh->service->global_res, 0);
562 res = zh->service->global_res;
564 else if (*zh->reg_name == 0)
566 res = zh->service->global_res;
570 yaz_log (LOG_WARN, "no register root specified");
571 return 0; /* no path for register - fail! */
576 static void zebra_close_res (ZebraHandle zh)
580 if (zh->res != zh->service->global_res)
585 static int zebra_select_register (ZebraHandle zh, const char *new_reg)
589 if (zh->res && strcmp (zh->reg_name, new_reg) == 0)
593 assert (zh->reg == 0);
594 assert (*zh->reg_name == 0);
600 resultSetInvalidate (zh);
601 zebra_register_close (zh->service, zh->reg);
606 xfree (zh->reg_name);
607 zh->reg_name = xstrdup (new_reg);
609 xfree (zh->path_reg);
611 if (zh->service->path_root)
613 zh->path_reg = xmalloc (strlen(zh->service->path_root) +
614 strlen(zh->reg_name) + 3);
615 strcpy (zh->path_reg, zh->service->path_root);
618 strcat (zh->path_reg, "/");
619 strcat (zh->path_reg, zh->reg_name);
622 zh->res = zebra_open_res (zh);
625 zebra_lock_destroy (zh->lock_normal);
629 zebra_lock_destroy (zh->lock_shadow);
635 const char *lock_area =res_get (zh->res, "lockDir");
637 if (!lock_area && zh->path_reg)
638 res_set (zh->res, "lockDir", zh->path_reg);
639 sprintf (fname, "norm.%s.LCK", zh->reg_name);
641 zebra_lock_create (res_get(zh->res, "lockDir"), fname);
643 sprintf (fname, "shadow.%s.LCK", zh->reg_name);
645 zebra_lock_create (res_get(zh->res, "lockDir"), fname);
647 if (!zh->lock_normal || !zh->lock_shadow)
651 zebra_lock_destroy(zh->lock_normal);
656 zebra_lock_destroy(zh->lock_shadow);
667 void map_basenames_func (void *vp, const char *name, const char *value)
669 struct map_baseinfo *p = (struct map_baseinfo *) vp;
671 char fromdb[128], todb[8][128];
674 sscanf (value, "%127s %127s %127s %127s %127s %127s %127s %127s %127s",
675 fromdb, todb[0], todb[1], todb[2], todb[3], todb[4],
676 todb[5], todb[6], todb[7]);
680 for (i = 0; i<p->num_bases; i++)
681 if (p->basenames[i] && !STRCASECMP (p->basenames[i], fromdb))
684 for (i = 0; i < no; i++)
686 if (p->new_num_bases == p->new_num_max)
688 p->new_basenames[(p->new_num_bases)++] =
689 nmem_strdup (p->mem, todb[i]);
695 void map_basenames (ZebraHandle zh, ODR stream,
696 int *num_bases, char ***basenames)
698 struct map_baseinfo info;
699 struct map_baseinfo *p = &info;
702 yaz_log(LOG_API,"map_basenames ");
706 info.num_bases = *num_bases;
707 info.basenames = *basenames;
708 info.new_num_max = 128;
709 info.new_num_bases = 0;
710 info.new_basenames = (char **)
711 odr_malloc (stream, sizeof(*info.new_basenames) * info.new_num_max);
712 info.mem = stream->mem;
714 res_trav (zh->service->global_res, "mapdb", &info, map_basenames_func);
716 for (i = 0; i<p->num_bases; i++)
717 if (p->basenames[i] && p->new_num_bases < p->new_num_max)
719 p->new_basenames[(p->new_num_bases)++] =
720 nmem_strdup (p->mem, p->basenames[i]);
722 *num_bases = info.new_num_bases;
723 *basenames = info.new_basenames;
724 for (i = 0; i<*num_bases; i++)
725 logf (LOG_LOG, "base %s", (*basenames)[i]);
728 int zebra_select_default_database(ZebraHandle zh)
732 /* no database has been selected - so we select based on
733 resource setting (including group)
735 const char *group = res_get(zh->service->global_res, "group");
736 const char *v = res_get_prefix(zh->service->global_res,
737 "database", group, "Default");
738 return zebra_select_database(zh, v);
743 int zebra_select_database (ZebraHandle zh, const char *basename)
746 yaz_log(LOG_API,"zebra_select_database %s",basename);
747 return zebra_select_databases (zh, 1, &basename);
750 int zebra_select_databases (ZebraHandle zh, int num_bases,
751 const char **basenames)
758 yaz_log(LOG_API,"zebra_select_databases n=%d [0]=%s",
759 num_bases,basenames[0]);
760 zebra_clearError(zh);
767 for (i = 0; i < zh->num_basenames; i++)
768 xfree (zh->basenames[i]);
769 xfree (zh->basenames);
771 zh->num_basenames = num_bases;
772 zh->basenames = xmalloc (zh->num_basenames * sizeof(*zh->basenames));
773 for (i = 0; i < zh->num_basenames; i++)
774 zh->basenames[i] = xstrdup (basenames[i]);
776 cp = strrchr(basenames[0], '/');
779 len = cp - basenames[0];
780 new_reg = xmalloc (len + 1);
781 memcpy (new_reg, basenames[0], len);
785 new_reg = xstrdup ("");
786 for (i = 1; i<num_bases; i++)
790 cp1 = strrchr (basenames[i], '/');
798 if (len != cp1 - basenames[i] ||
799 memcmp (basenames[i], new_reg, len))
814 zebra_select_register (zh, new_reg);
821 if (!zh->lock_normal || !zh->lock_shadow)
829 int zebra_search_RPN (ZebraHandle zh, ODR o,
830 Z_RPNQuery *query, const char *setname, int *hits)
833 yaz_log(LOG_API,"zebra_search_rpn");
835 zebra_clearError(zh);
839 if (zebra_begin_read (zh))
842 zebra_livcode_transform(zh, query);
844 resultSetAddRPN (zh, odr_extract_mem(o), query,
845 zh->num_basenames, zh->basenames, setname);
853 int zebra_records_retrieve (ZebraHandle zh, ODR stream,
854 const char *setname, Z_RecordComposition *comp,
855 oid_value input_format, int num_recs,
856 ZebraRetrievalRecord *recs)
859 int i, *pos_array, ret = 0;
861 yaz_log(LOG_API,"zebra_records_retrieve n=%d",num_recs);
863 zebra_clearError(zh);
868 zh->errString = odr_strdup (stream, setname);
872 if (zebra_begin_read (zh))
875 pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
876 for (i = 0; i<num_recs; i++)
877 pos_array[i] = recs[i].position;
878 poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
881 logf (LOG_DEBUG, "zebraPosSetCreate error");
883 zh->errString = nmem_strdup (stream->mem, setname);
888 for (i = 0; i<num_recs; i++)
893 recs[i].format = VAL_SUTRS;
894 recs[i].len = strlen(poset[i].term);
895 recs[i].buf = poset[i].term;
896 recs[i].base = poset[i].db;
898 else if (poset[i].sysno)
901 zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
902 stream, input_format, comp,
903 &recs[i].format, &recs[i].buf,
906 recs[i].errString = NULL;
912 sprintf (num_str, "%d", pos_array[i]);
914 zh->errString = odr_strdup (stream, num_str);
919 zebraPosSetDestroy (zh, poset, num_recs);
926 int zebra_scan (ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
927 oid_value attributeset,
928 int *position, int *num_entries, ZebraScanEntry **entries,
932 yaz_log(LOG_API,"zebra_scan");
934 if (zebra_begin_read (zh))
940 rpn_scan (zh, stream, zapt, attributeset,
941 zh->num_basenames, zh->basenames, position,
942 num_entries, entries, is_partial, 0, 0);
947 int zebra_sort (ZebraHandle zh, ODR stream,
948 int num_input_setnames, const char **input_setnames,
949 const char *output_setname, Z_SortKeySpecList *sort_sequence,
953 yaz_log(LOG_API,"zebra_sort");
955 if (zebra_begin_read (zh))
957 resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
958 output_setname, sort_sequence, sort_status);
963 int zebra_deleleResultSet(ZebraHandle zh, int function,
964 int num_setnames, char **setnames,
969 yaz_log(LOG_API,"zebra_deleleResultSet n=%d",num_setnames);
971 if (zebra_begin_read(zh))
972 return Z_DeleteStatus_systemProblemAtTarget;
975 case Z_DeleteResultSetRequest_list:
976 resultSetDestroy (zh, num_setnames, setnames, statuses);
978 case Z_DeleteResultSetRequest_all:
979 resultSetDestroy (zh, -1, 0, statuses);
983 status = Z_DeleteStatus_success;
984 for (i = 0; i<num_setnames; i++)
985 if (statuses[i] == Z_DeleteStatus_resultSetDidNotExist)
986 status = statuses[i];
990 int zebra_errCode (ZebraHandle zh)
994 yaz_log(LOG_API,"zebra_errCode: %d",zh->errCode);
997 yaz_log(LOG_API,"zebra_errCode: o");
1001 const char *zebra_errString (ZebraHandle zh)
1005 e= diagbib1_str (zh->errCode);
1006 yaz_log(LOG_API,"zebra_errString: %s",e);
1010 char *zebra_errAdd (ZebraHandle zh)
1015 yaz_log(LOG_API,"zebra_errAdd: %s",a);
1019 void zebra_clearError(ZebraHandle zh)
1028 int zebra_auth (ZebraHandle zh, const char *user, const char *pass)
1038 sprintf(u, "perm.%.30s", user ? user : "anonymous");
1039 p = res_get(zs->global_res, u);
1040 xfree (zh->user_perm);
1041 zh->user_perm = xstrdup(p ? p : "r");
1043 yaz_log(LOG_LOG, "User perm for %s: %s", u, zh->user_perm);
1045 /* users that don't require a password .. */
1046 if (zh->user_perm && strchr(zh->user_perm, 'a'))
1049 if (!zs->passwd_db || !passwd_db_auth (zs->passwd_db, user, pass))
1054 int zebra_admin_import_begin (ZebraHandle zh, const char *database,
1055 const char *record_type)
1058 yaz_log(LOG_API,"zebra_admin_import_begin db=%s rt=%s",
1059 database, record_type);
1061 if (zebra_select_database(zh, database))
1063 if (zebra_begin_trans (zh, 1))
1068 int zebra_admin_import_end (ZebraHandle zh)
1071 yaz_log(LOG_API,"zebra_admin_import_end");
1073 zebra_end_trans (zh);
1077 int zebra_admin_import_segment (ZebraHandle zh, Z_Segment *segment)
1082 yaz_log(LOG_API,"zebra_admin_import_segment");
1084 for (i = 0; i<segment->num_segmentRecords; i++)
1086 Z_NamePlusRecord *npr = segment->segmentRecords[i];
1088 printf ("--------------%d--------------------\n", i);
1089 if (npr->which == Z_NamePlusRecord_intermediateFragment)
1091 Z_FragmentSyntax *fragment = npr->u.intermediateFragment;
1092 if (fragment->which == Z_FragmentSyntax_notExternallyTagged)
1094 Odr_oct *oct = fragment->u.notExternallyTagged;
1095 printf ("%.*s", (oct->len > 100 ? 100 : oct->len) ,
1100 zebra_update_record(zh,
1101 0, /* record Type */
1113 int zebra_admin_exchange_record (ZebraHandle zh,
1114 const char *rec_buf,
1116 const char *recid_buf, size_t recid_len,
1118 /* 1 = insert. Fail it already exists */
1119 /* 2 = replace. Fail it does not exist */
1120 /* 3 = delete. Fail if does not exist */
1121 /* 4 = update. Insert/replace */
1127 yaz_log(LOG_API,"zebra_admin_exchange_record ac=%d", action);
1130 if (!recid_buf || recid_len <= 0 || recid_len >= sizeof(recid_z))
1132 memcpy (recid_z, recid_buf, recid_len);
1133 recid_z[recid_len] = 0;
1135 if (zebra_begin_trans(zh, 1))
1138 rinfo = dict_lookup (zh->reg->matchDict, recid_z);
1141 if (action == 1) /* fail if insert */
1143 zebra_end_trans(zh);
1147 memcpy (&sysno, rinfo+1, sizeof(sysno));
1151 if (action == 2 || action == 3) /* fail if delete or update */
1153 zebra_end_trans(zh);
1156 action = 1; /* make it an insert (if it's an update).. */
1158 buffer_extract_record (zh, rec_buf, rec_len,
1159 action == 3 ? 1 : 0 /* delete flag */,
1165 0, /* force update */
1166 1 /* allow update */
1170 dict_insert (zh->reg->matchDict, recid_z, sizeof(sysno), &sysno);
1172 else if (action == 3)
1174 dict_delete (zh->reg->matchDict, recid_z);
1176 zebra_end_trans(zh);
1180 int delete_w_handle(const char *info, void *handle)
1182 ZebraHandle zh = (ZebraHandle) handle;
1185 if (*info == sizeof(pos))
1187 memcpy (&pos, info+1, sizeof(pos));
1188 isamb_unlink(zh->reg->isamb, pos);
1193 static int delete_SU_handle(void *handle, int ord)
1195 ZebraHandle zh = (ZebraHandle) handle;
1199 ord_len = key_SU_encode (ord, ord_buf);
1200 ord_buf[ord_len] = '\0';
1202 assert (zh->reg->isamb);
1203 dict_delete_subtree(zh->reg->dict, ord_buf,
1204 zh, delete_w_handle);
1208 int zebra_drop_database (ZebraHandle zh, const char *database)
1212 yaz_log(LOG_API,"zebra_drop_database");
1214 zebra_clearError(zh);
1216 if (zebra_select_database (zh, database))
1218 if (zebra_begin_trans (zh, 1))
1222 zebraExplain_curDatabase (zh->reg->zei, database);
1224 zebraExplain_trav_ord(zh->reg->zei, zh, delete_SU_handle);
1225 zebraExplain_removeDatabase(zh->reg->zei, zh);
1229 yaz_log(LOG_WARN, "drop database only supported for isam:b");
1232 zebra_end_trans (zh);
1236 int zebra_create_database (ZebraHandle zh, const char *database)
1239 yaz_log(LOG_API,"zebra_create_database");
1242 if (zebra_select_database (zh, database))
1244 if (zebra_begin_trans (zh, 1))
1247 /* announce database */
1248 if (zebraExplain_newDatabase (zh->reg->zei, database, 0
1249 /* explainDatabase */))
1251 zebra_end_trans (zh);
1253 zh->errString = "database already exist";
1256 zebra_end_trans (zh);
1260 int zebra_string_norm (ZebraHandle zh, unsigned reg_id,
1261 const char *input_str, int input_len,
1262 char *output_str, int output_len)
1266 yaz_log(LOG_API,"zebra_string_norm ");
1268 if (!zh->reg->zebra_maps)
1270 wrbuf = zebra_replace(zh->reg->zebra_maps, reg_id, "",
1271 input_str, input_len);
1274 if (wrbuf_len(wrbuf) >= output_len)
1276 if (wrbuf_len(wrbuf))
1277 memcpy (output_str, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
1278 output_str[wrbuf_len(wrbuf)] = '\0';
1279 return wrbuf_len(wrbuf);
1283 int zebra_set_state (ZebraHandle zh, int val, int seqno)
1285 char state_fname[256];
1290 yaz_log(LOG_API,"zebra_set_state v=%d seq=%d", val, seqno);
1293 sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1294 fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1295 f = fopen (fname, "w");
1297 yaz_log (LOG_DEBUG, "%c %d %ld", val, seqno, p);
1298 fprintf (f, "%c %d %ld\n", val, seqno, p);
1304 int zebra_get_state (ZebraHandle zh, char *val, int *seqno)
1306 char state_fname[256];
1311 yaz_log(LOG_API,"zebra_get_state ");
1313 sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1314 fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1315 f = fopen (fname, "r");
1321 fscanf (f, "%c %d", val, seqno);
1328 int zebra_begin_read (ZebraHandle zh)
1330 return zebra_begin_trans(zh, 0);
1333 int zebra_end_read (ZebraHandle zh)
1335 return zebra_end_trans(zh);
1338 static void read_res_for_transaction(ZebraHandle zh)
1340 const char *group = res_get(zh->res, "group");
1343 zh->m_group = group;
1344 v = res_get_prefix(zh->res, "followLinks", group, "1");
1345 zh->m_follow_links = atoi(v);
1347 zh->m_record_id = res_get_prefix(zh->res, "recordId", group, 0);
1348 zh->m_record_type = res_get_prefix(zh->res, "recordType", group, 0);
1350 v = res_get_prefix(zh->res, "storeKeys", group, "1");
1351 zh->m_store_keys = atoi(v);
1353 v = res_get_prefix(zh->res, "storeData", group, "1");
1354 zh->m_store_data = atoi(v);
1356 v = res_get_prefix(zh->res, "explainDatabase", group, "0");
1357 zh->m_explain_database = atoi(v);
1359 v = res_get_prefix(zh->res, "openRW", group, "1");
1360 zh->m_flag_rw = atoi(v);
1362 v = res_get_prefix(zh->res, "fileVerboseLimit", group, "100000");
1363 zh->m_file_verbose_limit = atoi(v);
1366 int zebra_begin_trans (ZebraHandle zh, int rw)
1368 zebra_select_default_database(zh);
1372 zh->errString = "zebra_begin_trans: no database selected";
1376 yaz_log(LOG_API,"zebra_begin_trans rw=%d",rw);
1380 if (rw && !strchr(zh->user_perm, 'w'))
1394 const char *rval = 0;
1399 read_res_for_transaction(zh);
1402 if (zh->trans_no != 1)
1405 zh->errString = "zebra_begin_trans: write trans not allowed within read trans";
1410 resultSetInvalidate (zh);
1411 zebra_register_close (zh->service, zh->reg);
1413 zh->trans_w_no = zh->trans_no;
1417 zh->records_inserted = 0;
1418 zh->records_updated = 0;
1419 zh->records_deleted = 0;
1420 zh->records_processed = 0;
1422 #if HAVE_SYS_TIMES_H
1426 if (zh->shadow_enable)
1427 rval = res_get (zh->res, "shadow");
1429 for (pass = 0; pass < 2; pass++)
1433 zebra_lock_r (zh->lock_normal);
1434 zebra_lock_w (zh->lock_shadow);
1438 zebra_lock_w (zh->lock_normal);
1439 zebra_lock_w (zh->lock_shadow);
1442 zebra_get_state (zh, &val, &seqno);
1445 yaz_log (LOG_LOG, "previous transaction didn't finish commit");
1446 zebra_unlock (zh->lock_shadow);
1447 zebra_unlock (zh->lock_normal);
1451 else if (val == 'd')
1455 BFiles bfs = bfs_create (res_get (zh->res, "shadow"),
1457 yaz_log (LOG_LOG, "previous transaction didn't reach commit");
1458 bf_commitClean (bfs, rval);
1463 yaz_log (LOG_WARN, "your previous transaction didn't finish");
1470 yaz_log (LOG_FATAL, "zebra_begin_trans couldn't finish commit");
1474 zebra_set_state (zh, 'd', seqno);
1476 zh->reg = zebra_register_open (zh->service, zh->reg_name,
1477 1, rval ? 1 : 0, zh->res,
1480 zh->reg->seqno = seqno;
1483 zebra_set_state (zh, 'o', seqno);
1485 zebra_unlock (zh->lock_shadow);
1486 zebra_unlock (zh->lock_normal);
1492 zh->errString = "zebra_begin_trans: cannot open register";
1493 yaz_log(LOG_FATAL, zh->errString);
1505 if (zh->trans_no != 1)
1507 zebra_flush_reg (zh);
1511 #if HAVE_SYS_TIMES_H
1520 if (!zh->lock_normal || !zh->lock_shadow)
1526 zebra_get_state (zh, &val, &seqno);
1532 else if (seqno != zh->reg->seqno)
1534 yaz_log (LOG_LOG, "reopen seqno cur/old %d/%d",
1535 seqno, zh->reg->seqno);
1538 else if (zh->reg->last_val != val)
1540 yaz_log (LOG_LOG, "reopen last cur/old %d/%d",
1541 val, zh->reg->last_val);
1548 zebra_lock_r (zh->lock_shadow);
1550 zebra_lock_r (zh->lock_normal);
1554 resultSetInvalidate (zh);
1555 zebra_register_close (zh->service, zh->reg);
1557 zh->reg = zebra_register_open (zh->service, zh->reg_name,
1558 0, val == 'c' ? 1 : 0,
1559 zh->res, zh->path_reg);
1562 zebra_unlock (zh->lock_normal);
1563 zebra_unlock (zh->lock_shadow);
1568 zh->reg->last_val = val;
1569 zh->reg->seqno = seqno;
1571 read_res_for_transaction(zh);
1575 int zebra_end_trans (ZebraHandle zh)
1577 ZebraTransactionStatus dummy;
1578 yaz_log(LOG_API,"zebra_end_trans");
1579 return zebra_end_transaction(zh, &dummy);
1582 int zebra_end_transaction (ZebraHandle zh, ZebraTransactionStatus *status)
1589 yaz_log(LOG_API,"zebra_end_transaction");
1591 status->processed = 0;
1592 status->inserted = 0;
1593 status->updated = 0;
1594 status->deleted = 0;
1598 if (!zh->res || !zh->reg)
1601 zh->errString = "zebra_end_trans: no open transaction";
1604 if (zh->trans_no != zh->trans_w_no)
1607 if (zh->trans_no != 0)
1610 /* release read lock */
1612 zebra_unlock (zh->lock_normal);
1613 zebra_unlock (zh->lock_shadow);
1616 { /* release write lock */
1620 yaz_log (LOG_LOG, "zebra_end_trans");
1621 rval = res_get (zh->res, "shadow");
1623 zebraExplain_runNumberIncrement (zh->reg->zei, 1);
1625 zebra_flush_reg (zh);
1627 resultSetInvalidate (zh);
1629 zebra_register_close (zh->service, zh->reg);
1632 yaz_log (LOG_LOG, "Records: %7d i/u/d %d/%d/%d",
1633 zh->records_processed, zh->records_inserted,
1634 zh->records_updated, zh->records_deleted);
1636 status->processed = zh->records_processed;
1637 status->inserted = zh->records_inserted;
1638 status->updated = zh->records_updated;
1639 status->deleted = zh->records_deleted;
1641 zebra_get_state (zh, &val, &seqno);
1644 BFiles bfs = bfs_create (rval, zh->path_reg);
1645 yaz_log (LOG_LOG, "deleting shadow stuff val=%c", val);
1646 bf_commitClean (bfs, rval);
1651 zebra_set_state (zh, 'o', seqno);
1653 zebra_unlock (zh->lock_shadow);
1654 zebra_unlock (zh->lock_normal);
1657 #if HAVE_SYS_TIMES_H
1659 logf (LOG_LOG, "user/system: %ld/%ld",
1660 (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1661 (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1663 status->utime = (long) (zh->tms2.tms_utime - zh->tms1.tms_utime);
1664 status->stime = (long) (zh->tms2.tms_stime - zh->tms1.tms_stime);
1669 int zebra_repository_update (ZebraHandle zh, const char *path)
1673 logf (LOG_LOG|LOG_API, "updating %s", path);
1674 repositoryUpdate (zh, path);
1678 int zebra_repository_delete (ZebraHandle zh, const char *path)
1682 logf (LOG_LOG|LOG_API, "deleting %s", path);
1683 repositoryDelete (zh, path);
1687 int zebra_repository_show (ZebraHandle zh, const char *path)
1690 yaz_log(LOG_API,"zebra_repository_show");
1692 repositoryShow (zh, path);
1696 static int zebra_commit_ex (ZebraHandle zh, int clean_only)
1705 zebra_select_default_database(zh);
1711 rval = res_get (zh->res, "shadow");
1714 logf (LOG_WARN, "Cannot perform commit");
1715 logf (LOG_WARN, "No shadow area defined");
1719 zebra_lock_w (zh->lock_normal);
1720 zebra_lock_r (zh->lock_shadow);
1722 bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1724 zebra_get_state (zh, &val, &seqno);
1727 bf_cache (bfs, rval);
1728 if (bf_commitExists (bfs))
1731 zebra_set_state (zh, 'd', seqno);
1734 zebra_set_state (zh, 'c', seqno);
1736 logf (LOG_LOG, "commit start");
1737 bf_commitExec (bfs);
1742 logf (LOG_LOG, "commit clean");
1743 bf_commitClean (bfs, rval);
1745 zebra_set_state (zh, 'o', seqno);
1749 logf (LOG_LOG, "nothing to commit");
1753 zebra_unlock (zh->lock_shadow);
1754 zebra_unlock (zh->lock_normal);
1758 int zebra_clean (ZebraHandle zh)
1760 yaz_log(LOG_API,"zebra_clean");
1761 return zebra_commit_ex(zh, 1);
1764 int zebra_commit (ZebraHandle zh)
1766 yaz_log(LOG_API,"zebra_commit");
1767 return zebra_commit_ex(zh, 0);
1770 int zebra_init (ZebraHandle zh)
1775 yaz_log(LOG_API,"zebra_init");
1778 zebra_select_default_database(zh);
1784 rval = res_get (zh->res, "shadow");
1786 bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1790 bf_cache (bfs, rval);
1794 zebra_set_state (zh, 'o', 0);
1798 int zebra_compact (ZebraHandle zh)
1802 yaz_log(LOG_API,"zebra_compact");
1809 bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1815 int zebra_result (ZebraHandle zh, int *code, char **addinfo)
1818 yaz_log(LOG_API,"zebra_result");
1819 *code = zh->errCode;
1820 *addinfo = zh->errString;
1824 int zebra_shadow_enable (ZebraHandle zh, int value)
1827 yaz_log(LOG_API,"zebra_shadow_enable");
1829 zh->shadow_enable = value;
1833 int zebra_record_encoding (ZebraHandle zh, const char *encoding)
1836 yaz_log(LOG_API,"zebra_record_encoding");
1838 xfree (zh->record_encoding);
1842 * Something about charset aliases. Oleg???
1845 if (zh->iconv_to_utf8 != 0)
1846 yaz_iconv_close(zh->iconv_to_utf8);
1847 if (zh->iconv_from_utf8 != 0)
1848 yaz_iconv_close(zh->iconv_from_utf8);
1850 zh->record_encoding = xstrdup (encoding);
1852 logf(LOG_DEBUG, "Reset record encoding: %s", encoding);
1855 yaz_iconv_open ("UTF-8", encoding);
1856 if (zh->iconv_to_utf8 == 0)
1857 yaz_log (LOG_WARN, "iconv: %s to UTF-8 unsupported", encoding);
1858 zh->iconv_from_utf8 =
1859 yaz_iconv_open (encoding, "UTF-8");
1860 if (zh->iconv_to_utf8 == 0)
1861 yaz_log (LOG_WARN, "iconv: UTF-8 to %s unsupported", encoding);
1866 int zebra_set_resource(ZebraHandle zh, const char *name, const char *value)
1869 yaz_log(LOG_API,"zebra_set_resource %s:%s",name,value);
1871 res_set(zh->res, name, value);
1875 const char *zebra_get_resource(ZebraHandle zh,
1876 const char *name, const char *defaultvalue)
1880 v= res_get_def( zh->res, name, (char *)defaultvalue);
1882 yaz_log(LOG_API,"zebra_get_resource %s:%s",name,v);
1886 /* moved from zebra_api_ext.c by pop */
1887 /* FIXME: Should this really be public??? -Heikki */
1889 int zebra_trans_no (ZebraHandle zh)
1892 yaz_log(LOG_API,"zebra_trans_no");
1893 return zh->trans_no;
1896 int zebra_get_shadow_enable (ZebraHandle zh)
1898 yaz_log(LOG_API,"zebra_get_shadow_enable");
1899 return (zh->shadow_enable);
1902 int zebra_set_shadow_enable (ZebraHandle zh, int value)
1904 yaz_log(LOG_API,"zebra_set_shadow_enable %d",value);
1905 zh->shadow_enable = value;
1909 /* almost the same as zebra_records_retrieve ... but how did it work?
1910 I mean for multiple records ??? CHECK ??? */
1911 void api_records_retrieve (ZebraHandle zh, ODR stream,
1912 const char *setname, Z_RecordComposition *comp,
1913 oid_value input_format, int num_recs,
1914 ZebraRetrievalRecord *recs)
1918 yaz_log(LOG_API,"api_records_retrieve s=%s n=%d",setname,num_recs);
1923 zh->errString = odr_strdup (stream, setname);
1929 if (zebra_begin_read (zh))
1932 pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
1933 for (i = 0; i<num_recs; i++)
1934 pos_array[i] = recs[i].position;
1935 poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
1938 logf (LOG_DEBUG, "zebraPosSetCreate error");
1940 zh->errString = nmem_strdup (stream->mem, setname);
1944 for (i = 0; i<num_recs; i++)
1948 recs[i].errCode = 0;
1949 recs[i].format = VAL_SUTRS;
1950 recs[i].len = strlen(poset[i].term);
1951 recs[i].buf = poset[i].term;
1952 recs[i].base = poset[i].db;
1956 else if (poset[i].sysno)
1958 /* changed here ??? CHECK ??? */
1961 zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
1962 stream, input_format, comp,
1967 recs[i].buf = (char *) odr_malloc(stream,recs[i].len);
1968 memcpy(recs[i].buf, b, recs[i].len);
1969 recs[i].errString = 0; /* Hmmm !!! we should get this */
1970 recs[i].sysno = poset[i].sysno;
1971 recs[i].score = poset[i].score;
1977 sprintf (num_str, "%d", pos_array[i]);
1979 zh->errString = odr_strdup (stream, num_str);
1984 zebraPosSetDestroy (zh, poset, num_recs);
1986 zebra_end_read (zh);
1991 /* ---------------------------------------------------------------------------
1992 Record insert(=update), delete
1994 If sysno is provided, then it's used to identify the record.
1995 If not, and match_criteria is provided, then sysno is guessed
1996 If not, and a record is provided, then sysno is got from there
1997 NOTE: Now returns 0 at success and updates sysno, which is an int*
2001 int zebra_add_record(ZebraHandle zh,
2002 const char *buf, int buf_size)
2005 return zebra_update_record(zh, 0, &sysno, 0, 0, buf, buf_size, 0);
2008 int zebra_insert_record (ZebraHandle zh,
2009 const char *recordType,
2010 int *sysno, const char *match, const char *fname,
2011 const char *buf, int buf_size, int force_update)
2014 yaz_log(LOG_API,"zebra_insert_record sysno=%d", *sysno);
2016 if (buf_size < 1) buf_size = strlen(buf);
2018 if (zebra_begin_trans(zh, 1))
2020 res = buffer_extract_record (zh, buf, buf_size,
2021 0, /* delete_flag */
2027 0); /* allow_update */
2028 zebra_end_trans(zh);
2032 int zebra_update_record (ZebraHandle zh,
2033 const char *recordType,
2034 int* sysno, const char *match, const char *fname,
2035 const char *buf, int buf_size,
2040 yaz_log(LOG_API,"zebra_update_record sysno=%d", *sysno);
2042 if (buf_size < 1) buf_size = strlen(buf);
2044 if (zebra_begin_trans(zh, 1))
2046 res = buffer_extract_record (zh, buf, buf_size,
2047 0, /* delete_flag */
2053 1); /* allow_update */
2054 yaz_log(LOG_LOG, "zebra_update_record returned res=%d", res);
2055 zebra_end_trans(zh);
2059 int zebra_delete_record (ZebraHandle zh,
2060 const char *recordType,
2061 int *sysno, const char *match, const char *fname,
2062 const char *buf, int buf_size,
2066 yaz_log(LOG_API,"zebra_delete_record sysno=%d", *sysno);
2068 if (buf_size < 1) buf_size = strlen(buf);
2070 if (zebra_begin_trans(zh, 1))
2072 res = buffer_extract_record (zh, buf, buf_size,
2073 1, /* delete_flag */
2079 1); /* allow_update */
2080 zebra_end_trans(zh);
2084 /* ---------------------------------------------------------------------------
2088 int zebra_search_PQF (ZebraHandle zh, const char *pqf_query,
2089 const char *setname, int *numhits)
2094 ODR odr = odr_createmem(ODR_ENCODE);
2096 yaz_log(LOG_API,"zebra_search_PQF s=%s q=%s",setname, pqf_query);
2098 query = p_query_rpn (odr, PROTO_Z3950, pqf_query);
2101 yaz_log (LOG_WARN, "bad query %s\n", pqf_query);
2103 res=zebra_search_RPN (zh, odr, query, setname, &hits);
2107 yaz_log(LOG_API,"Hits: %d",hits);
2115 /* ---------------------------------------------------------------------------
2116 Sort - a simplified interface, with optional read locks.
2117 FIXME - This is a horrible name, will conflict with half the applications
2119 int zebra_sort_by_specstr (ZebraHandle zh,
2121 const char *sort_spec,
2122 const char *output_setname,
2123 const char **input_setnames)
2125 int num_input_setnames = 0;
2126 int sort_status = 0;
2127 Z_SortKeySpecList *sort_sequence = yaz_sort_spec (stream, sort_spec);
2128 yaz_log(LOG_API,"sort (FIXME) ");
2131 logf(LOG_WARN,"invalid sort specs '%s'", sort_spec);
2136 /* we can do this, since the perl typemap code for char** will
2137 put a NULL at the end of list */
2138 while (input_setnames[num_input_setnames]) num_input_setnames++;
2140 if (zebra_begin_read (zh))
2143 resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
2144 output_setname, sort_sequence, &sort_status);
2150 void zebra_lock_prefix (Res res, char *path)
2152 const char *lock_dir = res_get_def (res, "lockDir", "");
2154 strcpy (path, lock_dir);
2155 if (*path && path[strlen(path)-1] != '/')