X-Git-Url: http://git.indexdata.com/?p=idzebra-moved-to-github.git;a=blobdiff_plain;f=index%2Fextract.c;h=37c0df1518d9d68190abe73b8d3bc88bc3b915a5;hp=d235a4400b92d1730b2cd650ad12d50e56abfc9e;hb=4097bac1dce126e79ce1550fad8b2034a311ff80;hpb=4415da5dbbba04e50d4524347486d60113ed569c diff --git a/index/extract.c b/index/extract.c index d235a44..be000c2 100644 --- a/index/extract.c +++ b/index/extract.c @@ -1,1149 +1,472 @@ -/* - * Copyright (C) 1994-1999, Index Data - * All rights reserved. - * Sebastian Hammer, Adam Dickmeiss - * - * $Log: extract.c,v $ - * Revision 1.94 1999-05-20 12:57:18 adam - * Implemented TCL filter. Updated recctrl system. - * - * Revision 1.93 1999/05/15 14:36:38 adam - * Updated dictionary. Implemented "compression" of dictionary. - * - * Revision 1.92 1999/03/09 16:27:49 adam - * More work on SDRKit integration. - * - * Revision 1.91 1999/02/12 13:29:22 adam - * Implemented position-flag for registers. - * - * Revision 1.90 1999/02/02 14:50:52 adam - * Updated WIN32 code specific sections. Changed header. - * - * Revision 1.89 1998/10/28 10:54:38 adam - * SDRKit integration. - * - * Revision 1.88 1998/10/16 08:14:29 adam - * Updated record control system. - * - * Revision 1.87 1998/10/15 13:10:33 adam - * Fixed bug in Zebra that caused it to stop indexing when empty - * record was read. - * - * Revision 1.86 1998/10/13 20:33:53 adam - * Fixed one log message and change use ordinal to be an unsigned char. - * - * Revision 1.85 1998/09/22 10:03:41 adam - * Changed result sets to be persistent in the sense that they can - * be re-searched if needed. - * Fixed memory leak in rsm_or. - * - * Revision 1.84 1998/06/11 15:42:22 adam - * Changed the way use attributes are specified in the recordId - * specification. - * - * Revision 1.83 1998/06/08 14:43:10 adam - * Added suport for EXPLAIN Proxy servers - added settings databasePath - * and explainDatabase to facilitate this. Increased maximum number - * of databases and attributes in one register. - * - * Revision 1.82 1998/05/20 10:12:15 adam - * Implemented automatic EXPLAIN database maintenance. - * Modified Zebra to work with ASN.1 compiled version of YAZ. - * - * Revision 1.81 1998/03/11 11:19:04 adam - * Changed the way sequence numbers are generated. - * - * Revision 1.80 1998/03/05 08:45:11 adam - * New result set model and modular ranking system. Moved towards - * descent server API. System information stored as "SGML" records. - * - * Revision 1.79 1998/02/17 10:32:52 adam - * Fixed bug: binary files weren't opened with flag b on NT. - * - * Revision 1.78 1998/02/10 12:03:05 adam - * Implemented Sort. - * - * Revision 1.77 1998/01/12 15:04:08 adam - * The test option (-s) only uses read-lock (and not write lock). - * - * Revision 1.76 1997/10/27 14:33:04 adam - * Moved towards generic character mapping depending on "structure" - * field in abstract syntax file. Fixed a few memory leaks. Fixed - * bug with negative integers when doing searches with relational - * operators. - * - * Revision 1.75 1997/09/17 12:19:12 adam - * Zebra version corresponds to YAZ version 1.4. - * Changed Zebra server so that it doesn't depend on global common_resource. - * - * Revision 1.74 1997/09/09 13:38:06 adam - * Partial port to WIN95/NT. - * - * Revision 1.73 1997/09/04 13:57:20 adam - * New file extract/retrieve method tellf (added). - * Added O_BINARY for open calls. - * - * Revision 1.72 1997/07/15 16:32:29 adam - * Bug fix: Match handler didn't terminate the resulting string! - * - * Revision 1.71 1997/07/15 16:28:41 adam - * Bug fix: storeData didn't work with files with multiple records. - * Bug fix: fixed memory management with records; not really well - * thought through. - * - * Revision 1.70 1997/07/01 13:00:42 adam - * Bug fix in routine searchRecordKey: uninitialized variables. - * - * Revision 1.69 1997/04/29 09:26:03 adam - * Bug fix: generic recordId handling didn't work for compressed internal - * keys. - * - * Revision 1.68 1997/02/12 20:39:45 adam - * Implemented options -f that limits the log to the first - * records. - * Changed some log messages also. - * - * Revision 1.67 1996/11/15 15:02:14 adam - * Minor changes regarding logging. - * - * Revision 1.66 1996/11/14 09:52:21 adam - * Strings in record keys bound by IT_MAX_WORD. - * - * Revision 1.65 1996/11/14 08:57:56 adam - * Reduction of storeKeys area. - * - * Revision 1.64 1996/11/08 11:10:16 adam - * Buffers used during file match got bigger. - * Compressed ISAM support everywhere. - * Bug fixes regarding masking characters in queries. - * Redesigned Regexp-2 queries. - * - * Revision 1.63 1996/10/29 14:09:39 adam - * Use of cisam system - enabled if setting isamc is 1. - * - * Revision 1.62 1996/10/11 10:57:01 adam - * New module recctrl. Used to manage records (extract/retrieval). - * Several files have been moved to the recctrl sub directory. - * - * Revision 1.61 1996/06/06 12:08:37 quinn - * Added showRecord function - * - * Revision 1.60 1996/06/04 10:18:12 adam - * Search/scan uses character mapping module. - * - * Revision 1.59 1996/05/14 15:47:07 adam - * Cleanup of various buffer size entities. - * - * Revision 1.58 1996/05/14 06:16:38 adam - * Compact use/set bytes used in search service. - * - * Revision 1.57 1996/05/13 14:23:04 adam - * Work on compaction of set/use bytes in dictionary. - * - * Revision 1.56 1996/05/09 09:54:42 adam - * Server supports maps from one logical attributes to a list of physical - * attributes. - * The extraction process doesn't make space consuming 'any' keys. - * - * Revision 1.55 1996/05/09 07:28:55 quinn - * Work towards phrases and multiple registers - * - * Revision 1.54 1996/05/01 13:46:35 adam - * First work on multiple records in one file. - * New option, -offset, to the "unread" command in the filter module. - * - * Revision 1.53 1996/04/26 12:09:43 adam - * Added a few comments. - * - * Revision 1.52 1996/04/25 13:27:57 adam - * Function recordExtract modified so that files with no keys (possibly empty) - * are ignored. - * - * Revision 1.51 1996/03/19 11:08:42 adam - * Bug fix: Log preamble wasn't always turned off after recordExtract. - * - * Revision 1.50 1996/02/12 18:45:36 adam - * New fileVerboseFlag in record group control. - * - * Revision 1.49 1996/02/05 12:29:57 adam - * Logging reduced a bit. - * The remaining running time is estimated during register merge. - * - * Revision 1.48 1996/02/01 20:53:26 adam - * The temporary per-record keys are compacted a little, and duplication - * of the per-records keys are avoided when they are saved in the record - * information buffer. - * - * Revision 1.47 1996/01/17 14:57:48 adam - * Prototype changed for reader functions in extract/retrieve. File - * is identified by 'void *' instead of 'int. - * - * Revision 1.46 1995/12/15 14:57:16 adam - * Bug fix. - * - * Revision 1.45 1995/12/15 12:37:41 adam - * In addRecordKeyAny: Writes key only when attrSet != -1. - * - * Revision 1.44 1995/12/12 16:00:54 adam - * System call sync(2) used after update/commit. - * Locking (based on fcntl) uses F_EXLCK and F_SHLCK instead of F_WRLCK - * and F_RDLCK. - * - * Revision 1.43 1995/12/11 09:12:46 adam - * The rec_get function returns NULL if record doesn't exist - will - * happen in the server if the result set records have been deleted since - * the creation of the set (i.e. the search). - * The server saves a result temporarily if it is 'volatile', i.e. the - * set is register dependent. - * - * Revision 1.42 1995/12/07 17:38:46 adam - * Work locking mechanisms for concurrent updates/commit. - * - * Revision 1.41 1995/12/06 16:06:42 adam - * Better diagnostics. Work on 'real' dictionary deletion. - * - * Revision 1.40 1995/12/05 16:57:40 adam - * More work on regular patterns. - * - * Revision 1.39 1995/12/05 13:20:18 adam - * Bug fix: file_read sometimes returned early EOF. - * - * Revision 1.38 1995/12/04 17:59:21 adam - * More work on regular expression conversion. - * - * Revision 1.37 1995/12/04 14:22:27 adam - * Extra arg to recType_byName. - * Started work on new regular expression parsed input to - * structured records. - * - * Revision 1.36 1995/11/30 08:34:29 adam - * Started work on commit facility. - * Changed a few malloc/free to xmalloc/xfree. - * - * Revision 1.35 1995/11/28 14:26:21 adam - * Bug fix: recordId with constant wasn't right. - * Bug fix: recordId dictionary entry wasn't deleted when needed. - * - * Revision 1.34 1995/11/28 09:09:38 adam - * Zebra config renamed. - * Use setting 'recordId' to identify record now. - * Bug fix in recindex.c: rec_release_blocks was invokeded even - * though the blocks were already released. - * File traversal properly deletes records when needed. - * - * Revision 1.33 1995/11/27 09:56:20 adam - * Record info elements better enumerated. Internal store of records. - * - * Revision 1.32 1995/11/25 10:24:05 adam - * More record fields - they are enumerated now. - * New options: flagStoreData flagStoreKey. - * - * Revision 1.31 1995/11/24 11:31:35 adam - * Commands add & del read filenames from stdin if source directory is - * empty. - * Match criteria supports 'constant' strings. - * - * Revision 1.30 1995/11/22 17:19:16 adam - * Record management uses the bfile system. - * - * Revision 1.29 1995/11/21 15:01:14 adam - * New general match criteria implemented. - * New feature: document groups. - * - * Revision 1.28 1995/11/21 09:20:30 adam - * Yet more work on record match. - * - * Revision 1.27 1995/11/20 16:59:45 adam - * New update method: the 'old' keys are saved for each records. - * - * Revision 1.26 1995/11/20 11:56:24 adam - * Work on new traversal. - * - * Revision 1.25 1995/11/16 15:34:54 adam - * Uses new record management system in both indexer and server. - * - * Revision 1.24 1995/11/15 19:13:08 adam - * Work on record management. - * - * Revision 1.23 1995/10/27 14:00:10 adam - * Implemented detection of database availability. - * - * Revision 1.22 1995/10/17 18:02:07 adam - * New feature: databases. Implemented as prefix to words in dictionary. - * - * Revision 1.21 1995/10/10 12:24:38 adam - * Temporary sort files are compressed. - * - * Revision 1.20 1995/10/06 13:52:05 adam - * Bug fixes. Handler may abort further scanning. - * - * Revision 1.19 1995/10/04 12:55:16 adam - * Bug fix in ranked search. Use=Any keys inserted. - * - * Revision 1.18 1995/10/04 09:37:08 quinn - * Fixed bug. - * - * Revision 1.17 1995/10/03 14:28:57 adam - * Buffered read in extract works. - * - * Revision 1.16 1995/10/03 14:28:45 adam - * Work on more effecient read handler in extract. - * - * Revision 1.15 1995/10/02 15:42:53 adam - * Extract uses file descriptors instead of FILE pointers. - * - * Revision 1.14 1995/10/02 15:29:13 adam - * More logging in file_extract. - * - * Revision 1.13 1995/09/29 14:01:39 adam - * Bug fixes. - * - * Revision 1.12 1995/09/28 14:22:56 adam - * Sort uses smaller temporary files. - * - * Revision 1.11 1995/09/28 12:10:31 adam - * Bug fixes. Field prefix used in queries. - * - * Revision 1.10 1995/09/28 09:19:41 adam - * xfree/xmalloc used everywhere. - * Extract/retrieve method seems to work for text records. - * - * Revision 1.9 1995/09/27 12:22:28 adam - * More work on extract in record control. - * Field name is not in isam keys but in prefix in dictionary words. - * - * Revision 1.8 1995/09/14 07:48:22 adam - * Record control management. - * - * Revision 1.7 1995/09/11 13:09:32 adam - * More work on relevance feedback. - * - * Revision 1.6 1995/09/08 14:52:27 adam - * Minor changes. Dictionary is lower case now. - * - * Revision 1.5 1995/09/06 16:11:16 adam - * Option: only one word key per file. - * - * Revision 1.4 1995/09/05 15:28:39 adam - * More work on search engine. - * - * Revision 1.3 1995/09/04 12:33:41 adam - * Various cleanup. YAZ util used instead. - * - * Revision 1.2 1995/09/04 09:10:34 adam - * More work on index add/del/update. - * Merge sort implemented. - * Initial work on z39 server. - * - * Revision 1.1 1995/09/01 14:06:35 adam - * Split of work into more files. - * - */ +/* $Id: extract.c,v 1.275 2007-12-20 11:15:42 adam Exp $ + Copyright (C) 1995-2007 + Index Data ApS + +This file is part of the Zebra server. + +Zebra is free software; you can redistribute it and/or modify it under +the terms of the GNU General Public License as published by the Free +Software Foundation; either version 2, or (at your option) any later +version. + +Zebra is distributed in the hope that it will be useful, but WITHOUT ANY +WARRANTY; without even the implied warranty of MERCHANTABILITY or +FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +*/ + +/** \file + \brief indexes records and extract tokens for indexing and sorting +*/ + #include #include +#include #ifdef WIN32 #include -#else +#endif +#if HAVE_UNISTD_H #include #endif #include -#include -#include -#include -#include "index.h" - -#include "zinfo.h" - -#ifndef ZEBRASDR -#define ZEBRASDR 0 -#endif - -#if ZEBRASDR -#include "zebrasdr.h" -#endif - -static Dict matchDict; -static Records records = NULL; -static SortIdx sortIdx = NULL; +#include "index.h" +#include "orddict.h" +#include +#include +#include -static char **key_buf; -static size_t ptr_top; -static size_t ptr_i; -static size_t key_buf_used; -static int key_file_no; +static int log_level_extract = 0; +static int log_level_details = 0; +static int log_level_initialized = 0; -static int records_inserted = 0; -static int records_updated = 0; -static int records_deleted = 0; -static int records_processed = 0; +/* 1 if we use eliminitate identical delete/insert keys */ +/* eventually this the 0-case code will be removed */ +#define FLUSH2 1 -static ZebraExplainInfo zti = NULL; +void extract_flush_record_keys2(ZebraHandle zh, zint sysno, + zebra_rec_keys_t ins_keys, + zint ins_rank, + zebra_rec_keys_t del_keys, + zint del_rank); -static void logRecord (int showFlag) +static void zebra_init_log_level(void) { - if (!showFlag) - ++records_processed; - if (showFlag || !(records_processed % 1000)) + if (!log_level_initialized) { - logf (LOG_LOG, "Records: %7d i/u/d %d/%d/%d", - records_processed, records_inserted, records_updated, - records_deleted); - } -} - -static int explain_extract (void *handle, Record drec, data1_node *n); + log_level_initialized = 1; -int key_open (struct recordGroup *rGroup, int mem) -{ - BFiles bfs = rGroup->bfs; - int rw = rGroup->flagRw; - data1_handle dh = rGroup->dh; - if (!mem) - mem = atoi(res_get_def (common_resource, "memMax", "4"))*1024*1024; - if (mem < 50000) - mem = 50000; - key_buf = xmalloc (mem); - ptr_top = mem/sizeof(char*); - ptr_i = 0; - - key_buf_used = 0; - key_file_no = 0; - - if (!(matchDict = dict_open (bfs, GMATCH_DICT, 50, rw, 0))) - { - logf (LOG_FATAL, "dict_open fail of %s", GMATCH_DICT); - return -1; - } - assert (!records); - records = rec_open (bfs, rw); - if (!records) - { - dict_close (matchDict); - return -1; + log_level_extract = yaz_log_module_level("extract"); + log_level_details = yaz_log_module_level("indexdetails"); } - zti = zebraExplain_open (records, dh, common_resource, - rw, rGroup, explain_extract); - if (!zti) - { - rec_close (&records); - dict_close (matchDict); - return -1; - } - sortIdx = sortIdx_open (bfs, 1); - return 0; } -struct encode_info { - int sysno; - int seqno; - int cmd; - char buf[768]; -}; - -void encode_key_init (struct encode_info *i) -{ - i->sysno = 0; - i->seqno = 0; - i->cmd = -1; -} +static void extract_flush_sort_keys(ZebraHandle zh, zint sysno, + int cmd, zebra_rec_keys_t skp); +static void extract_schema_add(struct recExtractCtrl *p, Odr_oid *oid); +static void extract_token_add(RecWord *p); -char *encode_key_int (int d, char *bp) +static void check_log_limit(ZebraHandle zh) { - if (d <= 63) - *bp++ = d; - else if (d <= 16383) - { - *bp++ = 64 + (d>>8); - *bp++ = d & 255; - } - else if (d <= 4194303) + if (zh->records_processed + zh->records_skipped == zh->m_file_verbose_limit) { - *bp++ = 128 + (d>>16); - *bp++ = (d>>8) & 255; - *bp++ = d & 255; + yaz_log(YLOG_LOG, "More than %d file log entries. Omitting rest", + zh->m_file_verbose_limit); } - else - { - *bp++ = 192 + (d>>24); - *bp++ = (d>>16) & 255; - *bp++ = (d>>8) & 255; - *bp++ = d & 255; - } - return bp; } -void encode_key_write (char *k, struct encode_info *i, FILE *outf) +static void logRecord(ZebraHandle zh) { - struct it_key key; - char *bp = i->buf; - - while ((*bp++ = *k++)) - ; - memcpy (&key, k+1, sizeof(struct it_key)); - bp = encode_key_int ( (key.sysno - i->sysno) * 2 + *k, bp); - if (i->sysno != key.sysno) - { - i->sysno = key.sysno; - i->seqno = 0; - } - else if (!i->seqno && !key.seqno && i->cmd == *k) - return; - bp = encode_key_int (key.seqno - i->seqno, bp); - i->seqno = key.seqno; - i->cmd = *k; - if (fwrite (i->buf, bp - i->buf, 1, outf) != 1) + check_log_limit(zh); + ++zh->records_processed; + if (!(zh->records_processed % 1000)) { - logf (LOG_FATAL|LOG_ERRNO, "fwrite"); - exit (1); + yaz_log(YLOG_LOG, "Records: "ZINT_FORMAT" i/u/d " + ZINT_FORMAT"/"ZINT_FORMAT"/"ZINT_FORMAT, + zh->records_processed, zh->records_inserted, + zh->records_updated, zh->records_deleted); } } -#define SORT_EXTRA 0 - -#if SORT_EXTRA -static int key_y_len; - -static int key_y_compare (const void *p1, const void *p2) -{ - int r; - - if ((r = key_compare (*(char**) p1 + key_y_len + 1, - *(char**) p2 + key_y_len + 1))) - return r; - return *(*(char**) p1 + key_y_len) - *(*(char**) p2 + key_y_len); -} - -static int key_x_compare (const void *p1, const void *p2) +static void init_extractCtrl(ZebraHandle zh, struct recExtractCtrl *ctrl) { - return strcmp (*(char**) p1, *(char**) p2); + ctrl->flagShowRecords = !zh->m_flag_rw; } -#endif - -void key_flush (void) -{ - FILE *outf; - char out_fname[200]; - char *prevcp, *cp; - struct encode_info encode_info; -#if SORT_EXTRA - int i; -#endif - - if (ptr_i <= 0) - return; - - key_file_no++; - logf (LOG_LOG, "sorting section %d", key_file_no); -#if !SORT_EXTRA - qsort (key_buf + ptr_top-ptr_i, ptr_i, sizeof(char*), key_qsort_compare); - getFnameTmp (out_fname, key_file_no); - - if (!(outf = fopen (out_fname, "wb"))) - { - logf (LOG_FATAL|LOG_ERRNO, "fopen %s", out_fname); - exit (1); - } - logf (LOG_LOG, "writing section %d", key_file_no); - prevcp = cp = key_buf[ptr_top-ptr_i]; - - encode_key_init (&encode_info); - encode_key_write (cp, &encode_info, outf); - while (--ptr_i > 0) - { - cp = key_buf[ptr_top-ptr_i]; - if (strcmp (cp, prevcp)) - { - encode_key_init (&encode_info); - encode_key_write (cp, &encode_info, outf); - prevcp = cp; - } - else - encode_key_write (cp + strlen(cp), &encode_info, outf); - } -#else - qsort (key_buf + ptr_top-ptr_i, ptr_i, sizeof(char*), key_x_compare); - getFnameTmp (out_fname, key_file_no); - if (!(outf = fopen (out_fname, "wb"))) - { - logf (LOG_FATAL|LOG_ERRNO, "fopen %s", out_fname); - exit (1); - } - logf (LOG_LOG, "writing section %d", key_file_no); - i = ptr_i; - prevcp = key_buf[ptr_top-i]; - while (1) - if (!--i || strcmp (prevcp, key_buf[ptr_top-i])) - { - key_y_len = strlen(prevcp)+1; -#if 0 - logf (LOG_LOG, "key_y_len: %2d %02x %02x %s", - key_y_len, prevcp[0], prevcp[1], 2+prevcp); -#endif - qsort (key_buf + ptr_top-ptr_i, ptr_i - i, - sizeof(char*), key_y_compare); - cp = key_buf[ptr_top-ptr_i]; - --key_y_len; - encode_key_init (&encode_info); - encode_key_write (cp, &encode_info, outf); - while (--ptr_i > i) - { - cp = key_buf[ptr_top-ptr_i]; - encode_key_write (cp+key_y_len, &encode_info, outf); - } - if (!i) - break; - prevcp = key_buf[ptr_top-ptr_i]; - } -#endif - if (fclose (outf)) - { - logf (LOG_FATAL|LOG_ERRNO, "fclose %s", out_fname); - exit (1); - } - logf (LOG_LOG, "finished section %d", key_file_no); - ptr_i = 0; - key_buf_used = 0; -} -int key_close (struct recordGroup *rGroup) -{ - int rw = rGroup->flagRw; - if (rw) - zebraExplain_runNumberIncrement (zti, 1); - zebraExplain_close (zti, rw, 0); - key_flush (); - xfree (key_buf); - rec_close (&records); - dict_close (matchDict); - sortIdx_close (sortIdx); - - logRecord (1); - return key_file_no; -} +static void extract_add_index_string(RecWord *p, + zinfo_index_category_t cat, + const char *str, int length); -static void wordInit (struct recExtractCtrl *p, RecWord *w) -{ - w->zebra_maps = p->zebra_maps; - w->seqnos = p->seqno; - w->attrSet = VAL_BIB1; - w->attrUse = 1016; - w->reg_type = 'w'; -} +static void extract_set_store_data_prepare(struct recExtractCtrl *p); -static struct sortKey { - char *string; - int length; - int attrSet; - int attrUse; - struct sortKey *next; -} *sortKeys = NULL; - -static struct recKeys { - int buf_used; - int buf_max; - char *buf; - char prevAttrSet; - short prevAttrUse; - int prevSeqNo; -} reckeys; - -static void addIndexString (RecWord *p, const char *string, int length) +static void extract_init(struct recExtractCtrl *p, RecWord *w) { - char *dst; - unsigned char attrSet; - unsigned short attrUse; - int lead = 0; - int diff = 0; - int *pseqno = &p->seqnos[p->reg_type]; - - if (reckeys.buf_used+1024 > reckeys.buf_max) - { - char *b; - - b = xmalloc (reckeys.buf_max += 128000); - if (reckeys.buf_used > 0) - memcpy (b, reckeys.buf, reckeys.buf_used); - xfree (reckeys.buf); - reckeys.buf = b; - } - dst = reckeys.buf + reckeys.buf_used; - - attrSet = p->attrSet; - if (reckeys.buf_used > 0 && reckeys.prevAttrSet == attrSet) - lead |= 1; - else - reckeys.prevAttrSet = attrSet; - attrUse = p->attrUse; - if (reckeys.buf_used > 0 && reckeys.prevAttrUse == attrUse) - lead |= 2; - else - reckeys.prevAttrUse = attrUse; -#if 1 - diff = 1 + *pseqno - reckeys.prevSeqNo; - if (diff >= 1 && diff <= 15) - lead |= (diff << 2); - else - diff = 0; -#endif - reckeys.prevSeqNo = *pseqno; - - *dst++ = lead; - - if (!(lead & 1)) - { - memcpy (dst, &attrSet, sizeof(attrSet)); - dst += sizeof(attrSet); - } - if (!(lead & 2)) - { - memcpy (dst, &attrUse, sizeof(attrUse)); - dst += sizeof(attrUse); - } - *dst++ = p->reg_type; - memcpy (dst, string, length); - dst += length; - *dst++ = '\0'; - - if (!diff) - { - memcpy (dst, pseqno, sizeof(*pseqno)); - dst += sizeof(*pseqno); - } - reckeys.buf_used = dst - reckeys.buf; - if (*pseqno) - (*pseqno)++; + w->seqno = 1; + w->index_name = "any"; + w->index_type = "w"; + w->extractCtrl = p; + w->record_id = 0; + w->section_id = 0; + w->segment = 0; } -static void addSortString (RecWord *p, const char *string, int length) -{ - struct sortKey *sk; - - for (sk = sortKeys; sk; sk = sk->next) - if (sk->attrSet == p->attrSet && sk->attrUse == p->attrUse) - return; - - sk = xmalloc (sizeof(*sk)); - sk->next = sortKeys; - sortKeys = sk; - - sk->string = xmalloc (length); - sk->length = length; - memcpy (sk->string, string, length); +struct snip_rec_info { + ZebraHandle zh; + zebra_snippets *snippets; +}; - sk->attrSet = p->attrSet; - sk->attrUse = p->attrUse; -} -static void addString (RecWord *p, const char *string, int length) +static void snippet_add_complete_field(RecWord *p, int ord, + zebra_map_t zm) { - assert (length > 0); - if (zebra_maps_is_sort (p->zebra_maps, p->reg_type)) - addSortString (p, string, length); - else - addIndexString (p, string, length); -} + struct snip_rec_info *h = p->extractCtrl->handle; -static void addIncompleteField (RecWord *p) -{ - const char *b = p->string; - int remain = p->length; + const char *b = p->term_buf; + char buf[IT_MAX_WORD+1]; const char **map = 0; + int i = 0, remain = p->term_len; + const char *start = b; + const char *last = 0; if (remain > 0) - map = zebra_maps_input(p->zebra_maps, p->reg_type, &b, remain); + map = zebra_maps_input(zm, &b, remain, 1); - while (map) + while (remain > 0 && i < IT_MAX_WORD) { - char buf[IT_MAX_WORD+1]; - int i, remain; - - /* Skip spaces */ while (map && *map && **map == *CHR_SPACE) { - remain = p->length - (b - p->string); + remain = p->term_len - (b - p->term_buf); + + if (i == 0) + start = b; /* set to first non-ws area */ if (remain > 0) - map = zebra_maps_input(p->zebra_maps, p->reg_type, &b, remain); + { + int first = i ? 0 : 1; /* first position */ + + map = zebra_maps_input(zm, &b, remain, first); + } else map = 0; } if (!map) break; - i = 0; + + if (i && i < IT_MAX_WORD) + buf[i++] = *CHR_SPACE; while (map && *map && **map != *CHR_SPACE) { const char *cp = *map; - while (i < IT_MAX_WORD && *cp) - buf[i++] = *(cp++); - remain = p->length - (b - p->string); + if (**map == *CHR_CUT) + { + i = 0; + } + else + { + if (i >= IT_MAX_WORD) + break; + while (i < IT_MAX_WORD && *cp) + buf[i++] = *(cp++); + } + last = b; + remain = p->term_len - (b - p->term_buf); if (remain > 0) - map = zebra_maps_input(p->zebra_maps, p->reg_type, &b, remain); + { + map = zebra_maps_input(zm, &b, remain, 0); + } else map = 0; } - if (!i) - return; - addString (p, buf, i); } + if (!i) + return; + if (last && start != last) + zebra_snippets_appendn(h->snippets, p->seqno, 0, ord, + start, last - start); } -static void addCompleteField (RecWord *p) +static void snippet_add_incomplete_field(RecWord *p, int ord, zebra_map_t zm) { - const char *b = p->string; - char buf[IT_MAX_WORD+1]; + struct snip_rec_info *h = p->extractCtrl->handle; + const char *b = p->term_buf; + int remain = p->term_len; + int first = 1; const char **map = 0; - int i = 0, remain = p->length; + const char *start = b; + const char *last = b; if (remain > 0) - map = zebra_maps_input (p->zebra_maps, p->reg_type, &b, remain); + map = zebra_maps_input(zm, &b, remain, 0); - while (remain > 0 && i < IT_MAX_WORD) + while (map) { + char buf[IT_MAX_WORD+1]; + int i, remain; + + /* Skip spaces */ while (map && *map && **map == *CHR_SPACE) { - remain = p->length - (b - p->string); + remain = p->term_len - (b - p->term_buf); + last = b; if (remain > 0) - map = zebra_maps_input(p->zebra_maps, p->reg_type, &b, remain); + map = zebra_maps_input(zm, &b, remain, 0); else map = 0; } if (!map) break; + if (start != last) + { + zebra_snippets_appendn(h->snippets, p->seqno, 1, ord, + start, last - start); - if (i && i < IT_MAX_WORD) - buf[i++] = *CHR_SPACE; + } + start = last; + + i = 0; while (map && *map && **map != *CHR_SPACE) { const char *cp = *map; - if (i >= IT_MAX_WORD) - break; while (i < IT_MAX_WORD && *cp) buf[i++] = *(cp++); - remain = p->length - (b - p->string); + remain = p->term_len - (b - p->term_buf); + last = b; if (remain > 0) - map = zebra_maps_input (p->zebra_maps, p->reg_type, &b, - remain); + map = zebra_maps_input(zm, &b, remain, 0); else map = 0; } + if (!i) + return; + + if (first) + { + first = 0; + if (zebra_maps_is_first_in_field(zm)) + { + /* first in field marker */ + p->seqno++; + } + } + if (start != last) + zebra_snippets_appendn(h->snippets, p->seqno, 0, ord, + start, last - start); + start = last; + p->seqno++; } - if (!i) - return; - addString (p, buf, i); -} -static void addRecordKey (RecWord *p) -{ - if (zebra_maps_is_complete (p->zebra_maps, p->reg_type)) - addCompleteField (p); - else - addIncompleteField(p); } -static void flushSortKeys (SYSNO sysno, int cmd) +static void snippet_add_icu(RecWord *p, int ord, zebra_map_t zm) { - struct sortKey *sk = sortKeys; + struct snip_rec_info *h = p->extractCtrl->handle; + + const char *res_buf = 0; + size_t res_len = 0; - sortIdx_sysno (sortIdx, sysno); - while (sk) + const char *display_buf = 0; + size_t display_len = 0; + + zebra_map_tokenize_start(zm, p->term_buf, p->term_len); + while (zebra_map_tokenize_next(zm, &res_buf, &res_len, + &display_buf, &display_len)) { - struct sortKey *sk_next = sk->next; - sortIdx_type (sortIdx, sk->attrUse); - sortIdx_add (sortIdx, sk->string, sk->length); - xfree (sk->string); - xfree (sk); - sk = sk_next; + zebra_snippets_appendn(h->snippets, p->seqno, 0, ord, + display_buf, display_len); + p->seqno++; } - sortKeys = NULL; } -static void flushRecordKeys (SYSNO sysno, int cmd, struct recKeys *reckeys) +static void snippet_token_add(RecWord *p) { - unsigned char attrSet = (unsigned char) -1; - unsigned short attrUse = (unsigned short) -1; - int seqno = 0; - int off = 0; + struct snip_rec_info *h = p->extractCtrl->handle; + ZebraHandle zh = h->zh; + zebra_map_t zm = zebra_map_get(zh->reg->zebra_maps, p->index_type); - zebraExplain_recordCountIncrement (zti, cmd ? 1 : -1); - while (off < reckeys->buf_used) + if (zm && zebra_maps_is_index(zm)) { - const char *src = reckeys->buf + off; - struct it_key key; - int lead, ch; - - lead = *src++; + ZebraExplainInfo zei = zh->reg->zei; + int ch = zebraExplain_lookup_attr_str( + zei, zinfo_index_category_index, p->index_type, p->index_name); - if (!(lead & 1)) - { - memcpy (&attrSet, src, sizeof(attrSet)); - src += sizeof(attrSet); - } - if (!(lead & 2)) - { - memcpy (&attrUse, src, sizeof(attrUse)); - src += sizeof(attrUse); - } - if (key_buf_used + 1024 > (ptr_top-ptr_i)*sizeof(char*)) - key_flush (); - ++ptr_i; - key_buf[ptr_top-ptr_i] = (char*)key_buf + key_buf_used; - - ch = zebraExplain_lookupSU (zti, attrSet, attrUse); - if (ch < 0) - ch = zebraExplain_addSU (zti, attrSet, attrUse); - assert (ch > 0); - key_buf_used += key_SU_code (ch, ((char*)key_buf) + key_buf_used); - - while (*src) - ((char*)key_buf) [key_buf_used++] = *src++; - src++; - ((char*)key_buf) [key_buf_used++] = '\0'; - ((char*) key_buf)[key_buf_used++] = cmd; - - if (lead & 60) - seqno += ((lead>>2) & 15)-1; + if (zebra_maps_is_icu(zm)) + snippet_add_icu(p, ch, zm); else { - memcpy (&seqno, src, sizeof(seqno)); - src += sizeof(seqno); + if (zebra_maps_is_complete(zm)) + snippet_add_complete_field(p, ch, zm); + else + snippet_add_incomplete_field(p, ch, zm); } - key.seqno = seqno; - key.sysno = sysno; - memcpy ((char*)key_buf + key_buf_used, &key, sizeof(key)); - key_buf_used += sizeof(key); - off = src - reckeys->buf; } - assert (off == reckeys->buf_used); } -static const char **searchRecordKey (struct recKeys *reckeys, - int attrSetS, int attrUseS) +static void snippet_schema_add( + struct recExtractCtrl *p, Odr_oid *oid) { - static const char *ws[32]; - int off = 0; - int startSeq = -1; - int i; - short attrUse; - char attrSet; - int seqno = 0; - - for (i = 0; i<32; i++) - ws[i] = NULL; - - while (off < reckeys->buf_used) - { - const char *src = reckeys->buf + off; - const char *wstart; - int lead; - - lead = *src++; +} - if (!(lead & 1)) - { - memcpy (&attrSet, src, sizeof(attrSet)); - src += sizeof(attrSet); - } - if (!(lead & 2)) - { - memcpy (&attrUse, src, sizeof(attrUse)); - src += sizeof(attrUse); - } - wstart = src; - while (*src++) - ; - if (lead & 60) - seqno += ((lead>>2) & 15)-1; - else - { - memcpy (&seqno, src, sizeof(seqno)); - src += sizeof(seqno); - } - if (attrUseS == attrUse && attrSetS == attrSet) - { - int woff; +void extract_snippet(ZebraHandle zh, zebra_snippets *sn, + struct ZebraRecStream *stream, + RecType rt, void *recTypeClientData) +{ + struct recExtractCtrl extractCtrl; + struct snip_rec_info info; + int r; + extractCtrl.stream = stream; + extractCtrl.first_record = 1; + extractCtrl.init = extract_init; + extractCtrl.tokenAdd = snippet_token_add; + extractCtrl.schemaAdd = snippet_schema_add; + assert(zh->reg); + assert(zh->reg->dh); - if (startSeq == -1) - startSeq = seqno; - woff = seqno - startSeq; - if (woff >= 0 && woff < 31) - ws[woff] = wstart; - } + extractCtrl.dh = zh->reg->dh; + + info.zh = zh; + info.snippets = sn; + extractCtrl.handle = &info; + extractCtrl.match_criteria[0] = '\0'; + extractCtrl.staticrank = 0; + extractCtrl.action = action_insert; + + init_extractCtrl(zh, &extractCtrl); - off = src - reckeys->buf; - } - assert (off == reckeys->buf_used); - return ws; -} + extractCtrl.setStoreData = 0; -struct file_read_info { - off_t file_max; /* maximum offset so far */ - off_t file_offset; /* current offset */ - off_t file_moffset; /* offset of rec/rec boundary */ - int file_more; - int fd; - char *sdrbuf; - int sdrmax; -}; + r = (*rt->extract)(recTypeClientData, &extractCtrl); -static struct file_read_info *file_read_start (int fd) -{ - struct file_read_info *fi = xmalloc (sizeof(*fi)); - - fi->fd = fd; - fi->file_max = 0; - fi->file_moffset = 0; - fi->sdrbuf = 0; - fi->sdrmax = 0; - return fi; } -static void file_read_stop (struct file_read_info *fi) +static void searchRecordKey(ZebraHandle zh, + zebra_rec_keys_t reckeys, + const char *index_name, + const char **ws, int ws_length) { - xfree (fi); -} + int i; + int ch = -1; + zinfo_index_category_t cat = zinfo_index_category_index; -static off_t file_seek (void *handle, off_t offset) -{ - struct file_read_info *p = handle; - p->file_offset = offset; - if (p->sdrbuf) - return offset; - return lseek (p->fd, offset, SEEK_SET); -} + for (i = 0; ifile_offset; -} + if (ch < 0) + ch = zebraExplain_lookup_attr_str(zh->reg->zei, cat, "0", index_name); + if (ch < 0) + ch = zebraExplain_lookup_attr_str(zh->reg->zei, cat, "p", index_name); + if (ch < 0) + ch = zebraExplain_lookup_attr_str(zh->reg->zei, cat, "w", index_name); -static int file_read (void *handle, char *buf, size_t count) -{ - struct file_read_info *p = handle; - int fd = p->fd; - int r; - if (p->sdrbuf) - { - r = count; - if (r > p->sdrmax - p->file_offset) - r = p->sdrmax - p->file_offset; - if (r) - memcpy (buf, p->sdrbuf + p->file_offset, r); - } - else - r = read (fd, buf, count); - if (r > 0) - { - p->file_offset += r; - if (p->file_offset > p->file_max) - p->file_max = p->file_offset; - } - return r; -} + if (ch < 0) + return ; -static void file_begin (void *handle) -{ - struct file_read_info *p = handle; + if (zebra_rec_keys_rewind(reckeys)) + { + zint startSeq = -1; + const char *str; + size_t slen; + struct it_key key; + zint seqno; + while (zebra_rec_keys_read(reckeys, &str, &slen, &key)) + { + assert(key.len <= IT_KEY_LEVEL_MAX && key.len > 2); - p->file_offset = p->file_moffset; - if (!p->sdrbuf && p->file_moffset) - lseek (p->fd, p->file_moffset, SEEK_SET); - p->file_more = 0; + seqno = key.mem[key.len-1]; + + if (key.mem[0] == ch) + { + zint woff; + + if (startSeq == -1) + startSeq = seqno; + woff = seqno - startSeq; + if (woff >= 0 && woff < ws_length) + ws[woff] = str; + } + } + } } -static void file_end (void *handle, off_t offset) -{ - struct file_read_info *p = handle; - - assert (p->file_more == 0); - p->file_more = 1; - p->file_moffset = offset; -} +#define FILE_MATCH_BLANK "\t " -static char *fileMatchStr (struct recKeys *reckeys, struct recordGroup *rGroup, - const char *fname, const char *spec) +static char *get_match_from_spec(ZebraHandle zh, + zebra_rec_keys_t reckeys, + const char *fname, const char *spec) { - static char dstBuf[2048]; + static char dstBuf[2048]; /* static here ??? */ char *dst = dstBuf; const char *s = spec; - static const char **w; while (1) { - while (*s == ' ' || *s == '\t') - s++; + for (; *s && strchr(FILE_MATCH_BLANK, *s); s++) + ; if (!*s) break; if (*s == '(') { + const char *ws[32]; char attset_str[64], attname_str[64]; - data1_attset *attset; int i; - char matchFlag[32]; - int attSet = 1, attUse = 1; int first = 1; - - s++; - for (i = 0; *s && *s != ',' && *s != ')'; s++) - if (i < 63) + + for (s++; strchr(FILE_MATCH_BLANK, *s); s++) + ; + for (i = 0; *s && *s != ',' && *s != ')' && + !strchr(FILE_MATCH_BLANK, *s); s++) + if (i+1 < sizeof(attset_str)) attset_str[i++] = *s; attset_str[i] = '\0'; - - if (*s == ',') + + for (; strchr(FILE_MATCH_BLANK, *s); s++) + ; + if (*s != ',') + strcpy(attname_str, attset_str); + else { - s++; - for (i = 0; *s && *s != ')'; s++) - if (i < 63) + for (s++; strchr(FILE_MATCH_BLANK, *s); s++) + ; + for (i = 0; *s && *s != ')' && + !strchr(FILE_MATCH_BLANK, *s); s++) + if (i+1 < sizeof(attname_str)) attname_str[i++] = *s; attname_str[i] = '\0'; } - - if ((attset = data1_get_attset (rGroup->dh, attset_str))) - { - data1_att *att; - attSet = attset->reference; - att = data1_getattbyname(rGroup->dh, attset, attname_str); - if (att) - attUse = att->value; - else - attUse = atoi (attname_str); - } - w = searchRecordKey (reckeys, attSet, attUse); - assert (w); - if (*s == ')') - { - for (i = 0; i<32; i++) - matchFlag[i] = 1; - } - else + searchRecordKey(zh, reckeys, attname_str, ws, 32); + + if (*s != ')') { - logf (LOG_WARN, "Missing ) in match criteria %s in group %s", - spec, rGroup->groupName ? rGroup->groupName : "none"); + yaz_log(YLOG_WARN, "Missing ) in match criteria %s in group %s", + spec, zh->m_group ? zh->m_group : "none"); return NULL; } s++; for (i = 0; i<32; i++) - if (matchFlag[i] && w[i]) + if (ws[i]) { if (first) { *dst++ = ' '; first = 0; } - strcpy (dst, w[i]); - dst += strlen(w[i]); + strcpy(dst, ws[i]); + dst += strlen(ws[i]); } if (first) { - logf (LOG_WARN, "Record didn't contain match" + yaz_log(YLOG_WARN, "Record didn't contain match" " fields in (%s,%s)", attset_str, attname_str); return NULL; } @@ -1154,30 +477,31 @@ static char *fileMatchStr (struct recKeys *reckeys, struct recordGroup *rGroup, char special[64]; const char *spec_src = NULL; const char *s1 = ++s; - while (*s1 && *s1 != ' ' && *s1 != '\t') + while (*s1 && !strchr(FILE_MATCH_BLANK, *s1)) s1++; spec_len = s1 - s; - if (spec_len > 63) - spec_len = 63; - memcpy (special, s, spec_len); + if (spec_len > sizeof(special)-1) + spec_len = sizeof(special)-1; + memcpy(special, s, spec_len); special[spec_len] = '\0'; s = s1; - if (!strcmp (special, "group")) - spec_src = rGroup->groupName; - else if (!strcmp (special, "database")) - spec_src = rGroup->databaseName; - else if (!strcmp (special, "filename")) + if (!strcmp(special, "group")) + spec_src = zh->m_group; + else if (!strcmp(special, "database")) + spec_src = zh->basenames[0]; + else if (!strcmp(special, "filename")) { spec_src = fname; - else if (!strcmp (special, "type")) - spec_src = rGroup->recordType; + } + else if (!strcmp(special, "type")) + spec_src = zh->m_record_type; else spec_src = NULL; if (spec_src) { - strcpy (dst, spec_src); - dst += strlen (spec_src); + strcpy(dst, spec_src); + dst += strlen(spec_src); } } else if (*s == '\"' || *s == '\'') @@ -1188,27 +512,27 @@ static char *fileMatchStr (struct recKeys *reckeys, struct recordGroup *rGroup, while (*s && *s != stopMarker) { - if (i < 63) + if (i+1 < sizeof(tmpString)) tmpString[i++] = *s++; } if (*s) s++; tmpString[i] = '\0'; - strcpy (dst, tmpString); - dst += strlen (tmpString); + strcpy(dst, tmpString); + dst += strlen(tmpString); } else { - logf (LOG_WARN, "Syntax error in match criteria %s in group %s", - spec, rGroup->groupName ? rGroup->groupName : "none"); + yaz_log(YLOG_WARN, "Syntax error in match criteria %s in group %s", + spec, zh->m_group ? zh->m_group : "none"); return NULL; } *dst++ = 1; } if (dst == dstBuf) { - logf (LOG_WARN, "No match criteria for record %s in group %s", - fname, rGroup->groupName ? rGroup->groupName : "none"); + yaz_log(YLOG_WARN, "No match criteria for record %s in group %s", + fname, zh->m_group ? zh->m_group : "none"); return NULL; } *dst = '\0'; @@ -1220,286 +544,654 @@ struct recordLogInfo { int recordOffset; struct recordGroup *rGroup; }; - -static void recordLogPreamble (int level, const char *msg, void *info) -{ - struct recordLogInfo *p = info; - FILE *outf = log_file (); - - if (level & LOG_LOG) - return ; - fprintf (outf, "File %s, offset %d, type %s\n", - p->rGroup->recordType, p->recordOffset, p->fname); - log_event_start (NULL, NULL); -} -void addSchema (struct recExtractCtrl *p, Odr_oid *oid) +/** \brief add the always-matches index entry and map to real record ID + \param ctrl record control + \param record_id custom record ID + \param sysno system record ID + + This function serves two purposes.. It adds the always matches + entry and makes a pointer from the custom record ID (if defined) + back to the system record ID (sysno) + See zebra_recid_to_sysno . + */ +static void all_matches_add(struct recExtractCtrl *ctrl, zint record_id, + zint sysno) { - zebraExplain_addSchema (zti, oid); + RecWord word; + extract_init(ctrl, &word); + word.record_id = record_id; + /* we use the seqno as placeholder for a way to get back to + record database from _ALLRECORDS.. This is used if a custom + RECORD was defined */ + word.seqno = sysno; + word.index_name = "_ALLRECORDS"; + word.index_type = "w"; + + extract_add_index_string(&word, zinfo_index_category_alwaysmatches, + "", 0); } -static int recordExtract (SYSNO *sysno, const char *fname, - struct recordGroup *rGroup, int deleteFlag, - struct file_read_info *fi, - RecType recType, char *subType, void *clientData) +ZEBRA_RES zebra_extract_records_stream(ZebraHandle zh, + struct ZebraRecStream *stream, + enum zebra_recctrl_action_t action, + int test_mode, + const char *recordType, + zint *sysno, + const char *match_criteria, + const char *fname, + RecType recType, + void *recTypeClientData); + + +ZEBRA_RES zebra_extract_file(ZebraHandle zh, zint *sysno, const char *fname, + enum zebra_recctrl_action_t action) { - RecordAttr *recordAttr; - int r; - char *matchStr; - SYSNO sysnotmp; - Record rec; - struct recordLogInfo logInfo; - off_t recordOffset = 0; + ZEBRA_RES r = ZEBRA_OK; + int i, fd; + char gprefix[128]; + char ext[128]; + char ext_res[128]; + struct file_read_info *fi = 0; + const char *original_record_type = 0; + RecType recType; + void *recTypeClientData; + struct ZebraRecStream stream, *streamp; - if (fi->fd != -1) - { - struct recExtractCtrl extractCtrl; + zebra_init_log_level(); - /* we are going to read from a file, so prepare the extraction */ - int i; + if (!zh->m_group || !*zh->m_group) + *gprefix = '\0'; + else + sprintf(gprefix, "%s.", zh->m_group); + + yaz_log(log_level_extract, "zebra_extract_file %s", fname); - reckeys.buf_used = 0; - reckeys.prevAttrUse = -1; - reckeys.prevAttrSet = -1; - reckeys.prevSeqNo = 0; - - recordOffset = fi->file_moffset; - extractCtrl.offset = fi->file_moffset; - extractCtrl.readf = file_read; - extractCtrl.seekf = file_seek; - extractCtrl.tellf = file_tell; - extractCtrl.endf = file_end; - extractCtrl.fh = fi; - extractCtrl.subType = subType; - extractCtrl.init = wordInit; - extractCtrl.addWord = addRecordKey; - extractCtrl.addSchema = addSchema; - extractCtrl.dh = rGroup->dh; - for (i = 0; i<256; i++) - { - if (zebra_maps_is_positioned(rGroup->zebra_maps, i)) - extractCtrl.seqno[i] = 1; - else - extractCtrl.seqno[i] = 0; - } - extractCtrl.zebra_maps = rGroup->zebra_maps; - extractCtrl.flagShowRecords = !rGroup->flagRw; + /* determine file extension */ + *ext = '\0'; + for (i = strlen(fname); --i >= 0; ) + if (fname[i] == '/') + break; + else if (fname[i] == '.') + { + strcpy(ext, fname+i+1); + break; + } + /* determine file type - depending on extension */ + original_record_type = zh->m_record_type; + if (!zh->m_record_type) + { + sprintf(ext_res, "%srecordType.%s", gprefix, ext); + zh->m_record_type = res_get(zh->res, ext_res); + } + if (!zh->m_record_type) + { + check_log_limit(zh); + if (zh->records_processed + zh->records_skipped + < zh->m_file_verbose_limit) + yaz_log(YLOG_LOG, "? %s", fname); + zh->records_skipped++; + return 0; + } + /* determine match criteria */ + if (!zh->m_record_id) + { + sprintf(ext_res, "%srecordId.%s", gprefix, ext); + zh->m_record_id = res_get(zh->res, ext_res); + } - if (!rGroup->flagRw) - printf ("File: %s %ld\n", fname, (long) recordOffset); + if (!(recType = + recType_byName(zh->reg->recTypes, zh->res, zh->m_record_type, + &recTypeClientData))) + { + yaz_log(YLOG_WARN, "No such record type: %s", zh->m_record_type); + return ZEBRA_FAIL; + } - logInfo.fname = fname; - logInfo.recordOffset = recordOffset; - logInfo.rGroup = rGroup; - log_event_start (recordLogPreamble, &logInfo); + switch(recType->version) + { + case 0: + break; + default: + yaz_log(YLOG_WARN, "Bad filter version: %s", zh->m_record_type); + } + if (sysno && (action == action_delete || action == action_a_delete)) + { + streamp = 0; + fi = 0; + } + else + { + char full_rep[1024]; - r = (*recType->extract)(clientData, &extractCtrl); + if (zh->path_reg && !yaz_is_abspath(fname)) + { + strcpy(full_rep, zh->path_reg); + strcat(full_rep, "/"); + strcat(full_rep, fname); + } + else + strcpy(full_rep, fname); + + if ((fd = open(full_rep, O_BINARY|O_RDONLY)) == -1) + { + yaz_log(YLOG_WARN|YLOG_ERRNO, "open %s", full_rep); + zh->m_record_type = original_record_type; + return ZEBRA_FAIL; + } + streamp = &stream; + zebra_create_stream_fd(streamp, fd, 0); + } + r = zebra_extract_records_stream(zh, streamp, + action, + 0, /* tst_mode */ + zh->m_record_type, + sysno, + 0, /*match_criteria */ + fname, + recType, recTypeClientData); + if (streamp) + stream.destroy(streamp); + zh->m_record_type = original_record_type; + return r; +} - log_event_start (NULL, NULL); +/* + If sysno is provided, then it's used to identify the reocord. + If not, and match_criteria is provided, then sysno is guessed + If not, and a record is provided, then sysno is got from there + + */ - if (r) - { - /* error occured during extraction ... */ - if (rGroup->flagRw && - records_processed < rGroup->fileVerboseLimit) - { - logf (LOG_WARN, "fail %s %s %ld code = %d", rGroup->recordType, - fname, (long) recordOffset, r); - } - return 0; +ZEBRA_RES zebra_buffer_extract_record(ZebraHandle zh, + const char *buf, size_t buf_size, + enum zebra_recctrl_action_t action, + int test_mode, + const char *recordType, + zint *sysno, + const char *match_criteria, + const char *fname) +{ + struct ZebraRecStream stream; + ZEBRA_RES res; + void *clientData; + RecType recType = 0; + + if (recordType && *recordType) + { + yaz_log(log_level_extract, + "Record type explicitly specified: %s", recordType); + recType = recType_byName(zh->reg->recTypes, zh->res, recordType, + &clientData); + } + else + { + if (!(zh->m_record_type)) + { + yaz_log(YLOG_WARN, "No such record type defined"); + return ZEBRA_FAIL; } - if (reckeys.buf_used == 0) + yaz_log(log_level_extract, "Get record type from rgroup: %s", + zh->m_record_type); + recType = recType_byName(zh->reg->recTypes, zh->res, + zh->m_record_type, &clientData); + recordType = zh->m_record_type; + } + + if (!recType) + { + yaz_log(YLOG_WARN, "No such record type: %s", recordType); + return ZEBRA_FAIL; + } + + zebra_create_stream_mem(&stream, buf, buf_size); + + res = zebra_extract_records_stream(zh, &stream, + action, + test_mode, + recordType, + sysno, + match_criteria, + fname, + recType, clientData); + stream.destroy(&stream); + return res; +} + +ZEBRA_RES zebra_extract_records_stream(ZebraHandle zh, + struct ZebraRecStream *stream, + enum zebra_recctrl_action_t action, + int test_mode, + const char *recordType, + zint *sysno, + const char *match_criteria, + const char *fname, + RecType recType, + void *recTypeClientData) +{ + ZEBRA_RES res = ZEBRA_OK; + while (1) + { + int more = 0; + res = zebra_extract_record_stream(zh, stream, + action, + test_mode, + recordType, + sysno, + match_criteria, + fname, + recType, recTypeClientData, &more); + if (!more) { - /* the extraction process returned no information - the record - is probably empty - unless flagShowRecords is in use */ - if (!rGroup->flagRw) - return 1; - logf (LOG_WARN, "No keys generated for file %s", fname); - logf (LOG_WARN, " The file is probably empty"); - return 1; + res = ZEBRA_OK; + break; } + if (res != ZEBRA_OK) + break; + if (sysno) + break; } + return res; +} + - /* perform match if sysno not known and if match criteria is specified */ - - matchStr = NULL; - if (!sysno) +static WRBUF wrbuf_hex_str(const char *cstr) +{ + size_t i; + WRBUF w = wrbuf_alloc(); + for (i = 0; cstr[i]; i++) { - sysnotmp = 0; - sysno = &sysnotmp; - if (rGroup->recordId && *rGroup->recordId) + if (cstr[i] < ' ' || cstr[i] > 126) + wrbuf_printf(w, "\\%02X", cstr[i] & 0xff); + else + wrbuf_putc(w, cstr[i]); + } + return w; +} + +ZEBRA_RES zebra_extract_record_stream(ZebraHandle zh, + struct ZebraRecStream *stream, + enum zebra_recctrl_action_t action, + int test_mode, + const char *recordType, + zint *sysno, + const char *match_criteria, + const char *fname, + RecType recType, + void *recTypeClientData, + int *more) + +{ + zint sysno0 = 0; + RecordAttr *recordAttr; + struct recExtractCtrl extractCtrl; + int r; + const char *matchStr = 0; + Record rec; + off_t start_offset = 0, end_offset = 0; + const char *pr_fname = fname; /* filename to print .. */ + int show_progress = zh->records_processed + zh->records_skipped + < zh->m_file_verbose_limit ? 1:0; + + zebra_init_log_level(); + + if (!pr_fname) + pr_fname = ""; /* make it printable if file is omitted */ + + zebra_rec_keys_reset(zh->reg->keys); + zebra_rec_keys_reset(zh->reg->sortKeys); + + if (zebraExplain_curDatabase(zh->reg->zei, zh->basenames[0])) + { + if (zebraExplain_newDatabase(zh->reg->zei, zh->basenames[0], + zh->m_explain_database)) + return ZEBRA_FAIL; + } + + if (stream) + { + off_t null_offset = 0; + extractCtrl.stream = stream; + + start_offset = stream->tellf(stream); + + extractCtrl.first_record = start_offset ? 0 : 1; + + stream->endf(stream, &null_offset);; + + extractCtrl.init = extract_init; + extractCtrl.tokenAdd = extract_token_add; + extractCtrl.schemaAdd = extract_schema_add; + extractCtrl.dh = zh->reg->dh; + extractCtrl.handle = zh; + extractCtrl.match_criteria[0] = '\0'; + extractCtrl.staticrank = 0; + extractCtrl.action = action; + + init_extractCtrl(zh, &extractCtrl); + + extract_set_store_data_prepare(&extractCtrl); + + r = (*recType->extract)(recTypeClientData, &extractCtrl); + + if (action == action_update) { - char *rinfo; + action = extractCtrl.action; + } - matchStr = fileMatchStr (&reckeys, rGroup, fname, - rGroup->recordId); - if (matchStr) - { - rinfo = dict_lookup (matchDict, matchStr); - if (rinfo) - memcpy (sysno, rinfo+1, sizeof(*sysno)); + switch (r) + { + case RECCTRL_EXTRACT_EOF: + return ZEBRA_FAIL; + case RECCTRL_EXTRACT_ERROR_GENERIC: + /* error occured during extraction ... */ + yaz_log(YLOG_WARN, "extract error: generic"); + return ZEBRA_FAIL; + case RECCTRL_EXTRACT_ERROR_NO_SUCH_FILTER: + /* error occured during extraction ... */ + yaz_log(YLOG_WARN, "extract error: no such filter"); + return ZEBRA_FAIL; + case RECCTRL_EXTRACT_SKIP: + if (show_progress) + yaz_log(YLOG_LOG, "skip %s %s " ZINT_FORMAT, + recordType, pr_fname, (zint) start_offset); + *more = 1; + + end_offset = stream->endf(stream, 0); + if (end_offset) + stream->seekf(stream, end_offset); + + return ZEBRA_OK; + case RECCTRL_EXTRACT_OK: + break; + default: + yaz_log(YLOG_WARN, "extract error: unknown error: %d", r); + return ZEBRA_FAIL; + } + end_offset = stream->endf(stream, 0); + if (end_offset) + stream->seekf(stream, end_offset); + else + end_offset = stream->tellf(stream); + + if (extractCtrl.match_criteria[0]) + match_criteria = extractCtrl.match_criteria; + } + + *more = 1; + if (!sysno) + { + sysno = &sysno0; + + if (match_criteria && *match_criteria) { + matchStr = match_criteria; + } else { + if (zh->m_record_id && *zh->m_record_id) { + matchStr = get_match_from_spec(zh, zh->reg->keys, pr_fname, + zh->m_record_id); + if (!matchStr) + { + yaz_log(YLOG_LOG, "error %s %s " ZINT_FORMAT, recordType, + pr_fname, (zint) start_offset); + return ZEBRA_FAIL; + } } - else + } + if (matchStr) + { + int db_ord = zebraExplain_get_database_ord(zh->reg->zei); + char *rinfo = dict_lookup_ord(zh->reg->matchDict, db_ord, + matchStr); + + + if (log_level_extract) { - logf (LOG_WARN, "Bad match criteria"); - return 0; + WRBUF w = wrbuf_hex_str(matchStr); + yaz_log(log_level_extract, "matchStr: %s", wrbuf_cstr(w)); + wrbuf_destroy(w); } - } + if (rinfo) + { + assert(*rinfo == sizeof(*sysno)); + memcpy(sysno, rinfo+1, sizeof(*sysno)); + } + } + } + + if (zebra_rec_keys_empty(zh->reg->keys)) + { + /* the extraction process returned no information - the record + is probably empty - unless flagShowRecords is in use */ + if (test_mode) + return ZEBRA_OK; } if (! *sysno) { - /* new record */ - if (deleteFlag) + /* new record AKA does not exist already */ + if (action == action_delete) { - logf (LOG_LOG, "delete %s %s %ld", rGroup->recordType, - fname, (long) recordOffset); - logf (LOG_WARN, "cannot delete record above (seems new)"); - return 1; + yaz_log(YLOG_LOG, "delete %s %s " ZINT_FORMAT, recordType, + pr_fname, (zint) start_offset); + yaz_log(YLOG_WARN, "cannot delete record above (seems new)"); + return ZEBRA_FAIL; } - if (records_processed < rGroup->fileVerboseLimit) - logf (LOG_LOG, "add %s %s %ld", rGroup->recordType, - fname, (long) recordOffset); - rec = rec_new (records); + else if (action == action_a_delete) + { + if (show_progress) + yaz_log(YLOG_LOG, "delete %s %s " ZINT_FORMAT, recordType, + pr_fname, (zint) start_offset); + return ZEBRA_OK; + } + else if (action == action_replace) + { + yaz_log(YLOG_LOG, "update %s %s " ZINT_FORMAT, recordType, + pr_fname, (zint) start_offset); + yaz_log(YLOG_WARN, "cannot update record above (seems new)"); + return ZEBRA_FAIL; + } + if (show_progress) + yaz_log(YLOG_LOG, "add %s %s " ZINT_FORMAT, recordType, pr_fname, + (zint) start_offset); + rec = rec_new(zh->reg->records); *sysno = rec->sysno; - recordAttr = rec_init_attr (zti, rec); + + if (stream) + { + all_matches_add(&extractCtrl, + zebra_rec_keys_get_custom_record_id(zh->reg->keys), + *sysno); + } + + + recordAttr = rec_init_attr(zh->reg->zei, rec); + if (extractCtrl.staticrank < 0) + { + yaz_log(YLOG_WARN, "Negative staticrank for record. Set to 0"); + extractCtrl.staticrank = 0; + } if (matchStr) { - dict_insert (matchDict, matchStr, sizeof(*sysno), sysno); + int db_ord = zebraExplain_get_database_ord(zh->reg->zei); + dict_insert_ord(zh->reg->matchDict, db_ord, matchStr, + sizeof(*sysno), sysno); } - flushRecordKeys (*sysno, 1, &reckeys); - flushSortKeys (*sysno, 1); - records_inserted++; - } + extract_flush_sort_keys(zh, *sysno, 1, zh->reg->sortKeys); +#if FLUSH2 + extract_flush_record_keys2(zh, *sysno, + zh->reg->keys, extractCtrl.staticrank, + 0, recordAttr->staticrank); +#else + extract_flush_record_keys(zh, *sysno, 1, zh->reg->keys, + extractCtrl.staticrank); +#endif + recordAttr->staticrank = extractCtrl.staticrank; + zh->records_inserted++; + } else { /* record already exists */ - struct recKeys delkeys; - - rec = rec_get (records, *sysno); - assert (rec); - - recordAttr = rec_init_attr (zti, rec); - - if (recordAttr->runNumber == zebraExplain_runNumberIncrement (zti, 0)) + zebra_rec_keys_t delkeys = zebra_rec_keys_open(); + zebra_rec_keys_t sortKeys = zebra_rec_keys_open(); + if (action == action_insert) { - logf (LOG_LOG, "skipped %s %s %ld", rGroup->recordType, - fname, (long) recordOffset); - rec_rm (&rec); - logRecord (0); - return 1; + yaz_log(YLOG_LOG, "skipped %s %s " ZINT_FORMAT, + recordType, pr_fname, (zint) start_offset); + logRecord(zh); + return ZEBRA_FAIL; } - delkeys.buf_used = rec->size[recInfo_delKeys]; - delkeys.buf = rec->info[recInfo_delKeys]; - flushSortKeys (*sysno, 0); - flushRecordKeys (*sysno, 0, &delkeys); - if (deleteFlag) + + rec = rec_get(zh->reg->records, *sysno); + assert(rec); + + if (stream) + { + all_matches_add(&extractCtrl, + zebra_rec_keys_get_custom_record_id(zh->reg->keys), + *sysno); + } + + recordAttr = rec_init_attr(zh->reg->zei, rec); + + /* decrease total size */ + zebraExplain_recordBytesIncrement(zh->reg->zei, + - recordAttr->recordSize); + + zebra_rec_keys_set_buf(delkeys, + rec->info[recInfo_delKeys], + rec->size[recInfo_delKeys], + 0); + zebra_rec_keys_set_buf(sortKeys, + rec->info[recInfo_sortKeys], + rec->size[recInfo_sortKeys], + 0); + + extract_flush_sort_keys(zh, *sysno, 0, sortKeys); +#if !FLUSH2 + extract_flush_record_keys(zh, *sysno, 0, delkeys, + recordAttr->staticrank); +#endif + if (action == action_delete || action == action_a_delete) { /* record going to be deleted */ - if (!delkeys.buf_used) +#if FLUSH2 + extract_flush_record_keys2(zh, *sysno, 0, recordAttr->staticrank, + delkeys, recordAttr->staticrank); +#endif + if (zebra_rec_keys_empty(delkeys)) { - logf (LOG_LOG, "delete %s %s %ld", rGroup->recordType, - fname, (long) recordOffset); - logf (LOG_WARN, "cannot delete file above, storeKeys false"); - } + yaz_log(YLOG_LOG, "delete %s %s " ZINT_FORMAT, recordType, + pr_fname, (zint) start_offset); + yaz_log(YLOG_WARN, "cannot delete file above, " + "storeKeys false (3)"); + } else { - if (records_processed < rGroup->fileVerboseLimit) - logf (LOG_LOG, "delete %s %s %ld", rGroup->recordType, - fname, (long) recordOffset); - records_deleted++; + if (show_progress) + yaz_log(YLOG_LOG, "delete %s %s " ZINT_FORMAT, recordType, + pr_fname, (zint) start_offset); + zh->records_deleted++; if (matchStr) - dict_delete (matchDict, matchStr); - rec_del (records, &rec); + { + int db_ord = zebraExplain_get_database_ord(zh->reg->zei); + dict_delete_ord(zh->reg->matchDict, db_ord, matchStr); + } + rec_del(zh->reg->records, &rec); } - rec_rm (&rec); - logRecord (0); - return 1; + zebra_rec_keys_close(delkeys); + zebra_rec_keys_close(sortKeys); + rec_free(&rec); + logRecord(zh); + return ZEBRA_OK; } else - { - /* record going to be updated */ - if (!delkeys.buf_used) - { - logf (LOG_LOG, "update %s %s %ld", rGroup->recordType, - fname, (long) recordOffset); - logf (LOG_WARN, "cannot update file above, storeKeys false"); - } - else - { - if (records_processed < rGroup->fileVerboseLimit) - logf (LOG_LOG, "update %s %s %ld", rGroup->recordType, - fname, (long) recordOffset); - flushRecordKeys (*sysno, 1, &reckeys); - records_updated++; - } + { /* update or special_update */ + if (show_progress) + yaz_log(YLOG_LOG, "update %s %s " ZINT_FORMAT, recordType, + pr_fname, (zint) start_offset); + extract_flush_sort_keys(zh, *sysno, 1, zh->reg->sortKeys); + +#if FLUSH2 + extract_flush_record_keys2(zh, *sysno, + zh->reg->keys, extractCtrl.staticrank, + delkeys, recordAttr->staticrank); +#else + extract_flush_record_keys(zh, *sysno, 1, + zh->reg->keys, extractCtrl.staticrank); +#endif + recordAttr->staticrank = extractCtrl.staticrank; + zh->records_updated++; } + zebra_rec_keys_close(delkeys); + zebra_rec_keys_close(sortKeys); } /* update file type */ - xfree (rec->info[recInfo_fileType]); + xfree(rec->info[recInfo_fileType]); rec->info[recInfo_fileType] = - rec_strdup (rGroup->recordType, &rec->size[recInfo_fileType]); + rec_strdup(recordType, &rec->size[recInfo_fileType]); /* update filename */ - xfree (rec->info[recInfo_filename]); + xfree(rec->info[recInfo_filename]); rec->info[recInfo_filename] = - rec_strdup (fname, &rec->size[recInfo_filename]); + rec_strdup(fname, &rec->size[recInfo_filename]); /* update delete keys */ - xfree (rec->info[recInfo_delKeys]); - if (reckeys.buf_used > 0 && rGroup->flagStoreKeys == 1) + xfree(rec->info[recInfo_delKeys]); + if (!zebra_rec_keys_empty(zh->reg->keys) && zh->m_store_keys == 1) { -#if 1 - rec->size[recInfo_delKeys] = reckeys.buf_used; - rec->info[recInfo_delKeys] = reckeys.buf; - reckeys.buf = NULL; - reckeys.buf_max = 0; -#else - rec->info[recInfo_delKeys] = xmalloc (reckeys.buf_used); - rec->size[recInfo_delKeys] = reckeys.buf_used; - memcpy (rec->info[recInfo_delKeys], reckeys.buf, - rec->size[recInfo_delKeys]); -#endif + zebra_rec_keys_get_buf(zh->reg->keys, + &rec->info[recInfo_delKeys], + &rec->size[recInfo_delKeys]); } else { rec->info[recInfo_delKeys] = NULL; rec->size[recInfo_delKeys] = 0; } + /* update sort keys */ + xfree(rec->info[recInfo_sortKeys]); + + zebra_rec_keys_get_buf(zh->reg->sortKeys, + &rec->info[recInfo_sortKeys], + &rec->size[recInfo_sortKeys]); - /* save file size of original record */ - zebraExplain_recordBytesIncrement (zti, - recordAttr->recordSize); - recordAttr->recordSize = fi->file_moffset - recordOffset; - if (!recordAttr->recordSize) - recordAttr->recordSize = fi->file_max - recordOffset; - zebraExplain_recordBytesIncrement (zti, recordAttr->recordSize); + if (stream) + { + recordAttr->recordSize = end_offset - start_offset; + zebraExplain_recordBytesIncrement(zh->reg->zei, + recordAttr->recordSize); + } /* set run-number for this record */ - recordAttr->runNumber = zebraExplain_runNumberIncrement (zti, 0); + recordAttr->runNumber = + zebraExplain_runNumberIncrement(zh->reg->zei, 0); /* update store data */ - xfree (rec->info[recInfo_storeData]); - if (rGroup->flagStoreData == 1) + xfree(rec->info[recInfo_storeData]); + + /* update store data */ + if (zh->store_data_buf) { + rec->size[recInfo_storeData] = zh->store_data_size; + rec->info[recInfo_storeData] = zh->store_data_buf; + zh->store_data_buf = 0; + recordAttr->recordSize = zh->store_data_size; + } + else if (zh->m_store_data) + { + off_t cur_offset = stream->tellf(stream); + rec->size[recInfo_storeData] = recordAttr->recordSize; - rec->info[recInfo_storeData] = xmalloc (recordAttr->recordSize); - if (lseek (fi->fd, recordOffset, SEEK_SET) < 0) - { - logf (LOG_ERRNO|LOG_FATAL, "seek to %ld in %s", - (long) recordOffset, fname); - exit (1); - } - if (read (fi->fd, rec->info[recInfo_storeData], recordAttr->recordSize) - < recordAttr->recordSize) - { - logf (LOG_ERRNO|LOG_FATAL, "read %d bytes of %s", - recordAttr->recordSize, fname); - exit (1); - } + rec->info[recInfo_storeData] = (char *) + xmalloc(recordAttr->recordSize); + stream->seekf(stream, start_offset); + stream->readf(stream, rec->info[recInfo_storeData], + recordAttr->recordSize); + stream->seekf(stream, cur_offset); } else { @@ -1507,266 +1199,688 @@ static int recordExtract (SYSNO *sysno, const char *fname, rec->size[recInfo_storeData] = 0; } /* update database name */ - xfree (rec->info[recInfo_databaseName]); + xfree(rec->info[recInfo_databaseName]); rec->info[recInfo_databaseName] = - rec_strdup (rGroup->databaseName, &rec->size[recInfo_databaseName]); + rec_strdup(zh->basenames[0], &rec->size[recInfo_databaseName]); /* update offset */ - recordAttr->recordOffset = recordOffset; + recordAttr->recordOffset = start_offset; /* commit this record */ - rec_put (records, &rec); - logRecord (0); - return 1; + rec_put(zh->reg->records, &rec); + logRecord(zh); + return ZEBRA_OK; } -int fileExtract (SYSNO *sysno, const char *fname, - const struct recordGroup *rGroupP, int deleteFlag) +ZEBRA_RES zebra_extract_explain(void *handle, Record rec, data1_node *n) { - int r, i, fd; - char gprefix[128]; - char ext[128]; - char ext_res[128]; - char subType[128]; - RecType recType; - struct recordGroup rGroupM; - struct recordGroup *rGroup = &rGroupM; - struct file_read_info *fi; - void *clientData; + ZebraHandle zh = (ZebraHandle) handle; + struct recExtractCtrl extractCtrl; - memcpy (rGroup, rGroupP, sizeof(*rGroupP)); - - if (!rGroup->groupName || !*rGroup->groupName) - *gprefix = '\0'; + if (zebraExplain_curDatabase(zh->reg->zei, + rec->info[recInfo_databaseName])) + { + abort(); + if (zebraExplain_newDatabase(zh->reg->zei, + rec->info[recInfo_databaseName], 0)) + abort(); + } + + zebra_rec_keys_reset(zh->reg->keys); + zebra_rec_keys_reset(zh->reg->sortKeys); + + extractCtrl.init = extract_init; + extractCtrl.tokenAdd = extract_token_add; + extractCtrl.schemaAdd = extract_schema_add; + extractCtrl.dh = zh->reg->dh; + + init_extractCtrl(zh, &extractCtrl); + + extractCtrl.flagShowRecords = 0; + extractCtrl.match_criteria[0] = '\0'; + extractCtrl.staticrank = 0; + extractCtrl.action = action_update; + + extractCtrl.handle = handle; + extractCtrl.first_record = 1; + + extract_set_store_data_prepare(&extractCtrl); + + if (n) + grs_extract_tree(&extractCtrl, n); + + if (rec->size[recInfo_delKeys]) + { + zebra_rec_keys_t delkeys = zebra_rec_keys_open(); + + zebra_rec_keys_t sortkeys = zebra_rec_keys_open(); + + zebra_rec_keys_set_buf(delkeys, rec->info[recInfo_delKeys], + rec->size[recInfo_delKeys], + 0); +#if FLUSH2 + extract_flush_record_keys2(zh, rec->sysno, + zh->reg->keys, 0, delkeys, 0); +#else + extract_flush_record_keys(zh, rec->sysno, 0, delkeys, 0); + extract_flush_record_keys(zh, rec->sysno, 1, zh->reg->keys, 0); +#endif + zebra_rec_keys_close(delkeys); + + zebra_rec_keys_set_buf(sortkeys, rec->info[recInfo_sortKeys], + rec->size[recInfo_sortKeys], + 0); + + extract_flush_sort_keys(zh, rec->sysno, 0, sortkeys); + zebra_rec_keys_close(sortkeys); + } else - sprintf (gprefix, "%s.", rGroup->groupName); + { +#if FLUSH2 + extract_flush_record_keys2(zh, rec->sysno, zh->reg->keys, 0, 0, 0); +#else + extract_flush_record_keys(zh, rec->sysno, 1, zh->reg->keys, 0); +#endif + } + extract_flush_sort_keys(zh, rec->sysno, 1, zh->reg->sortKeys); + + xfree(rec->info[recInfo_delKeys]); + zebra_rec_keys_get_buf(zh->reg->keys, + &rec->info[recInfo_delKeys], + &rec->size[recInfo_delKeys]); + + xfree(rec->info[recInfo_sortKeys]); + zebra_rec_keys_get_buf(zh->reg->sortKeys, + &rec->info[recInfo_sortKeys], + &rec->size[recInfo_sortKeys]); + return ZEBRA_OK; +} - logf (LOG_DEBUG, "fileExtract %s", fname); +void extract_rec_keys_log(ZebraHandle zh, int is_insert, + zebra_rec_keys_t reckeys, + int level) +{ + if (zebra_rec_keys_rewind(reckeys)) + { + size_t slen; + const char *str; + struct it_key key; + NMEM nmem = nmem_create(); - /* determine file extension */ - *ext = '\0'; - for (i = strlen(fname); --i >= 0; ) - if (fname[i] == '/') - break; - else if (fname[i] == '.') + while(zebra_rec_keys_read(reckeys, &str, &slen, &key)) { - strcpy (ext, fname+i+1); - break; + char keystr[200]; /* room for zints to print */ + char *dst_term = 0; + int ord = CAST_ZINT_TO_INT(key.mem[0]); + const char *index_type; + int i; + const char *string_index; + + zebraExplain_lookup_ord(zh->reg->zei, ord, &index_type, + 0/* db */, &string_index); + assert(index_type); + zebra_term_untrans_iconv(zh, nmem, index_type, + &dst_term, str); + *keystr = '\0'; + for (i = 0; irecordType) + nmem_destroy(nmem); + } +} + +void extract_rec_keys_adjust(ZebraHandle zh, int is_insert, + zebra_rec_keys_t reckeys) +{ + ZebraExplainInfo zei = zh->reg->zei; + struct ord_stat { + int no; + int ord; + struct ord_stat *next; + }; + + if (zebra_rec_keys_rewind(reckeys)) { - sprintf (ext_res, "%srecordType.%s", gprefix, ext); - if (!(rGroup->recordType = res_get (common_resource, ext_res))) + struct ord_stat *ord_list = 0; + struct ord_stat *p; + size_t slen; + const char *str; + struct it_key key_in; + while(zebra_rec_keys_read(reckeys, &str, &slen, &key_in)) { - sprintf (ext_res, "%srecordType", gprefix); - rGroup->recordType = res_get (common_resource, ext_res); + int ord = CAST_ZINT_TO_INT(key_in.mem[0]); + + for (p = ord_list; p ; p = p->next) + if (p->ord == ord) + { + p->no++; + break; + } + if (!p) + { + p = xmalloc(sizeof(*p)); + p->no = 1; + p->ord = ord; + p->next = ord_list; + ord_list = p; + } + } + + p = ord_list; + while (p) + { + struct ord_stat *p1 = p; + + if (is_insert) + zebraExplain_ord_adjust_occurrences(zei, p->ord, p->no, 1); + else + zebraExplain_ord_adjust_occurrences(zei, p->ord, - p->no, -1); + p = p->next; + xfree(p1); } } - if (!rGroup->recordType) +} + +void extract_flush_record_keys2(ZebraHandle zh, zint sysno, + zebra_rec_keys_t ins_keys, zint ins_rank, + zebra_rec_keys_t del_keys, zint del_rank) +{ + ZebraExplainInfo zei = zh->reg->zei; + int normal = 0; + int optimized = 0; + + if (!zh->reg->key_block) { - if (records_processed < rGroup->fileVerboseLimit) - logf (LOG_LOG, "? %s", fname); - return 0; + int mem = 1024*1024 * atoi( res_get_def( zh->res, "memmax", "8")); + const char *key_tmp_dir = res_get_def(zh->res, "keyTmpDir", "."); + int use_threads = atoi(res_get_def(zh->res, "threads", "1")); + zh->reg->key_block = key_block_create(mem, key_tmp_dir, use_threads); } - if (!*rGroup->recordType) - return 0; - if (!(recType = - recType_byName (rGroup->recTypes, rGroup->recordType, subType, - &clientData))) + + if (ins_keys) { - logf (LOG_WARN, "No such record type: %s", rGroup->recordType); - return 0; + extract_rec_keys_adjust(zh, 1, ins_keys); + if (!del_keys) + zebraExplain_recordCountIncrement(zei, 1); + zebra_rec_keys_rewind(ins_keys); } - - /* determine match criteria */ - if (!rGroup->recordId) + if (del_keys) { - sprintf (ext_res, "%srecordId.%s", gprefix, ext); - rGroup->recordId = res_get (common_resource, ext_res); + extract_rec_keys_adjust(zh, 0, del_keys); + if (!ins_keys) + zebraExplain_recordCountIncrement(zei, -1); + zebra_rec_keys_rewind(del_keys); } - /* determine database name */ - if (!rGroup->databaseName) + while (1) { - sprintf (ext_res, "%sdatabase.%s", gprefix, ext); - if (!(rGroup->databaseName = res_get (common_resource, ext_res))) + size_t del_slen; + const char *del_str; + struct it_key del_key_in; + int del = 0; + + size_t ins_slen; + const char *ins_str; + struct it_key ins_key_in; + int ins = 0; + + if (del_keys) + del = zebra_rec_keys_read(del_keys, &del_str, &del_slen, + &del_key_in); + if (ins_keys) + ins = zebra_rec_keys_read(ins_keys, &ins_str, &ins_slen, + &ins_key_in); + + if (del && ins && ins_rank == del_rank + && !key_compare(&del_key_in, &ins_key_in) + && ins_slen == del_slen && !memcmp(del_str, ins_str, del_slen)) { - sprintf (ext_res, "%sdatabase", gprefix); - rGroup->databaseName = res_get (common_resource, ext_res); + optimized++; + continue; } + if (!del && !ins) + break; + + normal++; + if (del) + key_block_write(zh->reg->key_block, sysno, + &del_key_in, 0, del_str, del_slen, + del_rank, zh->m_staticrank); + if (ins) + key_block_write(zh->reg->key_block, sysno, + &ins_key_in, 1, ins_str, ins_slen, + ins_rank, zh->m_staticrank); } - if (!rGroup->databaseName) - rGroup->databaseName = "Default"; + yaz_log(log_level_extract, "normal=%d optimized=%d", normal, optimized); +} - /* determine if explain database */ - - sprintf (ext_res, "%sexplainDatabase", gprefix); - rGroup->explainDatabase = - atoi (res_get_def (common_resource, ext_res, "0")); - /* announce database */ - if (zebraExplain_curDatabase (zti, rGroup->databaseName)) +ZEBRA_RES zebra_rec_keys_to_snippets1(ZebraHandle zh, + zebra_rec_keys_t reckeys, + zebra_snippets *snippets) +{ + NMEM nmem = nmem_create(); + if (zebra_rec_keys_rewind(reckeys)) { - if (zebraExplain_newDatabase (zti, rGroup->databaseName, - rGroup->explainDatabase)) - abort (); + const char *str; + size_t slen; + struct it_key key; + while (zebra_rec_keys_read(reckeys, &str, &slen, &key)) + { + char *dst_term = 0; + int ord; + zint seqno; + const char *index_type; + + assert(key.len <= IT_KEY_LEVEL_MAX && key.len > 2); + seqno = key.mem[key.len-1]; + ord = CAST_ZINT_TO_INT(key.mem[0]); + + zebraExplain_lookup_ord(zh->reg->zei, ord, &index_type, + 0/* db */, 0 /* string_index */); + assert(index_type); + zebra_term_untrans_iconv(zh, nmem, index_type, + &dst_term, str); + zebra_snippets_append(snippets, seqno, 0, ord, dst_term); + nmem_reset(nmem); + } } + nmem_destroy(nmem); + return ZEBRA_OK; +} - if (rGroup->flagStoreData == -1) +void print_rec_keys(ZebraHandle zh, zebra_rec_keys_t reckeys) +{ + yaz_log(YLOG_LOG, "print_rec_keys"); + if (zebra_rec_keys_rewind(reckeys)) { - const char *sval; - sprintf (ext_res, "%sstoreData.%s", gprefix, ext); - if (!(sval = res_get (common_resource, ext_res))) - { - sprintf (ext_res, "%sstoreData", gprefix); - sval = res_get (common_resource, ext_res); - } - if (sval) - rGroup->flagStoreData = atoi (sval); + const char *str; + size_t slen; + struct it_key key; + while (zebra_rec_keys_read(reckeys, &str, &slen, &key)) + { + char dst_buf[IT_MAX_WORD]; + zint seqno; + const char *index_type; + int ord = CAST_ZINT_TO_INT(key.mem[0]); + const char *db = 0; + assert(key.len <= IT_KEY_LEVEL_MAX && key.len > 2); + + zebraExplain_lookup_ord(zh->reg->zei, ord, &index_type, &db, 0); + + seqno = key.mem[key.len-1]; + + zebra_term_untrans(zh, index_type, dst_buf, str); + + yaz_log(YLOG_LOG, "ord=%d seqno=" ZINT_FORMAT + " term=%s", ord, seqno, dst_buf); + } } - if (rGroup->flagStoreData == -1) - rGroup->flagStoreData = 0; +} - if (rGroup->flagStoreKeys == -1) - { - const char *sval; +static void extract_add_index_string(RecWord *p, zinfo_index_category_t cat, + const char *str, int length) +{ + struct it_key key; + ZebraHandle zh = p->extractCtrl->handle; + ZebraExplainInfo zei = zh->reg->zei; + int ch, i; + + ch = zebraExplain_lookup_attr_str(zei, cat, p->index_type, p->index_name); + if (ch < 0) + ch = zebraExplain_add_attr_str(zei, cat, p->index_type, p->index_name); + + i = 0; + key.mem[i++] = ch; + key.mem[i++] = p->record_id; + key.mem[i++] = p->section_id; + + if (zh->m_segment_indexing) + key.mem[i++] = p->segment; + key.mem[i++] = p->seqno; + key.len = i; + + zebra_rec_keys_write(zh->reg->keys, str, length, &key); +} + +static void extract_add_sort_string(RecWord *p, const char *str, int length) +{ + struct it_key key; + ZebraHandle zh = p->extractCtrl->handle; + ZebraExplainInfo zei = zh->reg->zei; + int ch; + zinfo_index_category_t cat = zinfo_index_category_sort; + + ch = zebraExplain_lookup_attr_str(zei, cat, p->index_type, p->index_name); + if (ch < 0) + ch = zebraExplain_add_attr_str(zei, cat, p->index_type, p->index_name); + key.len = 2; + key.mem[0] = ch; + key.mem[1] = p->record_id; + + zebra_rec_keys_write(zh->reg->sortKeys, str, length, &key); +} + +static void extract_add_staticrank_string(RecWord *p, + const char *str, int length) +{ + char valz[40]; + struct recExtractCtrl *ctrl = p->extractCtrl; + + if (length > sizeof(valz)-1) + length = sizeof(valz)-1; + + memcpy(valz, str, length); + valz[length] = '\0'; + ctrl->staticrank = atozint(valz); +} + +static void extract_add_string(RecWord *p, zebra_map_t zm, + const char *string, int length) +{ + assert(length > 0); + + if (!p->index_name) + return; - sprintf (ext_res, "%sstoreKeys.%s", gprefix, ext); - if (!(sval = res_get (common_resource, ext_res))) + if (zebra_maps_is_index(zm)) + { + extract_add_index_string(p, zinfo_index_category_index, + string, length); + if (zebra_maps_is_alwaysmatches(zm)) { - sprintf (ext_res, "%sstoreKeys", gprefix); - sval = res_get (common_resource, ext_res); + RecWord word; + memcpy(&word, p, sizeof(word)); + + word.seqno = 1; + extract_add_index_string( + &word, zinfo_index_category_alwaysmatches, "", 0); } - if (sval) - rGroup->flagStoreKeys = atoi (sval); } - if (rGroup->flagStoreKeys == -1) - rGroup->flagStoreKeys = 0; + else if (zebra_maps_is_sort(zm)) + { + extract_add_sort_string(p, string, length); + } + else if (zebra_maps_is_staticrank(zm)) + { + extract_add_staticrank_string(p, string, length); + } +} + +static void extract_add_incomplete_field(RecWord *p, zebra_map_t zm) +{ + const char *b = p->term_buf; + int remain = p->term_len; + int first = 1; + const char **map = 0; + + if (remain > 0) + map = zebra_maps_input(zm, &b, remain, 0); -#if ZEBRASDR - if (rGroup->useSDR) + while (map) { - ZebraSdrHandle h; - char xname[128], *xp; - - strncpy (xname, fname, 127); - if (!(xp = strchr (xname, '.'))) - return 0; - *xp = '\0'; - if (strcmp (xp+1, "sdr.bits")) - return 0; - - h = zebraSdr_open (xname); - if (!h) + char buf[IT_MAX_WORD+1]; + int i, remain; + + /* Skip spaces */ + while (map && *map && **map == *CHR_SPACE) { - logf (LOG_WARN, "sdr open %s", xname); - return 0; + remain = p->term_len - (b - p->term_buf); + if (remain > 0) + map = zebra_maps_input(zm, &b, remain, 0); + else + map = 0; } - for (;;) + if (!map) + break; + i = 0; + while (map && *map && **map != *CHR_SPACE) { - unsigned char *buf; - char sdr_name[128]; - int r, segmentno; + const char *cp = *map; - segmentno = zebraSdr_segment (h, 0); - sprintf (sdr_name, "%%%s.%d", xname, segmentno); + while (i < IT_MAX_WORD && *cp) + buf[i++] = *(cp++); + remain = p->term_len - (b - p->term_buf); + if (remain > 0) + map = zebra_maps_input(zm, &b, remain, 0); + else + map = 0; + } + if (!i) + return; -#if 0 - if (segmentno > 20) - break; -#endif - r = zebraSdr_read (h, &buf); + if (first) + { + first = 0; + if (zebra_maps_is_first_in_field(zm)) + { + /* first in field marker */ + extract_add_string(p, zm, FIRST_IN_FIELD_STR, FIRST_IN_FIELD_LEN); + p->seqno++; + } + } + extract_add_string(p, zm, buf, i); + p->seqno++; + } +} - if (!r) - break; +static void extract_add_complete_field(RecWord *p, zebra_map_t zm) +{ + const char *b = p->term_buf; + char buf[IT_MAX_WORD+1]; + const char **map = 0; + int i = 0, remain = p->term_len; - fi = file_read_start (0); - fi->sdrbuf = buf; - fi->sdrmax = r; - do + if (remain > 0) + map = zebra_maps_input(zm, &b, remain, 1); + + while (remain > 0 && i < IT_MAX_WORD) + { + while (map && *map && **map == *CHR_SPACE) + { + remain = p->term_len - (b - p->term_buf); + + if (remain > 0) { - file_begin (fi); - r = recordExtract (sysno, sdr_name, rGroup, deleteFlag, fi, - recType, subType); - } while (r && !sysno && fi->file_more); - file_read_stop (fi); - free (buf); + int first = i ? 0 : 1; /* first position */ + map = zebra_maps_input(zm, &b, remain, first); + } + else + map = 0; + } + if (!map) + break; + + if (i && i < IT_MAX_WORD) + buf[i++] = *CHR_SPACE; + while (map && *map && **map != *CHR_SPACE) + { + const char *cp = *map; + + if (**map == *CHR_CUT) + { + i = 0; + } + else + { + if (i >= IT_MAX_WORD) + break; + while (i < IT_MAX_WORD && *cp) + buf[i++] = *(cp++); + } + remain = p->term_len - (b - p->term_buf); + if (remain > 0) + { + map = zebra_maps_input(zm, &b, remain, 0); + } + else + map = 0; } - zebraSdr_close (h); - return 1; } -#endif - if (sysno && deleteFlag) - fd = -1; - else + if (!i) + return; + extract_add_string(p, zm, buf, i); +} + +static void extract_add_icu(RecWord *p, zebra_map_t zm) +{ + const char *res_buf = 0; + size_t res_len = 0; + + zebra_map_tokenize_start(zm, p->term_buf, p->term_len); + while (zebra_map_tokenize_next(zm, &res_buf, &res_len, 0, 0)) { - if ((fd = open (fname, O_BINARY|O_RDONLY)) == -1) - { - logf (LOG_WARN|LOG_ERRNO, "open %s", fname); - return 0; - } + extract_add_string(p, zm, res_buf, res_len); + p->seqno++; } - fi = file_read_start (fd); - do +} + + +/** \brief top-level indexing handler for recctrl system + \param p token data to be indexed + + Call sequence: + extract_token_add + extract_add_{in}_complete / extract_add_icu + extract_add_string + + extract_add_index_string + or + extract_add_sort_string + or + extract_add_staticrank_string + +*/ +static void extract_token_add(RecWord *p) +{ + ZebraHandle zh = p->extractCtrl->handle; + zebra_map_t zm = zebra_map_get_or_add(zh->reg->zebra_maps, p->index_type); + WRBUF wrbuf; + + if (log_level_details) { - file_begin (fi); - r = recordExtract (sysno, fname, rGroup, deleteFlag, fi, - recType, subType, clientData); - } while (r && !sysno && fi->file_more); - file_read_stop (fi); - if (fd != -1) - close (fd); - return r; + yaz_log(log_level_details, "extract_token_add " + "type=%s index=%s seqno=" ZINT_FORMAT " s=%.*s", + p->index_type, p->index_name, + p->seqno, p->term_len, p->term_buf); + } + if ((wrbuf = zebra_replace(zm, 0, p->term_buf, p->term_len))) + { + p->term_buf = wrbuf_buf(wrbuf); + p->term_len = wrbuf_len(wrbuf); + } + if (zebra_maps_is_icu(zm)) + { + extract_add_icu(p, zm); + } + else + { + if (zebra_maps_is_complete(zm)) + extract_add_complete_field(p, zm); + else + extract_add_incomplete_field(p, zm); + } } -static int explain_extract (void *handle, Record rec, data1_node *n) +static void extract_set_store_data_cb(struct recExtractCtrl *p, + void *buf, size_t sz) { - struct recordGroup *rGroup = (struct recordGroup*) handle; - struct recExtractCtrl extractCtrl; - int i; + ZebraHandle zh = (ZebraHandle) p->handle; - if (zebraExplain_curDatabase (zti, rec->info[recInfo_databaseName])) + xfree(zh->store_data_buf); + zh->store_data_buf = 0; + zh->store_data_size = 0; + if (buf && sz) { - if (zebraExplain_newDatabase (zti, rec->info[recInfo_databaseName], 0)) - abort (); + zh->store_data_buf = xmalloc(sz); + zh->store_data_size = sz; + memcpy(zh->store_data_buf, buf, sz); } +} - reckeys.buf_used = 0; - reckeys.prevAttrUse = -1; - reckeys.prevAttrSet = -1; - reckeys.prevSeqNo = 0; - - extractCtrl.init = wordInit; - extractCtrl.addWord = addRecordKey; - extractCtrl.addSchema = addSchema; - extractCtrl.dh = rGroup->dh; - for (i = 0; i<256; i++) - extractCtrl.seqno[i] = 0; - extractCtrl.zebra_maps = rGroup->zebra_maps; - extractCtrl.flagShowRecords = !rGroup->flagRw; - - grs_extract_tree(&extractCtrl, n); +static void extract_set_store_data_prepare(struct recExtractCtrl *p) +{ + ZebraHandle zh = (ZebraHandle) p->handle; + xfree(zh->store_data_buf); + zh->store_data_buf = 0; + zh->store_data_size = 0; + p->setStoreData = extract_set_store_data_cb; +} - logf (LOG_DEBUG, "flush explain record, sysno=%d", rec->sysno); +static void extract_schema_add(struct recExtractCtrl *p, Odr_oid *oid) +{ + ZebraHandle zh = (ZebraHandle) p->handle; + zebraExplain_addSchema(zh->reg->zei, oid); +} - if (rec->size[recInfo_delKeys]) +void extract_flush_sort_keys(ZebraHandle zh, zint sysno, + int cmd, zebra_rec_keys_t reckeys) +{ +#if 0 + yaz_log(YLOG_LOG, "extract_flush_sort_keys cmd=%d sysno=" ZINT_FORMAT, + cmd, sysno); + extract_rec_keys_log(zh, cmd, reckeys, YLOG_LOG); +#endif + + if (zebra_rec_keys_rewind(reckeys)) { - struct recKeys delkeys; + zebra_sort_index_t si = zh->reg->sort_index; + size_t slen; + const char *str; + struct it_key key_in; + + zebra_sort_sysno(si, sysno); - delkeys.buf_used = rec->size[recInfo_delKeys]; - delkeys.buf = rec->info[recInfo_delKeys]; - flushSortKeys (rec->sysno, 0); - flushRecordKeys (rec->sysno, 0, &delkeys); + while (zebra_rec_keys_read(reckeys, &str, &slen, &key_in)) + { + int ord = CAST_ZINT_TO_INT(key_in.mem[0]); + + zebra_sort_type(si, ord); + if (cmd == 1) + zebra_sort_add(si, str, slen); + else + zebra_sort_delete(si); + } } - flushRecordKeys (rec->sysno, 1, &reckeys); - flushSortKeys (rec->sysno, 1); +} - xfree (rec->info[recInfo_delKeys]); - rec->size[recInfo_delKeys] = reckeys.buf_used; - rec->info[recInfo_delKeys] = reckeys.buf; - reckeys.buf = NULL; - reckeys.buf_max = 0; +/* + * Local variables: + * c-basic-offset: 4 + * indent-tabs-mode: nil + * End: + * vim: shiftwidth=4 tabstop=8 expandtab + */ - return 0; -}