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