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