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