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