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