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