Zebra version corresponds to YAZ version 1.4.
[idzebra-moved-to-github.git] / index / extract.c
1 /*
2  * Copyright (C) 1994-1997, Index Data I/S 
3  * All rights reserved.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * $Log: extract.c,v $
7  * Revision 1.75  1997-09-17 12:19:12  adam
8  * Zebra version corresponds to YAZ version 1.4.
9  * Changed Zebra server so that it doesn't depend on global common_resource.
10  *
11  * Revision 1.74  1997/09/09 13:38:06  adam
12  * Partial port to WIN95/NT.
13  *
14  * Revision 1.73  1997/09/04 13:57:20  adam
15  * New file extract/retrieve method tellf (added).
16  * Added O_BINARY for open calls.
17  *
18  * Revision 1.72  1997/07/15 16:32:29  adam
19  * Bug fix: Match handler didn't terminate the resulting string!
20  *
21  * Revision 1.71  1997/07/15 16:28:41  adam
22  * Bug fix: storeData didn't work with files with multiple records.
23  * Bug fix: fixed memory management with records; not really well
24  *  thought through.
25  *
26  * Revision 1.70  1997/07/01 13:00:42  adam
27  * Bug fix in routine searchRecordKey: uninitialized variables.
28  *
29  * Revision 1.69  1997/04/29 09:26:03  adam
30  * Bug fix: generic recordId handling didn't work for compressed internal
31  * keys.
32  *
33  * Revision 1.68  1997/02/12 20:39:45  adam
34  * Implemented options -f <n> that limits the log to the first <n>
35  * records.
36  * Changed some log messages also.
37  *
38  * Revision 1.67  1996/11/15 15:02:14  adam
39  * Minor changes regarding logging.
40  *
41  * Revision 1.66  1996/11/14  09:52:21  adam
42  * Strings in record keys bound by IT_MAX_WORD.
43  *
44  * Revision 1.65  1996/11/14  08:57:56  adam
45  * Reduction of storeKeys area.
46  *
47  * Revision 1.64  1996/11/08 11:10:16  adam
48  * Buffers used during file match got bigger.
49  * Compressed ISAM support everywhere.
50  * Bug fixes regarding masking characters in queries.
51  * Redesigned Regexp-2 queries.
52  *
53  * Revision 1.63  1996/10/29 14:09:39  adam
54  * Use of cisam system - enabled if setting isamc is 1.
55  *
56  * Revision 1.62  1996/10/11 10:57:01  adam
57  * New module recctrl. Used to manage records (extract/retrieval).
58  * Several files have been moved to the recctrl sub directory.
59  *
60  * Revision 1.61  1996/06/06 12:08:37  quinn
61  * Added showRecord function
62  *
63  * Revision 1.60  1996/06/04  10:18:12  adam
64  * Search/scan uses character mapping module.
65  *
66  * Revision 1.59  1996/05/14  15:47:07  adam
67  * Cleanup of various buffer size entities.
68  *
69  * Revision 1.58  1996/05/14  06:16:38  adam
70  * Compact use/set bytes used in search service.
71  *
72  * Revision 1.57  1996/05/13 14:23:04  adam
73  * Work on compaction of set/use bytes in dictionary.
74  *
75  * Revision 1.56  1996/05/09  09:54:42  adam
76  * Server supports maps from one logical attributes to a list of physical
77  * attributes.
78  * The extraction process doesn't make space consuming 'any' keys.
79  *
80  * Revision 1.55  1996/05/09  07:28:55  quinn
81  * Work towards phrases and multiple registers
82  *
83  * Revision 1.54  1996/05/01  13:46:35  adam
84  * First work on multiple records in one file.
85  * New option, -offset, to the "unread" command in the filter module.
86  *
87  * Revision 1.53  1996/04/26  12:09:43  adam
88  * Added a few comments.
89  *
90  * Revision 1.52  1996/04/25  13:27:57  adam
91  * Function recordExtract modified so that files with no keys (possibly empty)
92  * are ignored.
93  *
94  * Revision 1.51  1996/03/19  11:08:42  adam
95  * Bug fix: Log preamble wasn't always turned off after recordExtract.
96  *
97  * Revision 1.50  1996/02/12  18:45:36  adam
98  * New fileVerboseFlag in record group control.
99  *
100  * Revision 1.49  1996/02/05  12:29:57  adam
101  * Logging reduced a bit.
102  * The remaining running time is estimated during register merge.
103  *
104  * Revision 1.48  1996/02/01  20:53:26  adam
105  * The temporary per-record keys are compacted a little, and duplication
106  * of the per-records keys are avoided when they are saved in the record
107  * information buffer.
108  *
109  * Revision 1.47  1996/01/17  14:57:48  adam
110  * Prototype changed for reader functions in extract/retrieve. File
111  *  is identified by 'void *' instead of 'int.
112  *
113  * Revision 1.46  1995/12/15  14:57:16  adam
114  * Bug fix.
115  *
116  * Revision 1.45  1995/12/15  12:37:41  adam
117  * In addRecordKeyAny: Writes key only when attrSet != -1.
118  *
119  * Revision 1.44  1995/12/12  16:00:54  adam
120  * System call sync(2) used after update/commit.
121  * Locking (based on fcntl) uses F_EXLCK and F_SHLCK instead of F_WRLCK
122  * and F_RDLCK.
123  *
124  * Revision 1.43  1995/12/11  09:12:46  adam
125  * The rec_get function returns NULL if record doesn't exist - will
126  * happen in the server if the result set records have been deleted since
127  * the creation of the set (i.e. the search).
128  * The server saves a result temporarily if it is 'volatile', i.e. the
129  * set is register dependent.
130  *
131  * Revision 1.42  1995/12/07  17:38:46  adam
132  * Work locking mechanisms for concurrent updates/commit.
133  *
134  * Revision 1.41  1995/12/06  16:06:42  adam
135  * Better diagnostics. Work on 'real' dictionary deletion.
136  *
137  * Revision 1.40  1995/12/05  16:57:40  adam
138  * More work on regular patterns.
139  *
140  * Revision 1.39  1995/12/05  13:20:18  adam
141  * Bug fix: file_read sometimes returned early EOF.
142  *
143  * Revision 1.38  1995/12/04  17:59:21  adam
144  * More work on regular expression conversion.
145  *
146  * Revision 1.37  1995/12/04  14:22:27  adam
147  * Extra arg to recType_byName.
148  * Started work on new regular expression parsed input to
149  * structured records.
150  *
151  * Revision 1.36  1995/11/30  08:34:29  adam
152  * Started work on commit facility.
153  * Changed a few malloc/free to xmalloc/xfree.
154  *
155  * Revision 1.35  1995/11/28  14:26:21  adam
156  * Bug fix: recordId with constant wasn't right.
157  * Bug fix: recordId dictionary entry wasn't deleted when needed.
158  *
159  * Revision 1.34  1995/11/28  09:09:38  adam
160  * Zebra config renamed.
161  * Use setting 'recordId' to identify record now.
162  * Bug fix in recindex.c: rec_release_blocks was invokeded even
163  * though the blocks were already released.
164  * File traversal properly deletes records when needed.
165  *
166  * Revision 1.33  1995/11/27  09:56:20  adam
167  * Record info elements better enumerated. Internal store of records.
168  *
169  * Revision 1.32  1995/11/25  10:24:05  adam
170  * More record fields - they are enumerated now.
171  * New options: flagStoreData flagStoreKey.
172  *
173  * Revision 1.31  1995/11/24  11:31:35  adam
174  * Commands add & del read filenames from stdin if source directory is
175  * empty.
176  * Match criteria supports 'constant' strings.
177  *
178  * Revision 1.30  1995/11/22  17:19:16  adam
179  * Record management uses the bfile system.
180  *
181  * Revision 1.29  1995/11/21  15:01:14  adam
182  * New general match criteria implemented.
183  * New feature: document groups.
184  *
185  * Revision 1.28  1995/11/21  09:20:30  adam
186  * Yet more work on record match.
187  *
188  * Revision 1.27  1995/11/20  16:59:45  adam
189  * New update method: the 'old' keys are saved for each records.
190  *
191  * Revision 1.26  1995/11/20  11:56:24  adam
192  * Work on new traversal.
193  *
194  * Revision 1.25  1995/11/16  15:34:54  adam
195  * Uses new record management system in both indexer and server.
196  *
197  * Revision 1.24  1995/11/15  19:13:08  adam
198  * Work on record management.
199  *
200  * Revision 1.23  1995/10/27  14:00:10  adam
201  * Implemented detection of database availability.
202  *
203  * Revision 1.22  1995/10/17  18:02:07  adam
204  * New feature: databases. Implemented as prefix to words in dictionary.
205  *
206  * Revision 1.21  1995/10/10  12:24:38  adam
207  * Temporary sort files are compressed.
208  *
209  * Revision 1.20  1995/10/06  13:52:05  adam
210  * Bug fixes. Handler may abort further scanning.
211  *
212  * Revision 1.19  1995/10/04  12:55:16  adam
213  * Bug fix in ranked search. Use=Any keys inserted.
214  *
215  * Revision 1.18  1995/10/04  09:37:08  quinn
216  * Fixed bug.
217  *
218  * Revision 1.17  1995/10/03  14:28:57  adam
219  * Buffered read in extract works.
220  *
221  * Revision 1.16  1995/10/03  14:28:45  adam
222  * Work on more effecient read handler in extract.
223  *
224  * Revision 1.15  1995/10/02  15:42:53  adam
225  * Extract uses file descriptors instead of FILE pointers.
226  *
227  * Revision 1.14  1995/10/02  15:29:13  adam
228  * More logging in file_extract.
229  *
230  * Revision 1.13  1995/09/29  14:01:39  adam
231  * Bug fixes.
232  *
233  * Revision 1.12  1995/09/28  14:22:56  adam
234  * Sort uses smaller temporary files.
235  *
236  * Revision 1.11  1995/09/28  12:10:31  adam
237  * Bug fixes. Field prefix used in queries.
238  *
239  * Revision 1.10  1995/09/28  09:19:41  adam
240  * xfree/xmalloc used everywhere.
241  * Extract/retrieve method seems to work for text records.
242  *
243  * Revision 1.9  1995/09/27  12:22:28  adam
244  * More work on extract in record control.
245  * Field name is not in isam keys but in prefix in dictionary words.
246  *
247  * Revision 1.8  1995/09/14  07:48:22  adam
248  * Record control management.
249  *
250  * Revision 1.7  1995/09/11  13:09:32  adam
251  * More work on relevance feedback.
252  *
253  * Revision 1.6  1995/09/08  14:52:27  adam
254  * Minor changes. Dictionary is lower case now.
255  *
256  * Revision 1.5  1995/09/06  16:11:16  adam
257  * Option: only one word key per file.
258  *
259  * Revision 1.4  1995/09/05  15:28:39  adam
260  * More work on search engine.
261  *
262  * Revision 1.3  1995/09/04  12:33:41  adam
263  * Various cleanup. YAZ util used instead.
264  *
265  * Revision 1.2  1995/09/04  09:10:34  adam
266  * More work on index add/del/update.
267  * Merge sort implemented.
268  * Initial work on z39 server.
269  *
270  * Revision 1.1  1995/09/01  14:06:35  adam
271  * Split of work into more files.
272  *
273  */
274 #include <stdio.h>
275 #include <assert.h>
276 #ifdef WINDOWS
277 #include <io.h>
278 #else
279 #include <unistd.h>
280 #endif
281 #include <fcntl.h>
282
283 #include <recctrl.h>
284 #include "index.h"
285
286 #include "zinfo.h"
287
288 static Dict matchDict;
289
290 static Records records = NULL;
291
292 static char **key_buf;
293 static size_t ptr_top;
294 static size_t ptr_i;
295 static size_t key_buf_used;
296 static int key_file_no;
297
298 static int records_inserted = 0;
299 static int records_updated = 0;
300 static int records_deleted = 0;
301 static int records_processed = 0;
302
303 static ZebTargetInfo *zti = NULL;
304
305 static void logRecord (int showFlag)
306 {
307     if (!showFlag)
308         ++records_processed;
309     if (showFlag || !(records_processed % 1000))
310     {
311         logf (LOG_LOG, "Records: %7d i/u/d %d/%d/%d", 
312               records_processed, records_inserted, records_updated,
313               records_deleted);
314     }
315 }
316
317 void key_open (BFiles bfs, int mem)
318 {
319     if (!mem)
320         mem = atoi(res_get_def (common_resource, "memMax", "4"))*1024*1024;
321     if (mem < 50000)
322         mem = 50000;
323     key_buf = xmalloc (mem);
324     ptr_top = mem/sizeof(char*);
325     ptr_i = 0;
326
327     key_buf_used = 0;
328     key_file_no = 0;
329
330     if (!(matchDict = dict_open (bfs, GMATCH_DICT, 50, 1)))
331     {
332         logf (LOG_FATAL, "dict_open fail of %s", GMATCH_DICT);
333         exit (1);
334     }
335     assert (!records);
336     records = rec_open (bfs, 1);
337 #if 1
338     zti = zebTargetInfo_open (records, 1);
339 #endif
340 }
341
342 struct encode_info {
343     int  sysno;
344     int  seqno;
345     char buf[768];
346 };
347
348 void encode_key_init (struct encode_info *i)
349 {
350     i->sysno = 0;
351     i->seqno = 0;
352 }
353
354 char *encode_key_int (int d, char *bp)
355 {
356     if (d <= 63)
357         *bp++ = d;
358     else if (d <= 16383)
359     {
360         *bp++ = 64 + (d>>8);
361         *bp++ = d  & 255;
362     }
363     else if (d <= 4194303)
364     {
365         *bp++ = 128 + (d>>16);
366         *bp++ = (d>>8) & 255;
367         *bp++ = d & 255;
368     }
369     else
370     {
371         *bp++ = 192 + (d>>24);
372         *bp++ = (d>>16) & 255;
373         *bp++ = (d>>8) & 255;
374         *bp++ = d & 255;
375     }
376     return bp;
377 }
378
379 void encode_key_write (char *k, struct encode_info *i, FILE *outf)
380 {
381     struct it_key key;
382     char *bp = i->buf;
383
384     while ((*bp++ = *k++))
385         ;
386     memcpy (&key, k+1, sizeof(struct it_key));
387     bp = encode_key_int ( (key.sysno - i->sysno) * 2 + *k, bp);
388     if (i->sysno != key.sysno)
389     {
390         i->sysno = key.sysno;
391         i->seqno = 0;
392     }
393     bp = encode_key_int (key.seqno - i->seqno, bp);
394     i->seqno = key.seqno;
395     if (fwrite (i->buf, bp - i->buf, 1, outf) != 1)
396     {
397         logf (LOG_FATAL|LOG_ERRNO, "fwrite");
398         exit (1);
399     }
400 }
401
402 #define SORT_EXTRA 0
403
404 #if SORT_EXTRA
405 static int key_y_len;
406
407 static int key_y_compare (const void *p1, const void *p2)
408 {
409     int r;
410
411     if ((r = key_compare (*(char**) p1 + key_y_len + 1,
412                           *(char**) p2 + key_y_len + 1)))
413          return r;
414     return *(*(char**) p1 + key_y_len) - *(*(char**) p2 + key_y_len);
415 }
416
417 static int key_x_compare (const void *p1, const void *p2)
418 {
419     return strcmp (*(char**) p1, *(char**) p2);
420 }
421 #endif
422
423 void key_flush (void)
424 {
425     FILE *outf;
426     char out_fname[200];
427     char *prevcp, *cp;
428     struct encode_info encode_info;
429 #if SORT_EXTRA
430     int i;
431 #endif
432     
433     if (ptr_i <= 0)
434         return;
435
436     key_file_no++;
437     logf (LOG_LOG, "sorting section %d", key_file_no);
438 #if !SORT_EXTRA
439     qsort (key_buf + ptr_top-ptr_i, ptr_i, sizeof(char*), key_qsort_compare);
440     getFnameTmp (out_fname, key_file_no);
441
442     if (!(outf = fopen (out_fname, "w")))
443     {
444         logf (LOG_FATAL|LOG_ERRNO, "fopen (4) %s", out_fname);
445         exit (1);
446     }
447     logf (LOG_LOG, "writing section %d", key_file_no);
448     prevcp = cp = key_buf[ptr_top-ptr_i];
449     
450     encode_key_init (&encode_info);
451     encode_key_write (cp, &encode_info, outf);
452     while (--ptr_i > 0)
453     {
454         cp = key_buf[ptr_top-ptr_i];
455         if (strcmp (cp, prevcp))
456         {
457             encode_key_init (&encode_info);
458             encode_key_write (cp, &encode_info, outf);
459             prevcp = cp;
460         }
461         else
462             encode_key_write (cp + strlen(cp), &encode_info, outf);
463     }
464 #else
465     qsort (key_buf + ptr_top-ptr_i, ptr_i, sizeof(char*), key_x_compare);
466     getFnameTmp (out_fname, key_file_no);
467
468     if (!(outf = fopen (out_fname, "w")))
469     {
470         logf (LOG_FATAL|LOG_ERRNO, "fopen (4) %s", out_fname);
471         exit (1);
472     }
473     logf (LOG_LOG, "writing section %d", key_file_no);
474     i = ptr_i;
475     prevcp =  key_buf[ptr_top-i];
476     while (1)
477         if (!--i || strcmp (prevcp, key_buf[ptr_top-i]))
478         {
479             key_y_len = strlen(prevcp)+1;
480 #if 0
481             logf (LOG_LOG, "key_y_len: %2d %02x %02x %s",
482                       key_y_len, prevcp[0], prevcp[1], 2+prevcp);
483 #endif
484             qsort (key_buf + ptr_top-ptr_i, ptr_i - i,
485                                    sizeof(char*), key_y_compare);
486             cp = key_buf[ptr_top-ptr_i];
487             --key_y_len;
488             encode_key_init (&encode_info);
489             encode_key_write (cp, &encode_info, outf);
490             while (--ptr_i > i)
491             {
492                 cp = key_buf[ptr_top-ptr_i];
493                 encode_key_write (cp+key_y_len, &encode_info, outf);
494             }
495             if (!i)
496                 break;
497             prevcp = key_buf[ptr_top-ptr_i];
498         }
499 #endif
500     if (fclose (outf))
501     {
502         logf (LOG_FATAL|LOG_ERRNO, "fclose %s", out_fname);
503         exit (1);
504     }
505     logf (LOG_LOG, "finished section %d", key_file_no);
506     ptr_i = 0;
507     key_buf_used = 0;
508 }
509
510 int key_close ()
511 {
512     key_flush ();
513     xfree (key_buf);
514 #if 1
515     zebTargetInfo_close (zti, 1);
516 #endif
517     rec_close (&records);
518     dict_close (matchDict);
519
520     logRecord (1);
521     return key_file_no;
522 }
523
524 static void wordInit (RecWord *p)
525 {
526     p->attrSet = 1;
527     p->attrUse = 1016;
528     p->which = Word_String;
529 }
530
531 struct recKeys {
532     int buf_used;
533     int buf_max;
534     char *buf;
535     char prevAttrSet;
536     short prevAttrUse;
537     int prevSeqNo;
538 } reckeys;
539
540 static void addRecordKey (const RecWord *p)
541 {
542     char *dst;
543     char attrSet;
544     short attrUse;
545     size_t i;
546     int lead = 0;
547     int diff = 0;
548
549     if (reckeys.buf_used+1024 > reckeys.buf_max)
550     {
551         char *b;
552
553         b = xmalloc (reckeys.buf_max += 128000);
554         if (reckeys.buf_used > 0)
555             memcpy (b, reckeys.buf, reckeys.buf_used);
556         xfree (reckeys.buf);
557         reckeys.buf = b;
558     }
559     dst = reckeys.buf + reckeys.buf_used;
560
561     attrSet = p->attrSet;
562     if (reckeys.buf_used > 0 && reckeys.prevAttrSet == attrSet)
563         lead |= 1;
564     else
565         reckeys.prevAttrSet = attrSet;
566     attrUse = p->attrUse;
567     if (reckeys.buf_used > 0 && reckeys.prevAttrUse == attrUse)
568         lead |= 2;
569     else
570         reckeys.prevAttrUse = attrUse;
571 #if 1
572     diff = 1 + p->seqno - reckeys.prevSeqNo;
573     if (diff >= 1 && diff <= 15)
574         lead |= (diff << 2);
575     else
576         diff = 0;
577 #endif
578     reckeys.prevSeqNo = p->seqno;
579
580     *dst++ = lead;
581
582     if (!(lead & 1))
583     {
584         memcpy (dst, &attrSet, sizeof(attrSet));
585         dst += sizeof(attrSet);
586     }
587     if (!(lead & 2))
588     {
589         memcpy (dst, &attrUse, sizeof(attrUse));
590         dst += sizeof(attrUse);
591     }
592     switch (p->which)
593     {
594         case Word_String:
595             *dst++ = 'w';
596             break;
597         case Word_Phrase:
598             *dst++ = 'p';
599             break;
600         case Word_Numeric:
601             *dst++ = 'n';
602     }
603     for (i = 0; p->u.string[i] && i < IT_MAX_WORD-3; i++)
604         *dst++ = p->u.string[i];
605     *dst++ = '\0';
606
607     if (!diff)
608     {
609         memcpy (dst, &p->seqno, sizeof(p->seqno));
610         dst += sizeof(p->seqno);
611     }
612     reckeys.buf_used = dst - reckeys.buf;
613 }
614
615 static void flushRecordKeys (SYSNO sysno, int cmd, struct recKeys *reckeys, 
616                              const char *databaseName)
617 {
618     char attrSet = -1;
619     short attrUse = -1;
620     int seqno = 0;
621     int off = 0;
622
623     if (zebTargetInfo_curDatabase (zti, databaseName))
624     {
625         if (zebTargetInfo_newDatabase (zti, databaseName))
626             abort ();
627     }
628     while (off < reckeys->buf_used)
629     {
630         const char *src = reckeys->buf + off;
631         struct it_key key;
632         int lead, ch;
633     
634         lead = *src++;
635
636         if (!(lead & 1))
637         {
638             memcpy (&attrSet, src, sizeof(attrSet));
639             src += sizeof(attrSet);
640         }
641         if (!(lead & 2))
642         {
643             memcpy (&attrUse, src, sizeof(attrUse));
644             src += sizeof(attrUse);
645         }
646         if (key_buf_used + 1024 > (ptr_top-ptr_i)*sizeof(char*))
647             key_flush ();
648         ++ptr_i;
649         key_buf[ptr_top-ptr_i] = (char*)key_buf + key_buf_used;
650
651         ch = zebTargetInfo_lookupSU (zti, attrSet, attrUse);
652         if (ch < 0)
653             ch = zebTargetInfo_addSU (zti, attrSet, attrUse);
654         assert (ch > 0);
655         ((char*) key_buf) [key_buf_used++] = ch;
656         while (*src)
657             ((char*)key_buf) [key_buf_used++] = *src++;
658         src++;
659         ((char*)key_buf) [key_buf_used++] = '\0';
660         ((char*) key_buf)[key_buf_used++] = cmd;
661
662         if (lead & 60)
663             seqno += ((lead>>2) & 15)-1;
664         else
665         {
666             memcpy (&seqno, src, sizeof(seqno));
667             src += sizeof(seqno);
668         }
669         key.seqno = seqno;
670         key.sysno = sysno;
671         memcpy ((char*)key_buf + key_buf_used, &key, sizeof(key));
672         key_buf_used += sizeof(key);
673         off = src - reckeys->buf;
674     }
675     assert (off == reckeys->buf_used);
676 }
677
678 static const char **searchRecordKey (struct recKeys *reckeys,
679                                int attrSetS, int attrUseS)
680 {
681     static const char *ws[32];
682     int off = 0;
683     int startSeq = -1;
684     int i;
685     short attrUse;
686     char attrSet;
687     int seqno = 0;
688
689     for (i = 0; i<32; i++)
690         ws[i] = NULL;
691     
692     while (off < reckeys->buf_used)
693     {
694
695         const char *src = reckeys->buf + off;
696         const char *wstart;
697         int lead;
698     
699         lead = *src++;
700
701         if (!(lead & 1))
702         {
703             memcpy (&attrSet, src, sizeof(attrSet));
704             src += sizeof(attrSet);
705         }
706         if (!(lead & 2))
707         {
708             memcpy (&attrUse, src, sizeof(attrUse));
709             src += sizeof(attrUse);
710         }
711         wstart = src;
712         while (*src++)
713             ;
714         if (lead & 60)
715             seqno += ((lead>>2) & 15)-1;
716         else
717         {
718             memcpy (&seqno, src, sizeof(seqno));
719             src += sizeof(seqno);
720         }
721         if (attrUseS == attrUse && attrSetS == attrSet)
722         {
723             int woff;
724
725
726             if (startSeq == -1)
727                 startSeq = seqno;
728             woff = seqno - startSeq;
729             if (woff >= 0 && woff < 31)
730                 ws[woff] = wstart;
731         }
732
733         off = src - reckeys->buf;
734     }
735     assert (off == reckeys->buf_used);
736     return ws;
737 }
738
739 struct file_read_info {
740     off_t file_max;
741     off_t file_offset;
742     off_t file_moffset;
743     int file_more;
744     int fd;
745 };
746
747 static struct file_read_info *file_read_start (int fd)
748 {
749     struct file_read_info *fi = xmalloc (sizeof(*fi));
750
751     fi->fd = fd;
752     fi->file_max = 0;
753     fi->file_moffset = 0;
754     return fi;
755 }
756
757 static void file_read_stop (struct file_read_info *fi)
758 {
759     assert (fi);
760     xfree (fi);
761 }
762
763 static off_t file_seek (void *handle, off_t offset)
764 {
765     struct file_read_info *p = handle;
766     p->file_offset = offset;
767     return lseek (p->fd, offset, SEEK_SET);
768 }
769
770 static off_t file_tell (void *handle)
771 {
772     struct file_read_info *p = handle;
773     return p->file_offset;
774 }
775
776 static int file_read (void *handle, char *buf, size_t count)
777 {
778     struct file_read_info *p = handle;
779     int fd = p->fd;
780     int r;
781     r = read (fd, buf, count);
782     if (r > 0)
783     {
784         p->file_offset += r;
785         if (p->file_offset > p->file_max)
786             p->file_max = p->file_offset;
787     }
788     return r;
789 }
790
791 static void file_begin (void *handle)
792 {
793     struct file_read_info *p = handle;
794
795     p->file_offset = p->file_moffset;
796     if (p->file_moffset)
797         lseek (p->fd, p->file_moffset, SEEK_SET);
798     p->file_more = 0;
799 }
800
801 static void file_end (void *handle, off_t offset)
802 {
803     struct file_read_info *p = handle;
804
805     assert (p->file_more == 0);
806     p->file_more = 1;
807     p->file_moffset = offset;
808 }
809
810 static int atois (const char **s)
811 {
812     int val = 0, c;
813     while ( (c=**s) >= '0' && c <= '9')
814     {
815         val = val*10 + c - '0';
816         ++(*s);
817     }
818     return val;
819 }
820
821 static char *fileMatchStr (struct recKeys *reckeys, struct recordGroup *rGroup,
822                            const char *fname,
823                            const char *spec)
824 {
825     static char dstBuf[2048];
826     char *dst = dstBuf;
827     const char *s = spec;
828     static const char **w;
829     int i;
830
831     while (1)
832     {
833         while (*s == ' ' || *s == '\t')
834             s++;
835         if (!*s)
836             break;
837         if (*s == '(')
838         {
839             char matchFlag[32];
840             int attrSet, attrUse;
841             int first = 1;
842
843             s++;
844             attrSet = atois (&s);
845             if (*s != ',')
846             {
847                 logf (LOG_WARN, "Missing , in match criteria %s in group %s",
848                       spec, rGroup->groupName ? rGroup->groupName : "none");
849                 return NULL;
850             }
851             s++;
852             attrUse = atois (&s);
853             w = searchRecordKey (reckeys, attrSet, attrUse);
854             assert (w);
855
856             if (*s == ')')
857             {
858                 for (i = 0; i<32; i++)
859                     matchFlag[i] = 1;
860             }
861             else
862             {
863                 logf (LOG_WARN, "Missing ) in match criteria %s in group %s",
864                       spec, rGroup->groupName ? rGroup->groupName : "none");
865                 return NULL;
866             }
867             s++;
868
869             for (i = 0; i<32; i++)
870                 if (matchFlag[i] && w[i])
871                 {
872                     if (first)
873                     {
874                         *dst++ = ' ';
875                         first = 0;
876                     }
877                     strcpy (dst, w[i]);
878                     dst += strlen(w[i]);
879                 }
880             if (first)
881             {
882                 logf (LOG_WARN, "Record didn't contain match"
883                       " fields in (%d,%d)", attrSet, attrUse);
884                 return NULL;
885             }
886         }
887         else if (*s == '$')
888         {
889             int spec_len;
890             char special[64];
891             const char *spec_src = NULL;
892             const char *s1 = ++s;
893             while (*s1 && *s1 != ' ' && *s1 != '\t')
894                 s1++;
895
896             spec_len = s1 - s;
897             if (spec_len > 63)
898                 spec_len = 63;
899             memcpy (special, s, spec_len);
900             special[spec_len] = '\0';
901             s = s1;
902
903             if (!strcmp (special, "group"))
904                 spec_src = rGroup->groupName;
905             else if (!strcmp (special, "database"))
906                 spec_src = rGroup->databaseName;
907             else if (!strcmp (special, "filename"))
908                 spec_src = fname;
909             else if (!strcmp (special, "type"))
910                 spec_src = rGroup->recordType;
911             else 
912                 spec_src = NULL;
913             if (spec_src)
914             {
915                 strcpy (dst, spec_src);
916                 dst += strlen (spec_src);
917             }
918         }
919         else if (*s == '\"' || *s == '\'')
920         {
921             int stopMarker = *s++;
922             char tmpString[64];
923             int i = 0;
924
925             while (*s && *s != stopMarker)
926             {
927                 if (i < 63)
928                     tmpString[i++] = *s++;
929             }
930             if (*s)
931                 s++;
932             tmpString[i] = '\0';
933             strcpy (dst, tmpString);
934             dst += strlen (tmpString);
935         }
936         else
937         {
938             logf (LOG_WARN, "Syntax error in match criteria %s in group %s",
939                   spec, rGroup->groupName ? rGroup->groupName : "none");
940             return NULL;
941         }
942         *dst++ = 1;
943     }
944     if (dst == dstBuf)
945     {
946         logf (LOG_WARN, "No match criteria for record %s in group %s",
947               fname, rGroup->groupName ? rGroup->groupName : "none");
948         return NULL;
949     }
950     *dst = '\0';
951     return dstBuf;
952 }
953
954 struct recordLogInfo {
955     const char *fname;
956     int recordOffset;
957     struct recordGroup *rGroup;
958 };
959      
960 static void recordLogPreamble (int level, const char *msg, void *info)
961 {
962     struct recordLogInfo *p = info;
963     FILE *outf = log_file ();
964
965     if (level & LOG_LOG)
966         return ;
967     fprintf (outf, "File %s, offset %d, type %s\n",
968              p->rGroup->recordType, p->recordOffset, p->fname);
969     log_event_start (NULL, NULL);
970 }
971
972 static int recordExtract (SYSNO *sysno, const char *fname,
973                           struct recordGroup *rGroup, int deleteFlag,
974                           struct file_read_info *fi, RecType recType,
975                           char *subType)
976 {
977     struct recExtractCtrl extractCtrl;
978     int r;
979     char *matchStr;
980     SYSNO sysnotmp;
981     off_t recordOffset = 0;
982     Record rec;
983     struct recordLogInfo logInfo;
984
985     if (fi->fd != -1)
986     {
987         /* we are going to read from a file, so prepare the extraction */
988         extractCtrl.fh = fi;
989         extractCtrl.subType = subType;
990         extractCtrl.init = wordInit;
991         extractCtrl.add = addRecordKey;
992         extractCtrl.dh = rGroup->dh;
993
994         reckeys.buf_used = 0;
995         reckeys.prevAttrUse = -1;
996         reckeys.prevAttrSet = -1;
997         reckeys.prevSeqNo = 0;
998
999         recordOffset = fi->file_moffset;
1000         extractCtrl.offset = recordOffset;
1001         extractCtrl.readf = file_read;
1002         extractCtrl.seekf = file_seek;
1003         extractCtrl.tellf = file_tell;
1004         extractCtrl.endf = file_end;
1005         extractCtrl.map_chrs_input = map_chrs_input;
1006         extractCtrl.flagShowRecords = rGroup->flagShowRecords;
1007         if (rGroup->flagShowRecords)
1008             printf ("File: %s %ld\n", fname, (long) recordOffset);
1009
1010         logInfo.fname = fname;
1011         logInfo.recordOffset = recordOffset;
1012         logInfo.rGroup = rGroup;
1013         log_event_start (recordLogPreamble, &logInfo);
1014
1015         r = (*recType->extract)(&extractCtrl);
1016
1017         log_event_start (NULL, NULL);
1018
1019         if (r)      
1020         {
1021             /* error occured during extraction ... */
1022             if (!rGroup->flagShowRecords &&
1023                     records_processed < rGroup->fileVerboseLimit)
1024             {
1025                 logf (LOG_WARN, "fail %s %s %ld code = %d", rGroup->recordType,
1026                       fname, (long) recordOffset, r);
1027             }
1028             return 0;
1029         }
1030         if (reckeys.buf_used == 0)
1031         {
1032             /* the extraction process returned no information - the record
1033                is probably empty - unless flagShowRecords is in use */
1034             if (rGroup->flagShowRecords)
1035                 return 1;
1036             logf (LOG_WARN, "No keys generated for file %s", fname);
1037             logf (LOG_WARN, " The file is probably empty");
1038             return 0;
1039         }
1040     }
1041
1042     /* perform match if sysno not known and if match criteria is specified */
1043        
1044     matchStr = NULL;
1045     if (!sysno) 
1046     {
1047         sysnotmp = 0;
1048         sysno = &sysnotmp;
1049         if (rGroup->recordId && *rGroup->recordId)
1050         {
1051             char *rinfo;
1052         
1053             matchStr = fileMatchStr (&reckeys, rGroup, fname, 
1054                                      rGroup->recordId);
1055             if (matchStr)
1056             {
1057                 rinfo = dict_lookup (matchDict, matchStr);
1058                 if (rinfo)
1059                     memcpy (sysno, rinfo+1, sizeof(*sysno));
1060             }
1061             else
1062             {
1063                 logf (LOG_WARN, "Bad match criteria");
1064                 return 0;
1065             }
1066         }
1067     }
1068
1069     if (! *sysno)
1070     {
1071         /* new record */
1072         if (deleteFlag)
1073         {
1074             logf (LOG_LOG, "Cannot delete new record");
1075             return 1;
1076         }
1077         if (records_processed < rGroup->fileVerboseLimit)
1078             logf (LOG_LOG, "add %s %s %ld", rGroup->recordType,
1079                   fname, (long) recordOffset);
1080         rec = rec_new (records);
1081         *sysno = rec->sysno;
1082
1083         if (matchStr)
1084         {
1085             dict_insert (matchDict, matchStr, sizeof(*sysno), sysno);
1086         }
1087         flushRecordKeys (*sysno, 1, &reckeys, rGroup->databaseName);
1088
1089         records_inserted++;
1090     }
1091     else
1092     {
1093         /* record already exists */
1094         struct recKeys delkeys;
1095
1096         rec = rec_get (records, *sysno);
1097         assert (rec);
1098         delkeys.buf_used = rec->size[recInfo_delKeys];
1099         delkeys.buf = rec->info[recInfo_delKeys];
1100         flushRecordKeys (*sysno, 0, &delkeys, rec->info[recInfo_databaseName]);
1101         if (deleteFlag)
1102         {
1103             /* record going to be deleted */
1104             if (!delkeys.buf_used)
1105             {
1106                 logf (LOG_LOG, "delete %s %s %ld", rGroup->recordType,
1107                       fname, (long) recordOffset);
1108                 logf (LOG_WARN, "cannot delete file above, storeKeys false");
1109             }
1110             else
1111             {
1112                 if (records_processed < rGroup->fileVerboseLimit)
1113                     logf (LOG_LOG, "delete %s %s %ld", rGroup->recordType,
1114                           fname, (long) recordOffset);
1115                 records_deleted++;
1116                 if (matchStr)
1117                     dict_delete (matchDict, matchStr);
1118                 rec_del (records, &rec);
1119             }
1120             logRecord (0);
1121             return 1;
1122         }
1123         else
1124         {
1125             /* record going to be updated */
1126             if (!delkeys.buf_used)
1127             {
1128                 logf (LOG_LOG, "update %s %s %ld", rGroup->recordType,
1129                       fname, (long) recordOffset);
1130                 logf (LOG_WARN, "cannot update file above, storeKeys false");
1131             }
1132             else
1133             {
1134                 if (records_processed < rGroup->fileVerboseLimit)
1135                     logf (LOG_LOG, "update %s %s %ld", rGroup->recordType,
1136                           fname, (long) recordOffset);
1137                 flushRecordKeys (*sysno, 1, &reckeys, rGroup->databaseName); 
1138                 records_updated++;
1139             }
1140         }
1141     }
1142     /* update file type */
1143     xfree (rec->info[recInfo_fileType]);
1144     rec->info[recInfo_fileType] =
1145         rec_strdup (rGroup->recordType, &rec->size[recInfo_fileType]);
1146
1147     /* update filename */
1148     xfree (rec->info[recInfo_filename]);
1149     rec->info[recInfo_filename] =
1150         rec_strdup (fname, &rec->size[recInfo_filename]);
1151
1152     /* update delete keys */
1153     xfree (rec->info[recInfo_delKeys]);
1154     if (reckeys.buf_used > 0 && rGroup->flagStoreKeys == 1)
1155     {
1156 #if 1
1157         rec->size[recInfo_delKeys] = reckeys.buf_used;
1158         rec->info[recInfo_delKeys] = reckeys.buf;
1159         reckeys.buf = NULL;
1160         reckeys.buf_max = 0;
1161 #else
1162         rec->info[recInfo_delKeys] = xmalloc (reckeys.buf_used);
1163         rec->size[recInfo_delKeys] = reckeys.buf_used;
1164         memcpy (rec->info[recInfo_delKeys], reckeys.buf,
1165                 rec->size[recInfo_delKeys]);
1166 #endif
1167     }
1168     else
1169     {
1170         rec->info[recInfo_delKeys] = NULL;
1171         rec->size[recInfo_delKeys] = 0;
1172     }
1173
1174     /* update store data */
1175     xfree (rec->info[recInfo_storeData]);
1176     if (rGroup->flagStoreData == 1)
1177     {
1178         int size = fi->file_moffset - recordOffset; 
1179         if (!size)
1180             size = fi->file_max - recordOffset;
1181         rec->size[recInfo_storeData] = size;
1182         rec->info[recInfo_storeData] = xmalloc (size);
1183         if (lseek (fi->fd, recordOffset, SEEK_SET) < 0)
1184         {
1185             logf (LOG_ERRNO|LOG_FATAL, "seek to %ld in %s", fname,
1186                   (long) recordOffset);
1187             exit (1);
1188         }
1189         if (read (fi->fd, rec->info[recInfo_storeData], size) < size)
1190         {
1191             logf (LOG_ERRNO|LOG_FATAL, "read %d bytes of %s",
1192                   fi->file_max, fname);
1193             exit (1);
1194         }
1195     }
1196     else
1197     {
1198         rec->info[recInfo_storeData] = NULL;
1199         rec->size[recInfo_storeData] = 0;
1200     }
1201     /* update database name */
1202     xfree (rec->info[recInfo_databaseName]);
1203     rec->info[recInfo_databaseName] =
1204         rec_strdup (rGroup->databaseName, &rec->size[recInfo_databaseName]); 
1205
1206     /* update offset */
1207     xfree (rec->info[recInfo_offset]);
1208
1209     rec->size[recInfo_offset] = sizeof(recordOffset);
1210     rec->info[recInfo_offset] = xmalloc (sizeof(recordOffset));
1211     memcpy (rec->info[recInfo_offset], &recordOffset, sizeof(recordOffset));
1212     
1213     /* commit this record */
1214     rec_put (records, &rec);
1215     logRecord (0);
1216     return 1;
1217 }
1218
1219 int fileExtract (SYSNO *sysno, const char *fname, 
1220                  const struct recordGroup *rGroupP, int deleteFlag)
1221 {
1222     int r, i, fd;
1223     char gprefix[128];
1224     char ext[128];
1225     char ext_res[128];
1226     char subType[128];
1227     RecType recType;
1228     struct recordGroup rGroupM;
1229     struct recordGroup *rGroup = &rGroupM;
1230     struct file_read_info *fi;
1231
1232     memcpy (rGroup, rGroupP, sizeof(*rGroupP));
1233    
1234     if (!rGroup->groupName || !*rGroup->groupName)
1235         *gprefix = '\0';
1236     else
1237         sprintf (gprefix, "%s.", rGroup->groupName);
1238
1239     logf (LOG_DEBUG, "fileExtract %s", fname);
1240
1241     /* determine file extension */
1242     for (i = strlen(fname); --i >= 0; )
1243         if (fname[i] == '/')
1244         {
1245             strcpy (ext, "");
1246             break;
1247         }
1248         else if (fname[i] == '.')
1249         {
1250             strcpy (ext, fname+i+1);
1251             break;
1252         }
1253     /* determine file type - depending on extension */
1254     if (!rGroup->recordType)
1255     {
1256         sprintf (ext_res, "%srecordType.%s", gprefix, ext);
1257         if (!(rGroup->recordType = res_get (common_resource, ext_res)))
1258         {
1259             sprintf (ext_res, "%srecordType", gprefix);
1260             if (!(rGroup->recordType = res_get (common_resource, ext_res)))
1261             {
1262                 if (records_processed < rGroup->fileVerboseLimit)
1263                     logf (LOG_LOG, "? %s", fname);
1264                 return 0;
1265             }
1266         }
1267     }
1268     if (!rGroup->recordType)
1269     {
1270         if (records_processed < rGroup->fileVerboseLimit)
1271             logf (LOG_LOG, "? record %s", fname);
1272         return 0;
1273     }
1274     if (!(recType = recType_byName (rGroup->recordType, subType)))
1275     {
1276         logf (LOG_WARN, "No such record type: %s", rGroup->recordType);
1277         return 0;
1278     }
1279
1280     /* determine match criteria */
1281     if (!rGroup->recordId)
1282     {
1283         sprintf (ext_res, "%srecordId.%s", gprefix, ext);
1284         rGroup->recordId = res_get (common_resource, ext_res);
1285     }
1286
1287     /* determine database name */
1288     if (!rGroup->databaseName)
1289     {
1290         sprintf (ext_res, "%sdatabase.%s", gprefix, ext);
1291         if (!(rGroup->databaseName = res_get (common_resource, ext_res)))
1292         {
1293             sprintf (ext_res, "%sdatabase", gprefix);
1294             rGroup->databaseName = res_get (common_resource, ext_res);
1295         }
1296     }
1297     if (!rGroup->databaseName)
1298         rGroup->databaseName = "Default";
1299
1300     if (rGroup->flagStoreData == -1)
1301     {
1302         const char *sval;
1303         sprintf (ext_res, "%sstoreData.%s", gprefix, ext);
1304         if (!(sval = res_get (common_resource, ext_res)))
1305         {
1306             sprintf (ext_res, "%sstoreData", gprefix);
1307             sval = res_get (common_resource, ext_res);
1308         }
1309         if (sval)
1310             rGroup->flagStoreData = atoi (sval);
1311     }
1312     if (rGroup->flagStoreData == -1)
1313         rGroup->flagStoreData = 0;
1314
1315     if (rGroup->flagStoreKeys == -1)
1316     {
1317         const char *sval;
1318
1319         sprintf (ext_res, "%sstoreKeys.%s", gprefix, ext);
1320         if (!(sval = res_get (common_resource, ext_res)))
1321         {
1322             sprintf (ext_res, "%sstoreKeys", gprefix);
1323             sval = res_get (common_resource, ext_res);
1324         }
1325         if (sval)
1326             rGroup->flagStoreKeys = atoi (sval);
1327     }
1328     if (rGroup->flagStoreKeys == -1)
1329         rGroup->flagStoreKeys = 0;
1330
1331     if (sysno && deleteFlag)
1332         fd = -1;
1333     else
1334     {
1335         if ((fd = open (fname, O_BINARY|O_RDONLY)) == -1)
1336         {
1337             logf (LOG_WARN|LOG_ERRNO, "open %s", fname);
1338             return 0;
1339         }
1340     }
1341     fi = file_read_start (fd);
1342     do
1343     {
1344         file_begin (fi);
1345         r = recordExtract (sysno, fname, rGroup, deleteFlag, fi,
1346                            recType, subType);
1347     } while (r && !sysno && fi->file_more);
1348     file_read_stop (fi);
1349     if (fd != -1)
1350         close (fd);
1351     return r;
1352 }
1353