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