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