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