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