Termlist source implemented (so that we can index values of XML/SGML
[idzebra-moved-to-github.git] / index / extract.c
1 /*
2  * Copyright (C) 1994-2000, Index Data 
3  * All rights reserved.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * $Log: extract.c,v $
7  * Revision 1.106  2000-12-05 12:22:53  adam
8  * Termlist source implemented (so that we can index values of XML/SGML
9  * attributes).
10  *
11  * Revision 1.105  2000/12/05 10:01:44  adam
12  * Fixed bug regarding user-defined attribute sets.
13  *
14  * Revision 1.104  2000/09/05 14:04:05  adam
15  * Updates for prefix 'yaz_' for YAZ log functions.
16  *
17  * Revision 1.103  2000/05/18 12:01:36  adam
18  * System call times(2) used again. More 64-bit fixes.
19  *
20  * Revision 1.102  2000/05/15 15:32:33  adam
21  * Added 64 bit file input.
22  *
23  * Revision 1.101  2000/05/15 13:02:39  adam
24  * Minor change.
25  *
26  * Revision 1.100  2000/03/20 19:08:36  adam
27  * Added remote record import using Z39.50 extended services and Segment
28  * Requests.
29  *
30  * Revision 1.99  2000/02/24 10:57:02  adam
31  * Sequence number incremented after each incomplete-field.
32  *
33  * Revision 1.98  1999/09/07 07:19:21  adam
34  * Work on character mapping. Implemented replace rules.
35  *
36  * Revision 1.97  1999/07/06 12:28:04  adam
37  * Updated record index structure. Format includes version ID. Compression
38  * algorithm ID is stored for each record block.
39  *
40  * Revision 1.96  1999/05/26 07:49:13  adam
41  * C++ compilation.
42  *
43  * Revision 1.95  1999/05/21 12:00:17  adam
44  * Better diagnostics for extraction process.
45  *
46  * Revision 1.94  1999/05/20 12:57:18  adam
47  * Implemented TCL filter. Updated recctrl system.
48  *
49  * Revision 1.93  1999/05/15 14:36:38  adam
50  * Updated dictionary. Implemented "compression" of dictionary.
51  *
52  * Revision 1.92  1999/03/09 16:27:49  adam
53  * More work on SDRKit integration.
54  *
55  * Revision 1.91  1999/02/12 13:29:22  adam
56  * Implemented position-flag for registers.
57  *
58  * Revision 1.90  1999/02/02 14:50:52  adam
59  * Updated WIN32 code specific sections. Changed header.
60  *
61  * Revision 1.89  1998/10/28 10:54:38  adam
62  * SDRKit integration.
63  *
64  * Revision 1.88  1998/10/16 08:14:29  adam
65  * Updated record control system.
66  *
67  * Revision 1.87  1998/10/15 13:10:33  adam
68  * Fixed bug in Zebra that caused it to stop indexing when empty
69  * record was read.
70  *
71  * Revision 1.86  1998/10/13 20:33:53  adam
72  * Fixed one log message and change use ordinal to be an unsigned char.
73  *
74  * Revision 1.85  1998/09/22 10:03:41  adam
75  * Changed result sets to be persistent in the sense that they can
76  * be re-searched if needed.
77  * Fixed memory leak in rsm_or.
78  *
79  * Revision 1.84  1998/06/11 15:42:22  adam
80  * Changed the way use attributes are specified in the recordId
81  * specification.
82  *
83  * Revision 1.83  1998/06/08 14:43:10  adam
84  * Added suport for EXPLAIN Proxy servers - added settings databasePath
85  * and explainDatabase to facilitate this. Increased maximum number
86  * of databases and attributes in one register.
87  *
88  * Revision 1.82  1998/05/20 10:12:15  adam
89  * Implemented automatic EXPLAIN database maintenance.
90  * Modified Zebra to work with ASN.1 compiled version of YAZ.
91  *
92  * Revision 1.81  1998/03/11 11:19:04  adam
93  * Changed the way sequence numbers are generated.
94  *
95  * Revision 1.80  1998/03/05 08:45:11  adam
96  * New result set model and modular ranking system. Moved towards
97  * descent server API. System information stored as "SGML" records.
98  *
99  * Revision 1.79  1998/02/17 10:32:52  adam
100  * Fixed bug: binary files weren't opened with flag b on NT.
101  *
102  * Revision 1.78  1998/02/10 12:03:05  adam
103  * Implemented Sort.
104  *
105  * Revision 1.77  1998/01/12 15:04:08  adam
106  * The test option (-s) only uses read-lock (and not write lock).
107  *
108  * Revision 1.76  1997/10/27 14:33:04  adam
109  * Moved towards generic character mapping depending on "structure"
110  * field in abstract syntax file. Fixed a few memory leaks. Fixed
111  * bug with negative integers when doing searches with relational
112  * operators.
113  *
114  * Revision 1.75  1997/09/17 12:19:12  adam
115  * Zebra version corresponds to YAZ version 1.4.
116  * Changed Zebra server so that it doesn't depend on global common_resource.
117  *
118  * Revision 1.74  1997/09/09 13:38:06  adam
119  * Partial port to WIN95/NT.
120  *
121  * Revision 1.73  1997/09/04 13:57:20  adam
122  * New file extract/retrieve method tellf (added).
123  * Added O_BINARY for open calls.
124  *
125  * Revision 1.72  1997/07/15 16:32:29  adam
126  * Bug fix: Match handler didn't terminate the resulting string!
127  *
128  * Revision 1.71  1997/07/15 16:28:41  adam
129  * Bug fix: storeData didn't work with files with multiple records.
130  * Bug fix: fixed memory management with records; not really well
131  *  thought through.
132  *
133  * Revision 1.70  1997/07/01 13:00:42  adam
134  * Bug fix in routine searchRecordKey: uninitialized variables.
135  *
136  * Revision 1.69  1997/04/29 09:26:03  adam
137  * Bug fix: generic recordId handling didn't work for compressed internal
138  * keys.
139  *
140  * Revision 1.68  1997/02/12 20:39:45  adam
141  * Implemented options -f <n> that limits the log to the first <n>
142  * records.
143  * Changed some log messages also.
144  *
145  * Revision 1.67  1996/11/15 15:02:14  adam
146  * Minor changes regarding logging.
147  *
148  * Revision 1.66  1996/11/14  09:52:21  adam
149  * Strings in record keys bound by IT_MAX_WORD.
150  *
151  * Revision 1.65  1996/11/14  08:57:56  adam
152  * Reduction of storeKeys area.
153  *
154  * Revision 1.64  1996/11/08 11:10:16  adam
155  * Buffers used during file match got bigger.
156  * Compressed ISAM support everywhere.
157  * Bug fixes regarding masking characters in queries.
158  * Redesigned Regexp-2 queries.
159  *
160  * Revision 1.63  1996/10/29 14:09:39  adam
161  * Use of cisam system - enabled if setting isamc is 1.
162  *
163  * Revision 1.62  1996/10/11 10:57:01  adam
164  * New module recctrl. Used to manage records (extract/retrieval).
165  * Several files have been moved to the recctrl sub directory.
166  *
167  * Revision 1.61  1996/06/06 12:08:37  quinn
168  * Added showRecord function
169  *
170  * Revision 1.60  1996/06/04  10:18:12  adam
171  * Search/scan uses character mapping module.
172  *
173  * Revision 1.59  1996/05/14  15:47:07  adam
174  * Cleanup of various buffer size entities.
175  *
176  * Revision 1.58  1996/05/14  06:16:38  adam
177  * Compact use/set bytes used in search service.
178  *
179  * Revision 1.57  1996/05/13 14:23:04  adam
180  * Work on compaction of set/use bytes in dictionary.
181  *
182  * Revision 1.56  1996/05/09  09:54:42  adam
183  * Server supports maps from one logical attributes to a list of physical
184  * attributes.
185  * The extraction process doesn't make space consuming 'any' keys.
186  *
187  * Revision 1.55  1996/05/09  07:28:55  quinn
188  * Work towards phrases and multiple registers
189  *
190  * Revision 1.54  1996/05/01  13:46:35  adam
191  * First work on multiple records in one file.
192  * New option, -offset, to the "unread" command in the filter module.
193  *
194  * Revision 1.53  1996/04/26  12:09:43  adam
195  * Added a few comments.
196  *
197  * Revision 1.52  1996/04/25  13:27:57  adam
198  * Function recordExtract modified so that files with no keys (possibly empty)
199  * are ignored.
200  *
201  * Revision 1.51  1996/03/19  11:08:42  adam
202  * Bug fix: Log preamble wasn't always turned off after recordExtract.
203  *
204  * Revision 1.50  1996/02/12  18:45:36  adam
205  * New fileVerboseFlag in record group control.
206  *
207  * Revision 1.49  1996/02/05  12:29:57  adam
208  * Logging reduced a bit.
209  * The remaining running time is estimated during register merge.
210  *
211  * Revision 1.48  1996/02/01  20:53:26  adam
212  * The temporary per-record keys are compacted a little, and duplication
213  * of the per-records keys are avoided when they are saved in the record
214  * information buffer.
215  *
216  * Revision 1.47  1996/01/17  14:57:48  adam
217  * Prototype changed for reader functions in extract/retrieve. File
218  *  is identified by 'void *' instead of 'int.
219  *
220  * Revision 1.46  1995/12/15  14:57:16  adam
221  * Bug fix.
222  *
223  * Revision 1.45  1995/12/15  12:37:41  adam
224  * In addRecordKeyAny: Writes key only when attrSet != -1.
225  *
226  * Revision 1.44  1995/12/12  16:00:54  adam
227  * System call sync(2) used after update/commit.
228  * Locking (based on fcntl) uses F_EXLCK and F_SHLCK instead of F_WRLCK
229  * and F_RDLCK.
230  *
231  * Revision 1.43  1995/12/11  09:12:46  adam
232  * The rec_get function returns NULL if record doesn't exist - will
233  * happen in the server if the result set records have been deleted since
234  * the creation of the set (i.e. the search).
235  * The server saves a result temporarily if it is 'volatile', i.e. the
236  * set is register dependent.
237  *
238  * Revision 1.42  1995/12/07  17:38:46  adam
239  * Work locking mechanisms for concurrent updates/commit.
240  *
241  * Revision 1.41  1995/12/06  16:06:42  adam
242  * Better diagnostics. Work on 'real' dictionary deletion.
243  *
244  * Revision 1.40  1995/12/05  16:57:40  adam
245  * More work on regular patterns.
246  *
247  * Revision 1.39  1995/12/05  13:20:18  adam
248  * Bug fix: file_read sometimes returned early EOF.
249  *
250  * Revision 1.38  1995/12/04  17:59:21  adam
251  * More work on regular expression conversion.
252  *
253  * Revision 1.37  1995/12/04  14:22:27  adam
254  * Extra arg to recType_byName.
255  * Started work on new regular expression parsed input to
256  * structured records.
257  *
258  * Revision 1.36  1995/11/30  08:34:29  adam
259  * Started work on commit facility.
260  * Changed a few malloc/free to xmalloc/xfree.
261  *
262  * Revision 1.35  1995/11/28  14:26:21  adam
263  * Bug fix: recordId with constant wasn't right.
264  * Bug fix: recordId dictionary entry wasn't deleted when needed.
265  *
266  * Revision 1.34  1995/11/28  09:09:38  adam
267  * Zebra config renamed.
268  * Use setting 'recordId' to identify record now.
269  * Bug fix in recindex.c: rec_release_blocks was invokeded even
270  * though the blocks were already released.
271  * File traversal properly deletes records when needed.
272  *
273  * Revision 1.33  1995/11/27  09:56:20  adam
274  * Record info elements better enumerated. Internal store of records.
275  *
276  * Revision 1.32  1995/11/25  10:24:05  adam
277  * More record fields - they are enumerated now.
278  * New options: flagStoreData flagStoreKey.
279  *
280  * Revision 1.31  1995/11/24  11:31:35  adam
281  * Commands add & del read filenames from stdin if source directory is
282  * empty.
283  * Match criteria supports 'constant' strings.
284  *
285  * Revision 1.30  1995/11/22  17:19:16  adam
286  * Record management uses the bfile system.
287  *
288  * Revision 1.29  1995/11/21  15:01:14  adam
289  * New general match criteria implemented.
290  * New feature: document groups.
291  *
292  * Revision 1.28  1995/11/21  09:20:30  adam
293  * Yet more work on record match.
294  *
295  * Revision 1.27  1995/11/20  16:59:45  adam
296  * New update method: the 'old' keys are saved for each records.
297  *
298  * Revision 1.26  1995/11/20  11:56:24  adam
299  * Work on new traversal.
300  *
301  * Revision 1.25  1995/11/16  15:34:54  adam
302  * Uses new record management system in both indexer and server.
303  *
304  * Revision 1.24  1995/11/15  19:13:08  adam
305  * Work on record management.
306  *
307  * Revision 1.23  1995/10/27  14:00:10  adam
308  * Implemented detection of database availability.
309  *
310  * Revision 1.22  1995/10/17  18:02:07  adam
311  * New feature: databases. Implemented as prefix to words in dictionary.
312  *
313  * Revision 1.21  1995/10/10  12:24:38  adam
314  * Temporary sort files are compressed.
315  *
316  * Revision 1.20  1995/10/06  13:52:05  adam
317  * Bug fixes. Handler may abort further scanning.
318  *
319  * Revision 1.19  1995/10/04  12:55:16  adam
320  * Bug fix in ranked search. Use=Any keys inserted.
321  *
322  * Revision 1.18  1995/10/04  09:37:08  quinn
323  * Fixed bug.
324  *
325  * Revision 1.17  1995/10/03  14:28:57  adam
326  * Buffered read in extract works.
327  *
328  * Revision 1.16  1995/10/03  14:28:45  adam
329  * Work on more effecient read handler in extract.
330  *
331  * Revision 1.15  1995/10/02  15:42:53  adam
332  * Extract uses file descriptors instead of FILE pointers.
333  *
334  * Revision 1.14  1995/10/02  15:29:13  adam
335  * More logging in file_extract.
336  *
337  * Revision 1.13  1995/09/29  14:01:39  adam
338  * Bug fixes.
339  *
340  * Revision 1.12  1995/09/28  14:22:56  adam
341  * Sort uses smaller temporary files.
342  *
343  * Revision 1.11  1995/09/28  12:10:31  adam
344  * Bug fixes. Field prefix used in queries.
345  *
346  * Revision 1.10  1995/09/28  09:19:41  adam
347  * xfree/xmalloc used everywhere.
348  * Extract/retrieve method seems to work for text records.
349  *
350  * Revision 1.9  1995/09/27  12:22:28  adam
351  * More work on extract in record control.
352  * Field name is not in isam keys but in prefix in dictionary words.
353  *
354  * Revision 1.8  1995/09/14  07:48:22  adam
355  * Record control management.
356  *
357  * Revision 1.7  1995/09/11  13:09:32  adam
358  * More work on relevance feedback.
359  *
360  * Revision 1.6  1995/09/08  14:52:27  adam
361  * Minor changes. Dictionary is lower case now.
362  *
363  * Revision 1.5  1995/09/06  16:11:16  adam
364  * Option: only one word key per file.
365  *
366  * Revision 1.4  1995/09/05  15:28:39  adam
367  * More work on search engine.
368  *
369  * Revision 1.3  1995/09/04  12:33:41  adam
370  * Various cleanup. YAZ util used instead.
371  *
372  * Revision 1.2  1995/09/04  09:10:34  adam
373  * More work on index add/del/update.
374  * Merge sort implemented.
375  * Initial work on z39 server.
376  *
377  * Revision 1.1  1995/09/01  14:06:35  adam
378  * Split of work into more files.
379  *
380  */
381 #include <stdio.h>
382 #include <assert.h>
383 #ifdef WIN32
384 #include <io.h>
385 #else
386 #include <unistd.h>
387 #endif
388 #include <fcntl.h>
389
390 #include <recctrl.h>
391 #include <charmap.h>
392 #include <sortidx.h>
393 #include "index.h"
394
395 #include "zinfo.h"
396
397 #if _FILE_OFFSET_BITS == 64
398 #define PRINTF_OFF_T "%Ld"
399 #else
400 #define PRINTF_OFF_T "%ld"
401 #endif
402
403 #ifndef ZEBRASDR
404 #define ZEBRASDR 0
405 #endif
406
407 #if ZEBRASDR
408 #include "zebrasdr.h"
409 #endif
410
411 static Dict matchDict;
412
413 static Records records = NULL;
414 static SortIdx sortIdx = NULL;
415
416 static char **key_buf;
417 static size_t ptr_top;
418 static size_t ptr_i;
419 static size_t key_buf_used;
420 static int key_file_no;
421
422 static int records_inserted = 0;
423 static int records_updated = 0;
424 static int records_deleted = 0;
425 static int records_processed = 0;
426
427 static ZebraExplainInfo zti = NULL;
428
429
430 static void logRecord (int showFlag)
431 {
432     if (!showFlag)
433         ++records_processed;
434     if (showFlag || !(records_processed % 1000))
435     {
436         logf (LOG_LOG, "Records: %7d i/u/d %d/%d/%d", 
437               records_processed, records_inserted, records_updated,
438               records_deleted);
439     }
440 }
441
442 static int explain_extract (void *handle, Record drec, data1_node *n);
443
444 int key_open (struct recordGroup *rGroup, int mem)
445 {
446     BFiles bfs = rGroup->bfs;
447     int rw = rGroup->flagRw;
448     data1_handle dh = rGroup->dh;
449     char *recordCompression;
450     int record_compression = REC_COMPRESS_NONE;
451     if (!mem)
452         mem = atoi(res_get_def (common_resource, "memMax", "16"))*1024*1024;
453     if (mem < 50000)
454         mem = 50000;
455     key_buf = (char **) xmalloc (mem);
456     ptr_top = mem/sizeof(char*);
457     ptr_i = 0;
458
459     key_buf_used = 0;
460     key_file_no = 0;
461
462     if (!(matchDict = dict_open (bfs, GMATCH_DICT, 50, rw, 0)))
463     {
464         logf (LOG_FATAL, "dict_open fail of %s", GMATCH_DICT);
465         return -1;
466     }
467     assert (!records);
468     recordCompression = res_get_def (common_resource,
469                                      "recordCompression", "none");
470     if (!strcmp (recordCompression, "none"))
471         record_compression = REC_COMPRESS_NONE;
472     if (!strcmp (recordCompression, "bzip2"))
473         record_compression = REC_COMPRESS_BZIP2;
474     records = rec_open (bfs, rw, record_compression);
475     if (!records)
476     {
477         dict_close (matchDict);
478         return -1;
479     }
480     zti = zebraExplain_open (records, dh, common_resource,
481                              rw, rGroup, explain_extract);
482     if (!zti)
483     {
484         rec_close (&records);
485         dict_close (matchDict);
486         return -1;      
487     }
488     sortIdx = sortIdx_open (bfs, 1);
489     return 0;
490 }
491
492 struct encode_info {
493     int  sysno;
494     int  seqno;
495     int  cmd;
496     char buf[768];
497 };
498
499 void encode_key_init (struct encode_info *i)
500 {
501     i->sysno = 0;
502     i->seqno = 0;
503     i->cmd = -1;
504 }
505
506 char *encode_key_int (int d, char *bp)
507 {
508     if (d <= 63)
509         *bp++ = d;
510     else if (d <= 16383)
511     {
512         *bp++ = 64 + (d>>8);
513         *bp++ = d  & 255;
514     }
515     else if (d <= 4194303)
516     {
517         *bp++ = 128 + (d>>16);
518         *bp++ = (d>>8) & 255;
519         *bp++ = d & 255;
520     }
521     else
522     {
523         *bp++ = 192 + (d>>24);
524         *bp++ = (d>>16) & 255;
525         *bp++ = (d>>8) & 255;
526         *bp++ = d & 255;
527     }
528     return bp;
529 }
530
531 void encode_key_write (char *k, struct encode_info *i, FILE *outf)
532 {
533     struct it_key key;
534     char *bp = i->buf;
535
536     while ((*bp++ = *k++))
537         ;
538     memcpy (&key, k+1, sizeof(struct it_key));
539     bp = encode_key_int ( (key.sysno - i->sysno) * 2 + *k, bp);
540     if (i->sysno != key.sysno)
541     {
542         i->sysno = key.sysno;
543         i->seqno = 0;
544     }
545     else if (!i->seqno && !key.seqno && i->cmd == *k)
546         return;
547     bp = encode_key_int (key.seqno - i->seqno, bp);
548     i->seqno = key.seqno;
549     i->cmd = *k;
550     if (fwrite (i->buf, bp - i->buf, 1, outf) != 1)
551     {
552         logf (LOG_FATAL|LOG_ERRNO, "fwrite");
553         exit (1);
554     }
555 }
556
557 #define SORT_EXTRA 0
558
559 #if SORT_EXTRA
560 static int key_y_len;
561
562 static int key_y_compare (const void *p1, const void *p2)
563 {
564     int r;
565
566     if ((r = key_compare (*(char**) p1 + key_y_len + 1,
567                           *(char**) p2 + key_y_len + 1)))
568          return r;
569     return *(*(char**) p1 + key_y_len) - *(*(char**) p2 + key_y_len);
570 }
571
572 static int key_x_compare (const void *p1, const void *p2)
573 {
574     return strcmp (*(char**) p1, *(char**) p2);
575 }
576 #endif
577
578 void key_flush (void)
579 {
580     FILE *outf;
581     char out_fname[200];
582     char *prevcp, *cp;
583     struct encode_info encode_info;
584 #if SORT_EXTRA
585     int i;
586 #endif
587     
588     if (ptr_i <= 0)
589         return;
590
591     key_file_no++;
592     logf (LOG_LOG, "sorting section %d", key_file_no);
593 #if !SORT_EXTRA
594     qsort (key_buf + ptr_top-ptr_i, ptr_i, sizeof(char*), key_qsort_compare);
595     getFnameTmp (common_resource, out_fname, key_file_no);
596
597     if (!(outf = fopen (out_fname, "wb")))
598     {
599         logf (LOG_FATAL|LOG_ERRNO, "fopen %s", out_fname);
600         exit (1);
601     }
602     logf (LOG_LOG, "writing section %d", key_file_no);
603     prevcp = cp = key_buf[ptr_top-ptr_i];
604     
605     encode_key_init (&encode_info);
606     encode_key_write (cp, &encode_info, outf);
607     while (--ptr_i > 0)
608     {
609         cp = key_buf[ptr_top-ptr_i];
610         if (strcmp (cp, prevcp))
611         {
612             encode_key_init (&encode_info);
613             encode_key_write (cp, &encode_info, outf);
614             prevcp = cp;
615         }
616         else
617             encode_key_write (cp + strlen(cp), &encode_info, outf);
618     }
619 #else
620     qsort (key_buf + ptr_top-ptr_i, ptr_i, sizeof(char*), key_x_compare);
621     getFnameTmp (out_fname, key_file_no);
622
623     if (!(outf = fopen (out_fname, "wb")))
624     {
625         logf (LOG_FATAL|LOG_ERRNO, "fopen %s", out_fname);
626         exit (1);
627     }
628     logf (LOG_LOG, "writing section %d", key_file_no);
629     i = ptr_i;
630     prevcp =  key_buf[ptr_top-i];
631     while (1)
632         if (!--i || strcmp (prevcp, key_buf[ptr_top-i]))
633         {
634             key_y_len = strlen(prevcp)+1;
635 #if 0
636             logf (LOG_LOG, "key_y_len: %2d %02x %02x %s",
637                       key_y_len, prevcp[0], prevcp[1], 2+prevcp);
638 #endif
639             qsort (key_buf + ptr_top-ptr_i, ptr_i - i,
640                                    sizeof(char*), key_y_compare);
641             cp = key_buf[ptr_top-ptr_i];
642             --key_y_len;
643             encode_key_init (&encode_info);
644             encode_key_write (cp, &encode_info, outf);
645             while (--ptr_i > i)
646             {
647                 cp = key_buf[ptr_top-ptr_i];
648                 encode_key_write (cp+key_y_len, &encode_info, outf);
649             }
650             if (!i)
651                 break;
652             prevcp = key_buf[ptr_top-ptr_i];
653         }
654 #endif
655     if (fclose (outf))
656     {
657         logf (LOG_FATAL|LOG_ERRNO, "fclose %s", out_fname);
658         exit (1);
659     }
660     logf (LOG_LOG, "finished section %d", key_file_no);
661     ptr_i = 0;
662     key_buf_used = 0;
663 }
664
665 int key_close (struct recordGroup *rGroup)
666 {
667     int rw = rGroup->flagRw;
668     if (rw)
669         zebraExplain_runNumberIncrement (zti, 1);
670     zebraExplain_close (zti, rw);
671     key_flush ();
672     xfree (key_buf);
673     rec_close (&records);
674     dict_close (matchDict);
675     sortIdx_close (sortIdx);
676
677     logRecord (1);
678     return key_file_no;
679 }
680
681 static void wordInit (struct recExtractCtrl *p, RecWord *w)
682 {
683     w->zebra_maps = p->zebra_maps;
684     w->seqnos = p->seqno;
685     w->attrSet = VAL_BIB1;
686     w->attrUse = 1016;
687     w->reg_type = 'w';
688     w->extractCtrl = p;
689 }
690
691 static struct sortKey {
692     char *string;
693     int length;
694     int attrSet;
695     int attrUse;
696     struct sortKey *next;
697 } *sortKeys = NULL;
698
699 static struct recKeys {
700     int buf_used;
701     int buf_max;
702     char *buf;
703     char prevAttrSet;
704     short prevAttrUse;
705     int prevSeqNo;
706 } reckeys;
707
708 static void addIndexString (RecWord *p, const char *string, int length)
709 {
710     char *dst;
711     unsigned char attrSet;
712     unsigned short attrUse;
713     int lead = 0;
714     int diff = 0;
715     int *pseqno = &p->seqnos[p->reg_type];
716
717     if (reckeys.buf_used+1024 > reckeys.buf_max)
718     {
719         char *b;
720
721         b = (char *) xmalloc (reckeys.buf_max += 128000);
722         if (reckeys.buf_used > 0)
723             memcpy (b, reckeys.buf, reckeys.buf_used);
724         xfree (reckeys.buf);
725         reckeys.buf = b;
726     }
727     dst = reckeys.buf + reckeys.buf_used;
728
729     attrSet = p->attrSet;
730     if (reckeys.buf_used > 0 && reckeys.prevAttrSet == attrSet)
731         lead |= 1;
732     else
733         reckeys.prevAttrSet = attrSet;
734     attrUse = p->attrUse;
735     if (reckeys.buf_used > 0 && reckeys.prevAttrUse == attrUse)
736         lead |= 2;
737     else
738         reckeys.prevAttrUse = attrUse;
739 #if 1
740     diff = 1 + *pseqno - reckeys.prevSeqNo;
741     if (diff >= 1 && diff <= 15)
742         lead |= (diff << 2);
743     else
744         diff = 0;
745 #endif
746     reckeys.prevSeqNo = *pseqno;
747     
748     *dst++ = lead;
749
750 #if SU_SCHEME
751     if ((lead & 3) < 3)
752     {
753         int ch = zebraExplain_lookupSU (zti, attrSet, attrUse);
754         if (ch < 0)
755         {
756             ch = zebraExplain_addSU (zti, attrSet, attrUse);
757         }
758         assert (ch > 0);
759         memcpy (dst, &ch, sizeof(ch));
760         dst += sizeof(ch);
761     }
762 #else
763     if (!(lead & 1))
764     {
765         memcpy (dst, &attrSet, sizeof(attrSet));
766         dst += sizeof(attrSet);
767     }
768     if (!(lead & 2))
769     {
770         memcpy (dst, &attrUse, sizeof(attrUse));
771         dst += sizeof(attrUse);
772     }
773 #endif
774     *dst++ = p->reg_type;
775     memcpy (dst, string, length);
776     dst += length;
777     *dst++ = '\0';
778
779     if (!diff)
780     {
781         memcpy (dst, pseqno, sizeof(*pseqno));
782         dst += sizeof(*pseqno);
783     }
784     reckeys.buf_used = dst - reckeys.buf;
785     if (*pseqno)
786         (*pseqno)++;
787 }
788
789 static void addSortString (RecWord *p, const char *string, int length)
790 {
791     struct sortKey *sk;
792
793     for (sk = sortKeys; sk; sk = sk->next)
794         if (sk->attrSet == p->attrSet && sk->attrUse == p->attrUse)
795             return;
796
797     sk = (struct sortKey *) xmalloc (sizeof(*sk));
798     sk->next = sortKeys;
799     sortKeys = sk;
800
801     sk->string = (char *) xmalloc (length);
802     sk->length = length;
803     memcpy (sk->string, string, length);
804
805     sk->attrSet = p->attrSet;
806     sk->attrUse = p->attrUse;
807 }
808
809 static void addString (RecWord *p, const char *string, int length)
810 {
811     assert (length > 0);
812     if (zebra_maps_is_sort (p->zebra_maps, p->reg_type))
813         addSortString (p, string, length);
814     else
815         addIndexString (p, string, length);
816 }
817
818 static void addIncompleteField (RecWord *p)
819 {
820     const char *b = p->string;
821     int remain = p->length;
822     const char **map = 0;
823
824     if (remain > 0)
825         map = zebra_maps_input(p->zebra_maps, p->reg_type, &b, remain);
826
827     while (map)
828     {
829         char buf[IT_MAX_WORD+1];
830         int i, remain;
831
832         /* Skip spaces */
833         while (map && *map && **map == *CHR_SPACE)
834         {
835             remain = p->length - (b - p->string);
836             if (remain > 0)
837                 map = zebra_maps_input(p->zebra_maps, p->reg_type, &b, remain);
838             else
839                 map = 0;
840         }
841         if (!map)
842             break;
843         i = 0;
844         while (map && *map && **map != *CHR_SPACE)
845         {
846             const char *cp = *map;
847
848             while (i < IT_MAX_WORD && *cp)
849                 buf[i++] = *(cp++);
850             remain = p->length - (b - p->string);
851             if (remain > 0)
852                 map = zebra_maps_input(p->zebra_maps, p->reg_type, &b, remain);
853             else
854                 map = 0;
855         }
856         if (!i)
857             return;
858         addString (p, buf, i);
859     }
860     (p->seqnos[p->reg_type])++; /* to separate this from next one  */
861 }
862
863 static void addCompleteField (RecWord *p)
864 {
865     const char *b = p->string;
866     char buf[IT_MAX_WORD+1];
867     const char **map = 0;
868     int i = 0, remain = p->length;
869
870     if (remain > 0)
871         map = zebra_maps_input (p->zebra_maps, p->reg_type, &b, remain);
872
873     while (remain > 0 && i < IT_MAX_WORD)
874     {
875         while (map && *map && **map == *CHR_SPACE)
876         {
877             remain = p->length - (b - p->string);
878             if (remain > 0)
879                 map = zebra_maps_input(p->zebra_maps, p->reg_type, &b, remain);
880             else
881                 map = 0;
882         }
883         if (!map)
884             break;
885
886         if (i && i < IT_MAX_WORD)
887             buf[i++] = *CHR_SPACE;
888         while (map && *map && **map != *CHR_SPACE)
889         {
890             const char *cp = *map;
891
892             if (i >= IT_MAX_WORD)
893                 break;
894             while (i < IT_MAX_WORD && *cp)
895                 buf[i++] = *(cp++);
896             remain = p->length  - (b - p->string);
897             if (remain > 0)
898                 map = zebra_maps_input (p->zebra_maps, p->reg_type, &b,
899                                         remain);
900             else
901                 map = 0;
902         }
903     }
904     if (!i)
905         return;
906     addString (p, buf, i);
907 }
908
909 static void addRecordKey (RecWord *p)
910 {
911     WRBUF wrbuf;
912     if ((wrbuf = zebra_replace(p->zebra_maps, p->reg_type, 0,
913                                p->string, p->length)))
914     {
915         p->string = wrbuf_buf(wrbuf);
916         p->length = wrbuf_len(wrbuf);
917     }
918     if (zebra_maps_is_complete (p->zebra_maps, p->reg_type))
919         addCompleteField (p);
920     else
921         addIncompleteField(p);
922 }
923
924 static void flushSortKeys (SYSNO sysno, int cmd)
925 {
926     struct sortKey *sk = sortKeys;
927
928     sortIdx_sysno (sortIdx, sysno);
929     while (sk)
930     {
931         struct sortKey *sk_next = sk->next;
932         sortIdx_type (sortIdx, sk->attrUse);
933         sortIdx_add (sortIdx, sk->string, sk->length);
934         xfree (sk->string);
935         xfree (sk);
936         sk = sk_next;
937     }
938     sortKeys = NULL;
939 }
940
941 static void flushRecordKeys (SYSNO sysno, int cmd, struct recKeys *reckeys)
942 {
943 #if SU_SCHEME
944 #else
945     unsigned char attrSet = (unsigned char) -1;
946     unsigned short attrUse = (unsigned short) -1;
947 #endif
948     int seqno = 0;
949     int off = 0;
950     int ch = 0;
951
952     zebraExplain_recordCountIncrement (zti, cmd ? 1 : -1);
953     while (off < reckeys->buf_used)
954     {
955         const char *src = reckeys->buf + off;
956         struct it_key key;
957         int lead;
958     
959         lead = *src++;
960
961 #if SU_SCHEME
962         if ((lead & 3) < 3)
963         {
964             memcpy (&ch, src, sizeof(ch));
965             src += sizeof(ch);
966         }
967 #else
968         if (!(lead & 1))
969         {
970             memcpy (&attrSet, src, sizeof(attrSet));
971             src += sizeof(attrSet);
972         }
973         if (!(lead & 2))
974         {
975             memcpy (&attrUse, src, sizeof(attrUse));
976             src += sizeof(attrUse);
977         }
978 #endif
979         if (key_buf_used + 1024 > (ptr_top-ptr_i)*sizeof(char*))
980             key_flush ();
981         ++ptr_i;
982
983         key_buf[ptr_top-ptr_i] = (char*)key_buf + key_buf_used;
984
985 #if SU_SCHEME
986 #else
987         ch = zebraExplain_lookupSU (zti, attrSet, attrUse);
988         if (ch < 0)
989         {
990             ch = zebraExplain_addSU (zti, attrSet, attrUse);
991             yaz_log (LOG_LOG, "addSU cmd=%d set=%d use=%d SU=%d",
992                      cmd, attrSet, attrUse, ch);
993         }
994 #endif
995         assert (ch > 0);
996         key_buf_used += key_SU_code (ch, ((char*)key_buf) + key_buf_used);
997
998         while (*src)
999             ((char*)key_buf) [key_buf_used++] = *src++;
1000         src++;
1001         ((char*)key_buf) [key_buf_used++] = '\0';
1002         ((char*) key_buf)[key_buf_used++] = cmd;
1003
1004         if (lead & 60)
1005             seqno += ((lead>>2) & 15)-1;
1006         else
1007         {
1008             memcpy (&seqno, src, sizeof(seqno));
1009             src += sizeof(seqno);
1010         }
1011         key.seqno = seqno;
1012         key.sysno = sysno;
1013         memcpy ((char*)key_buf + key_buf_used, &key, sizeof(key));
1014         key_buf_used += sizeof(key);
1015         off = src - reckeys->buf;
1016     }
1017     assert (off == reckeys->buf_used);
1018 }
1019
1020 static const char **searchRecordKey (struct recKeys *reckeys,
1021                                      int attrSetS, int attrUseS)
1022 {
1023     static const char *ws[32];
1024     int off = 0;
1025     int startSeq = -1;
1026     int i;
1027     int seqno = 0;
1028 #if SU_SCHEME
1029     int chS, ch;
1030 #else
1031     short attrUse;
1032     char attrSet;
1033 #endif
1034
1035     for (i = 0; i<32; i++)
1036         ws[i] = NULL;
1037
1038 #if SU_SCHEME
1039     chS = zebraExplain_lookupSU (zti, attrSetS, attrUseS);
1040     if (chS < 0)
1041         return ws;
1042 #endif
1043     while (off < reckeys->buf_used)
1044     {
1045
1046         const char *src = reckeys->buf + off;
1047         const char *wstart;
1048         int lead;
1049     
1050         lead = *src++;
1051 #if SU_SCHEME
1052         if ((lead & 3)<3)
1053         {
1054             memcpy (&ch, src, sizeof(ch));
1055             src += sizeof(ch);
1056         }
1057 #else
1058         if (!(lead & 1))
1059         {
1060             memcpy (&attrSet, src, sizeof(attrSet));
1061             src += sizeof(attrSet);
1062         }
1063         if (!(lead & 2))
1064         {
1065             memcpy (&attrUse, src, sizeof(attrUse));
1066             src += sizeof(attrUse);
1067         }
1068 #endif
1069         wstart = src;
1070         while (*src++)
1071             ;
1072         if (lead & 60)
1073             seqno += ((lead>>2) & 15)-1;
1074         else
1075         {
1076             memcpy (&seqno, src, sizeof(seqno));
1077             src += sizeof(seqno);
1078         }
1079         if (
1080 #if SU_SCHEME
1081             ch == chS
1082 #else
1083             attrUseS == attrUse && attrSetS == attrSet
1084 #endif
1085             )
1086         {
1087             int woff;
1088
1089
1090             if (startSeq == -1)
1091                 startSeq = seqno;
1092             woff = seqno - startSeq;
1093             if (woff >= 0 && woff < 31)
1094                 ws[woff] = wstart;
1095         }
1096
1097         off = src - reckeys->buf;
1098     }
1099     assert (off == reckeys->buf_used);
1100     return ws;
1101 }
1102
1103 struct file_read_info {
1104     off_t file_max;         /* maximum offset so far */
1105     off_t file_offset;      /* current offset */
1106     off_t file_moffset;     /* offset of rec/rec boundary */
1107     int file_more;
1108     int fd;
1109     char *sdrbuf;
1110     int sdrmax;
1111 };
1112
1113 static struct file_read_info *file_read_start (int fd)
1114 {
1115     struct file_read_info *fi = (struct file_read_info *)
1116         xmalloc (sizeof(*fi));
1117
1118     fi->fd = fd;
1119     fi->file_max = 0;
1120     fi->file_moffset = 0;
1121     fi->sdrbuf = 0;
1122     fi->sdrmax = 0;
1123     return fi;
1124 }
1125
1126 static void file_read_stop (struct file_read_info *fi)
1127 {
1128     xfree (fi);
1129 }
1130
1131 static off_t file_seek (void *handle, off_t offset)
1132 {
1133     struct file_read_info *p = (struct file_read_info *) handle;
1134     p->file_offset = offset;
1135     if (p->sdrbuf)
1136         return offset;
1137     return lseek (p->fd, offset, SEEK_SET);
1138 }
1139
1140 static off_t file_tell (void *handle)
1141 {
1142     struct file_read_info *p = (struct file_read_info *) handle;
1143     return p->file_offset;
1144 }
1145
1146 static int file_read (void *handle, char *buf, size_t count)
1147 {
1148     struct file_read_info *p = (struct file_read_info *) handle;
1149     int fd = p->fd;
1150     int r;
1151     if (p->sdrbuf)
1152     {
1153         r = count;
1154         if (r > p->sdrmax - p->file_offset)
1155             r = p->sdrmax - p->file_offset;
1156         if (r)
1157             memcpy (buf, p->sdrbuf + p->file_offset, r);
1158     }
1159     else
1160         r = read (fd, buf, count);
1161     if (r > 0)
1162     {
1163         p->file_offset += r;
1164         if (p->file_offset > p->file_max)
1165             p->file_max = p->file_offset;
1166     }
1167     return r;
1168 }
1169
1170 static void file_begin (void *handle)
1171 {
1172     struct file_read_info *p = (struct file_read_info *) handle;
1173
1174     p->file_offset = p->file_moffset;
1175     if (!p->sdrbuf && p->file_moffset)
1176         lseek (p->fd, p->file_moffset, SEEK_SET);
1177     p->file_more = 0;
1178 }
1179
1180 static void file_end (void *handle, off_t offset)
1181 {
1182     struct file_read_info *p = (struct file_read_info *) handle;
1183
1184     assert (p->file_more == 0);
1185     p->file_more = 1;
1186     p->file_moffset = offset;
1187 }
1188
1189 static char *fileMatchStr (struct recKeys *reckeys, struct recordGroup *rGroup,
1190                            const char *fname, const char *spec)
1191 {
1192     static char dstBuf[2048];
1193     char *dst = dstBuf;
1194     const char *s = spec;
1195     static const char **w;
1196
1197     while (1)
1198     {
1199         while (*s == ' ' || *s == '\t')
1200             s++;
1201         if (!*s)
1202             break;
1203         if (*s == '(')
1204         {
1205             char attset_str[64], attname_str[64];
1206             data1_attset *attset;
1207             int i;
1208             char matchFlag[32];
1209             int attSet = 1, attUse = 1;
1210             int first = 1;
1211
1212             s++;
1213             for (i = 0; *s && *s != ',' && *s != ')'; s++)
1214                 if (i < 63)
1215                     attset_str[i++] = *s;
1216             attset_str[i] = '\0';
1217
1218             if (*s == ',')
1219             {
1220                 s++;
1221                 for (i = 0; *s && *s != ')'; s++)
1222                     if (i < 63)
1223                         attname_str[i++] = *s;
1224                 attname_str[i] = '\0';
1225             }
1226             
1227             if ((attset = data1_get_attset (rGroup->dh, attset_str)))
1228             {
1229                 data1_att *att;
1230                 attSet = attset->reference;
1231                 att = data1_getattbyname(rGroup->dh, attset, attname_str);
1232                 if (att)
1233                     attUse = att->value;
1234                 else
1235                     attUse = atoi (attname_str);
1236             }
1237             w = searchRecordKey (reckeys, attSet, attUse);
1238             assert (w);
1239
1240             if (*s == ')')
1241             {
1242                 for (i = 0; i<32; i++)
1243                     matchFlag[i] = 1;
1244             }
1245             else
1246             {
1247                 logf (LOG_WARN, "Missing ) in match criteria %s in group %s",
1248                       spec, rGroup->groupName ? rGroup->groupName : "none");
1249                 return NULL;
1250             }
1251             s++;
1252
1253             for (i = 0; i<32; i++)
1254                 if (matchFlag[i] && w[i])
1255                 {
1256                     if (first)
1257                     {
1258                         *dst++ = ' ';
1259                         first = 0;
1260                     }
1261                     strcpy (dst, w[i]);
1262                     dst += strlen(w[i]);
1263                 }
1264             if (first)
1265             {
1266                 logf (LOG_WARN, "Record didn't contain match"
1267                       " fields in (%s,%s)", attset_str, attname_str);
1268                 return NULL;
1269             }
1270         }
1271         else if (*s == '$')
1272         {
1273             int spec_len;
1274             char special[64];
1275             const char *spec_src = NULL;
1276             const char *s1 = ++s;
1277             while (*s1 && *s1 != ' ' && *s1 != '\t')
1278                 s1++;
1279
1280             spec_len = s1 - s;
1281             if (spec_len > 63)
1282                 spec_len = 63;
1283             memcpy (special, s, spec_len);
1284             special[spec_len] = '\0';
1285             s = s1;
1286
1287             if (!strcmp (special, "group"))
1288                 spec_src = rGroup->groupName;
1289             else if (!strcmp (special, "database"))
1290                 spec_src = rGroup->databaseName;
1291             else if (!strcmp (special, "filename"))
1292                 spec_src = fname;
1293             else if (!strcmp (special, "type"))
1294                 spec_src = rGroup->recordType;
1295             else 
1296                 spec_src = NULL;
1297             if (spec_src)
1298             {
1299                 strcpy (dst, spec_src);
1300                 dst += strlen (spec_src);
1301             }
1302         }
1303         else if (*s == '\"' || *s == '\'')
1304         {
1305             int stopMarker = *s++;
1306             char tmpString[64];
1307             int i = 0;
1308
1309             while (*s && *s != stopMarker)
1310             {
1311                 if (i < 63)
1312                     tmpString[i++] = *s++;
1313             }
1314             if (*s)
1315                 s++;
1316             tmpString[i] = '\0';
1317             strcpy (dst, tmpString);
1318             dst += strlen (tmpString);
1319         }
1320         else
1321         {
1322             logf (LOG_WARN, "Syntax error in match criteria %s in group %s",
1323                   spec, rGroup->groupName ? rGroup->groupName : "none");
1324             return NULL;
1325         }
1326         *dst++ = 1;
1327     }
1328     if (dst == dstBuf)
1329     {
1330         logf (LOG_WARN, "No match criteria for record %s in group %s",
1331               fname, rGroup->groupName ? rGroup->groupName : "none");
1332         return NULL;
1333     }
1334     *dst = '\0';
1335     return dstBuf;
1336 }
1337
1338 struct recordLogInfo {
1339     const char *fname;
1340     int recordOffset;
1341     struct recordGroup *rGroup;
1342 };
1343      
1344 static void recordLogPreamble (int level, const char *msg, void *info)
1345 {
1346     struct recordLogInfo *p = (struct recordLogInfo *) info;
1347     FILE *outf = yaz_log_file ();
1348
1349     if (level & LOG_LOG)
1350         return ;
1351     fprintf (outf, "File %s, offset %d, type %s\n",
1352              p->rGroup->recordType, p->recordOffset, p->fname);
1353     log_event_start (NULL, NULL);
1354 }
1355
1356 void addSchema (struct recExtractCtrl *p, Odr_oid *oid)
1357 {
1358     zebraExplain_addSchema (zti, oid);
1359 }
1360
1361 static int recordExtract (SYSNO *sysno, const char *fname,
1362                           struct recordGroup *rGroup, int deleteFlag,
1363                           struct file_read_info *fi,
1364                           RecType recType, char *subType, void *clientData)
1365 {
1366     RecordAttr *recordAttr;
1367     int r;
1368     char *matchStr;
1369     SYSNO sysnotmp;
1370     Record rec;
1371     struct recordLogInfo logInfo;
1372     off_t recordOffset = 0;
1373
1374     if (fi->fd != -1)
1375     {
1376         struct recExtractCtrl extractCtrl;
1377
1378         /* we are going to read from a file, so prepare the extraction */
1379         int i;
1380
1381         reckeys.buf_used = 0;
1382         reckeys.prevAttrUse = -1;
1383         reckeys.prevAttrSet = -1;
1384         reckeys.prevSeqNo = 0;
1385         
1386         recordOffset = fi->file_moffset;
1387         extractCtrl.offset = fi->file_moffset;
1388         extractCtrl.readf = file_read;
1389         extractCtrl.seekf = file_seek;
1390         extractCtrl.tellf = file_tell;
1391         extractCtrl.endf = file_end;
1392         extractCtrl.fh = fi;
1393         extractCtrl.subType = subType;
1394         extractCtrl.init = wordInit;
1395         extractCtrl.tokenAdd = addRecordKey;
1396         extractCtrl.schemaAdd = addSchema;
1397         extractCtrl.dh = rGroup->dh;
1398         for (i = 0; i<256; i++)
1399         {
1400             if (zebra_maps_is_positioned(rGroup->zebra_maps, i))
1401                 extractCtrl.seqno[i] = 1;
1402             else
1403                 extractCtrl.seqno[i] = 0;
1404         }
1405         extractCtrl.zebra_maps = rGroup->zebra_maps;
1406         extractCtrl.flagShowRecords = !rGroup->flagRw;
1407
1408         if (!rGroup->flagRw)
1409             printf ("File: %s " PRINTF_OFF_T "\n", fname, recordOffset);
1410
1411         logInfo.fname = fname;
1412         logInfo.recordOffset = recordOffset;
1413         logInfo.rGroup = rGroup;
1414         log_event_start (recordLogPreamble, &logInfo);
1415
1416         r = (*recType->extract)(clientData, &extractCtrl);
1417
1418         log_event_start (NULL, NULL);
1419
1420         if (r == RECCTRL_EXTRACT_EOF)
1421             return 0;
1422         else if (r == RECCTRL_EXTRACT_ERROR)
1423         {
1424             /* error occured during extraction ... */
1425             if (rGroup->flagRw &&
1426                 records_processed < rGroup->fileVerboseLimit)
1427             {
1428                 logf (LOG_WARN, "fail %s %s " PRINTF_OFF_T, rGroup->recordType,
1429                       fname, recordOffset);
1430             }
1431             return 0;
1432         }
1433         if (reckeys.buf_used == 0)
1434         {
1435             /* the extraction process returned no information - the record
1436                is probably empty - unless flagShowRecords is in use */
1437             if (!rGroup->flagRw)
1438                 return 1;
1439             
1440             logf (LOG_WARN, "empty %s %s " PRINTF_OFF_T, rGroup->recordType,
1441                   fname, recordOffset);
1442             return 1;
1443         }
1444     }
1445
1446     /* perform match if sysno not known and if match criteria is specified */
1447        
1448     matchStr = NULL;
1449     if (!sysno) 
1450     {
1451         sysnotmp = 0;
1452         sysno = &sysnotmp;
1453         if (rGroup->recordId && *rGroup->recordId)
1454         {
1455             char *rinfo;
1456         
1457             matchStr = fileMatchStr (&reckeys, rGroup, fname, 
1458                                      rGroup->recordId);
1459             if (matchStr)
1460             {
1461                 rinfo = dict_lookup (matchDict, matchStr);
1462                 if (rinfo)
1463                     memcpy (sysno, rinfo+1, sizeof(*sysno));
1464             }
1465             else
1466             {
1467                 logf (LOG_WARN, "Bad match criteria");
1468                 return 0;
1469             }
1470         }
1471     }
1472
1473     if (! *sysno)
1474     {
1475         /* new record */
1476         if (deleteFlag)
1477         {
1478             logf (LOG_LOG, "delete %s %s " PRINTF_OFF_T, rGroup->recordType,
1479                   fname, recordOffset);
1480             logf (LOG_WARN, "cannot delete record above (seems new)");
1481             return 1;
1482         }
1483         if (records_processed < rGroup->fileVerboseLimit)
1484             logf (LOG_LOG, "add %s %s " PRINTF_OFF_T, rGroup->recordType,
1485                   fname, recordOffset);
1486         rec = rec_new (records);
1487
1488         *sysno = rec->sysno;
1489
1490         recordAttr = rec_init_attr (zti, rec);
1491
1492         if (matchStr)
1493         {
1494             dict_insert (matchDict, matchStr, sizeof(*sysno), sysno);
1495         }
1496         flushRecordKeys (*sysno, 1, &reckeys);
1497         flushSortKeys (*sysno, 1);
1498
1499         records_inserted++;
1500     }
1501     else
1502     {
1503         /* record already exists */
1504         struct recKeys delkeys;
1505
1506         rec = rec_get (records, *sysno);
1507         assert (rec);
1508         
1509         recordAttr = rec_init_attr (zti, rec);
1510
1511         if (recordAttr->runNumber == zebraExplain_runNumberIncrement (zti, 0))
1512         {
1513             logf (LOG_LOG, "skipped %s %s " PRINTF_OFF_T, rGroup->recordType,
1514                   fname, recordOffset);
1515             rec_rm (&rec);
1516             logRecord (0);
1517             return 1;
1518         }
1519         delkeys.buf_used = rec->size[recInfo_delKeys];
1520         delkeys.buf = rec->info[recInfo_delKeys];
1521         flushSortKeys (*sysno, 0);
1522         flushRecordKeys (*sysno, 0, &delkeys);
1523         if (deleteFlag)
1524         {
1525             /* record going to be deleted */
1526             if (!delkeys.buf_used)
1527             {
1528                 logf (LOG_LOG, "delete %s %s " PRINTF_OFF_T,
1529                       rGroup->recordType, fname, recordOffset);
1530                 logf (LOG_WARN, "cannot delete file above, storeKeys false");
1531             }
1532             else
1533             {
1534                 if (records_processed < rGroup->fileVerboseLimit)
1535                     logf (LOG_LOG, "delete %s %s " PRINTF_OFF_T,
1536                          rGroup->recordType, fname, recordOffset);
1537                 records_deleted++;
1538                 if (matchStr)
1539                     dict_delete (matchDict, matchStr);
1540                 rec_del (records, &rec);
1541             }
1542             rec_rm (&rec);
1543             logRecord (0);
1544             return 1;
1545         }
1546         else
1547         {
1548             /* record going to be updated */
1549             if (!delkeys.buf_used)
1550             {
1551                 logf (LOG_LOG, "update %s %s " PRINTF_OFF_T,
1552                       rGroup->recordType, fname, recordOffset);
1553                 logf (LOG_WARN, "cannot update file above, storeKeys false");
1554             }
1555             else
1556             {
1557                 if (records_processed < rGroup->fileVerboseLimit)
1558                     logf (LOG_LOG, "update %s %s " PRINTF_OFF_T,
1559                         rGroup->recordType, fname, recordOffset);
1560                 flushRecordKeys (*sysno, 1, &reckeys);
1561                 records_updated++;
1562             }
1563         }
1564     }
1565     /* update file type */
1566     xfree (rec->info[recInfo_fileType]);
1567     rec->info[recInfo_fileType] =
1568         rec_strdup (rGroup->recordType, &rec->size[recInfo_fileType]);
1569
1570     /* update filename */
1571     xfree (rec->info[recInfo_filename]);
1572     rec->info[recInfo_filename] =
1573         rec_strdup (fname, &rec->size[recInfo_filename]);
1574
1575     /* update delete keys */
1576     xfree (rec->info[recInfo_delKeys]);
1577     if (reckeys.buf_used > 0 && rGroup->flagStoreKeys == 1)
1578     {
1579 #if 1
1580         rec->size[recInfo_delKeys] = reckeys.buf_used;
1581         rec->info[recInfo_delKeys] = reckeys.buf;
1582         reckeys.buf = NULL;
1583         reckeys.buf_max = 0;
1584 #else
1585         rec->info[recInfo_delKeys] = xmalloc (reckeys.buf_used);
1586         rec->size[recInfo_delKeys] = reckeys.buf_used;
1587         memcpy (rec->info[recInfo_delKeys], reckeys.buf,
1588                 rec->size[recInfo_delKeys]);
1589 #endif
1590     }
1591     else
1592     {
1593         rec->info[recInfo_delKeys] = NULL;
1594         rec->size[recInfo_delKeys] = 0;
1595     }
1596
1597     /* save file size of original record */
1598     zebraExplain_recordBytesIncrement (zti, - recordAttr->recordSize);
1599     recordAttr->recordSize = fi->file_moffset - recordOffset;
1600     if (!recordAttr->recordSize)
1601         recordAttr->recordSize = fi->file_max - recordOffset;
1602     zebraExplain_recordBytesIncrement (zti, recordAttr->recordSize);
1603
1604     /* set run-number for this record */
1605     recordAttr->runNumber = zebraExplain_runNumberIncrement (zti, 0);
1606
1607     /* update store data */
1608     xfree (rec->info[recInfo_storeData]);
1609     if (rGroup->flagStoreData == 1)
1610     {
1611         rec->size[recInfo_storeData] = recordAttr->recordSize;
1612         rec->info[recInfo_storeData] = (char *)
1613             xmalloc (recordAttr->recordSize);
1614         if (lseek (fi->fd, recordOffset, SEEK_SET) < 0)
1615         {
1616             logf (LOG_ERRNO|LOG_FATAL, "seek to " PRINTF_OFF_T " in %s",
1617                   recordOffset, fname);
1618             exit (1);
1619         }
1620         if (read (fi->fd, rec->info[recInfo_storeData], recordAttr->recordSize)
1621             < recordAttr->recordSize)
1622         {
1623             logf (LOG_ERRNO|LOG_FATAL, "read %d bytes of %s",
1624                   recordAttr->recordSize, fname);
1625             exit (1);
1626         }
1627     }
1628     else
1629     {
1630         rec->info[recInfo_storeData] = NULL;
1631         rec->size[recInfo_storeData] = 0;
1632     }
1633     /* update database name */
1634     xfree (rec->info[recInfo_databaseName]);
1635     rec->info[recInfo_databaseName] =
1636         rec_strdup (rGroup->databaseName, &rec->size[recInfo_databaseName]); 
1637
1638     /* update offset */
1639     recordAttr->recordOffset = recordOffset;
1640     
1641     /* commit this record */
1642     rec_put (records, &rec);
1643     logRecord (0);
1644     return 1;
1645 }
1646
1647 int fileExtract (SYSNO *sysno, const char *fname, 
1648                  const struct recordGroup *rGroupP, int deleteFlag)
1649 {
1650     int r, i, fd;
1651     char gprefix[128];
1652     char ext[128];
1653     char ext_res[128];
1654     char subType[128];
1655     RecType recType;
1656     struct recordGroup rGroupM;
1657     struct recordGroup *rGroup = &rGroupM;
1658     struct file_read_info *fi;
1659     void *clientData;
1660
1661     memcpy (rGroup, rGroupP, sizeof(*rGroupP));
1662    
1663     if (!rGroup->groupName || !*rGroup->groupName)
1664         *gprefix = '\0';
1665     else
1666         sprintf (gprefix, "%s.", rGroup->groupName);
1667
1668     logf (LOG_DEBUG, "fileExtract %s", fname);
1669
1670     /* determine file extension */
1671     *ext = '\0';
1672     for (i = strlen(fname); --i >= 0; )
1673         if (fname[i] == '/')
1674             break;
1675         else if (fname[i] == '.')
1676         {
1677             strcpy (ext, fname+i+1);
1678             break;
1679         }
1680     /* determine file type - depending on extension */
1681     if (!rGroup->recordType)
1682     {
1683         sprintf (ext_res, "%srecordType.%s", gprefix, ext);
1684         if (!(rGroup->recordType = res_get (common_resource, ext_res)))
1685         {
1686             sprintf (ext_res, "%srecordType", gprefix);
1687             rGroup->recordType = res_get (common_resource, ext_res);
1688         }
1689     }
1690     if (!rGroup->recordType)
1691     {
1692         if (records_processed < rGroup->fileVerboseLimit)
1693             logf (LOG_LOG, "? %s", fname);
1694         return 0;
1695     }
1696     if (!*rGroup->recordType)
1697         return 0;
1698     if (!(recType =
1699           recType_byName (rGroup->recTypes, rGroup->recordType, subType,
1700                           &clientData)))
1701     {
1702         logf (LOG_WARN, "No such record type: %s", rGroup->recordType);
1703         return 0;
1704     }
1705
1706     /* determine match criteria */
1707     if (!rGroup->recordId)
1708     {
1709         sprintf (ext_res, "%srecordId.%s", gprefix, ext);
1710         rGroup->recordId = res_get (common_resource, ext_res);
1711     }
1712
1713     /* determine database name */
1714     if (!rGroup->databaseName)
1715     {
1716         sprintf (ext_res, "%sdatabase.%s", gprefix, ext);
1717         if (!(rGroup->databaseName = res_get (common_resource, ext_res)))
1718         {
1719             sprintf (ext_res, "%sdatabase", gprefix);
1720             rGroup->databaseName = res_get (common_resource, ext_res);
1721         }
1722     }
1723     if (!rGroup->databaseName)
1724         rGroup->databaseName = "Default";
1725
1726     /* determine if explain database */
1727     
1728     sprintf (ext_res, "%sexplainDatabase", gprefix);
1729     rGroup->explainDatabase =
1730         atoi (res_get_def (common_resource, ext_res, "0"));
1731
1732     /* announce database */
1733     if (zebraExplain_curDatabase (zti, rGroup->databaseName))
1734     {
1735         if (zebraExplain_newDatabase (zti, rGroup->databaseName,
1736                                       rGroup->explainDatabase))
1737             return 0;
1738     }
1739
1740     if (rGroup->flagStoreData == -1)
1741     {
1742         const char *sval;
1743         sprintf (ext_res, "%sstoreData.%s", gprefix, ext);
1744         if (!(sval = res_get (common_resource, ext_res)))
1745         {
1746             sprintf (ext_res, "%sstoreData", gprefix);
1747             sval = res_get (common_resource, ext_res);
1748         }
1749         if (sval)
1750             rGroup->flagStoreData = atoi (sval);
1751     }
1752     if (rGroup->flagStoreData == -1)
1753         rGroup->flagStoreData = 0;
1754
1755     if (rGroup->flagStoreKeys == -1)
1756     {
1757         const char *sval;
1758
1759         sprintf (ext_res, "%sstoreKeys.%s", gprefix, ext);
1760         if (!(sval = res_get (common_resource, ext_res)))
1761         {
1762             sprintf (ext_res, "%sstoreKeys", gprefix);
1763             sval = res_get (common_resource, ext_res);
1764         }
1765         if (sval)
1766             rGroup->flagStoreKeys = atoi (sval);
1767     }
1768     if (rGroup->flagStoreKeys == -1)
1769         rGroup->flagStoreKeys = 0;
1770
1771     if (sysno && deleteFlag)
1772         fd = -1;
1773     else
1774     {
1775         if ((fd = open (fname, O_BINARY|O_RDONLY)) == -1)
1776         {
1777             logf (LOG_WARN|LOG_ERRNO, "open %s", fname);
1778             return 0;
1779         }
1780     }
1781     fi = file_read_start (fd);
1782     do
1783     {
1784         file_begin (fi);
1785         r = recordExtract (sysno, fname, rGroup, deleteFlag, fi,
1786                            recType, subType, clientData);
1787     } while (r && !sysno && fi->file_more);
1788     file_read_stop (fi);
1789     if (fd != -1)
1790         close (fd);
1791     return r;
1792 }
1793
1794 static int explain_extract (void *handle, Record rec, data1_node *n)
1795 {
1796     struct recordGroup *rGroup = (struct recordGroup*) handle;
1797     struct recExtractCtrl extractCtrl;
1798     int i;
1799
1800     if (zebraExplain_curDatabase (zti, rec->info[recInfo_databaseName]))
1801     {
1802         if (zebraExplain_newDatabase (zti, rec->info[recInfo_databaseName], 0))
1803             abort ();
1804     }
1805
1806     reckeys.buf_used = 0;
1807     reckeys.prevAttrUse = -1;
1808     reckeys.prevAttrSet = -1;
1809     reckeys.prevSeqNo = 0;
1810     
1811     extractCtrl.init = wordInit;
1812     extractCtrl.tokenAdd = addRecordKey;
1813     extractCtrl.schemaAdd = addSchema;
1814     extractCtrl.dh = rGroup->dh;
1815     for (i = 0; i<256; i++)
1816         extractCtrl.seqno[i] = 0;
1817     extractCtrl.zebra_maps = rGroup->zebra_maps;
1818     extractCtrl.flagShowRecords = !rGroup->flagRw;
1819     
1820     grs_extract_tree(&extractCtrl, n);
1821
1822     logf (LOG_DEBUG, "flush explain record, sysno=%d", rec->sysno);
1823
1824     if (rec->size[recInfo_delKeys])
1825     {
1826         struct recKeys delkeys;
1827
1828         delkeys.buf_used = rec->size[recInfo_delKeys];
1829         delkeys.buf = rec->info[recInfo_delKeys];
1830         flushSortKeys (rec->sysno, 0);
1831         flushRecordKeys (rec->sysno, 0, &delkeys);
1832     }
1833     flushRecordKeys (rec->sysno, 1, &reckeys);
1834     flushSortKeys (rec->sysno, 1);
1835
1836     xfree (rec->info[recInfo_delKeys]);
1837     rec->size[recInfo_delKeys] = reckeys.buf_used;
1838     rec->info[recInfo_delKeys] = reckeys.buf;
1839     reckeys.buf = NULL;
1840     reckeys.buf_max = 0;
1841
1842     return 0;
1843 }