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