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