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