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