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