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