Implemented bug #588: allrecords search. Using @attr 1=allrecords ""
[idzebra-moved-to-github.git] / index / extract.c
1 /* $Id: extract.c,v 1.213 2006-05-17 17:46:45 adam Exp $
2    Copyright (C) 1995-2006
3    Index Data ApS
4
5 This file is part of the Zebra server.
6
7 Zebra is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
10 version.
11
12 Zebra is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Zebra; see the file LICENSE.zebra.  If not, write to the
19 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20 02111-1307, USA.
21 */
22
23 #include <stdio.h>
24 #include <assert.h>
25 #include <ctype.h>
26 #ifdef WIN32
27 #include <io.h>
28 #endif
29 #if HAVE_UNISTD_H
30 #include <unistd.h>
31 #endif
32 #include <fcntl.h>
33
34 #include "index.h"
35 #include "orddict.h"
36 #include <direntz.h>
37 #include <charmap.h>
38
39 #ifdef WIN32
40 #define PRINTF_OFF_T "%I64d"
41 #else
42 /* !WIN32 */
43 #if SIZEOF_OFF_T == SIZEOF_LONG_LONG
44 #define PRINTF_OFF_T "%lld"
45 #else
46 #define PRINTF_OFF_T "%ld"
47 #endif
48
49 #endif
50
51
52 #define USE_SHELLSORT 0
53
54 #if USE_SHELLSORT
55 static void shellsort(void *ar, int r, size_t s,
56                       int (*cmp)(const void *a, const void *b))
57 {
58     char *a = ar;
59     char v[100];
60     int h, i, j, k;
61     static const int incs[16] = { 1391376, 463792, 198768, 86961, 33936,
62                                   13776, 4592, 1968, 861, 336, 
63                                   112, 48, 21, 7, 3, 1 };
64     for ( k = 0; k < 16; k++)
65         for (h = incs[k], i = h; i < r; i++)
66         { 
67             memcpy (v, a+s*i, s);
68             j = i;
69             while (j > h && (*cmp)(a + s*(j-h), v) > 0)
70             {
71                 memcpy (a + s*j, a + s*(j-h), s);
72                 j -= h;
73             }
74             memcpy (a+s*j, v, s);
75         } 
76 }
77 #endif
78
79 static void logRecord (ZebraHandle zh)
80 {
81     ++zh->records_processed;
82     if (!(zh->records_processed % 1000))
83     {
84         yaz_log (YLOG_LOG, "Records: "ZINT_FORMAT" i/u/d "
85                         ZINT_FORMAT"/"ZINT_FORMAT"/"ZINT_FORMAT, 
86               zh->records_processed, zh->records_inserted, zh->records_updated,
87               zh->records_deleted);
88     }
89 }
90
91 static void extract_add_index_string (RecWord *p, const char *str, int length);
92
93 static void extract_set_store_data_prepare(struct recExtractCtrl *p);
94
95 static void extract_init (struct recExtractCtrl *p, RecWord *w)
96 {
97     w->zebra_maps = p->zebra_maps;
98     w->seqno = 1;
99 #if NATTR
100 #else
101     w->attrSet = VAL_BIB1;
102     w->attrUse = 1016;
103 #endif
104     w->index_name = 0;
105     w->index_type = 'w';
106     w->extractCtrl = p;
107     w->record_id = 0;
108     w->section_id = 0;
109 }
110
111 static void searchRecordKey(ZebraHandle zh,
112                             zebra_rec_keys_t reckeys,
113                             int attrSetS, int attrUseS,
114                             const char **ws, int ws_length)
115 {
116     int i;
117     int ch;
118
119     for (i = 0; i<ws_length; i++)
120         ws[i] = NULL;
121
122     ch = zebraExplain_lookup_attr_su_any_index(zh->reg->zei,
123                                                attrSetS, attrUseS);
124     if (ch < 0)
125         return ;
126
127     if (zebra_rec_keys_rewind(reckeys))
128     {
129         int startSeq = -1;
130         const char *str;
131         size_t slen;
132         struct it_key key;
133         zint seqno;
134         while (zebra_rec_keys_read(reckeys, &str, &slen, &key))
135         {
136             assert(key.len <= 4 && key.len > 2);
137
138             seqno = key.mem[key.len-1];
139             
140             if (key.mem[0] == ch)
141             {
142                 int woff;
143                 
144                 if (startSeq == -1)
145                     startSeq = seqno;
146                 woff = seqno - startSeq;
147                 if (woff >= 0 && woff < ws_length)
148                     ws[woff] = str;
149             }
150         }
151     }
152 }
153
154 struct file_read_info {
155     off_t file_max;         /* maximum offset so far */
156     off_t file_offset;      /* current offset */
157     off_t file_moffset;     /* offset of rec/rec boundary */
158     int file_more;
159     int fd;
160 };
161
162 static struct file_read_info *file_read_start (int fd)
163 {
164     struct file_read_info *fi = (struct file_read_info *)
165         xmalloc (sizeof(*fi));
166
167     fi->fd = fd;
168     fi->file_max = 0;
169     fi->file_moffset = 0;
170     fi->file_offset = 0;
171     fi->file_more = 0;
172     return fi;
173 }
174
175 static void file_read_stop (struct file_read_info *fi)
176 {
177     xfree (fi);
178 }
179
180 static off_t file_seek (void *handle, off_t offset)
181 {
182     struct file_read_info *p = (struct file_read_info *) handle;
183     p->file_offset = offset;
184     return lseek (p->fd, offset, SEEK_SET);
185 }
186
187 static off_t file_tell (void *handle)
188 {
189     struct file_read_info *p = (struct file_read_info *) handle;
190     return p->file_offset;
191 }
192
193 static int file_read (void *handle, char *buf, size_t count)
194 {
195     struct file_read_info *p = (struct file_read_info *) handle;
196     int fd = p->fd;
197     int r;
198     r = read (fd, buf, count);
199     if (r > 0)
200     {
201         p->file_offset += r;
202         if (p->file_offset > p->file_max)
203             p->file_max = p->file_offset;
204     }
205     return r;
206 }
207
208 static void file_end (void *handle, off_t offset)
209 {
210     struct file_read_info *p = (struct file_read_info *) handle;
211
212     if (offset != p->file_moffset)
213     {
214         p->file_moffset = offset;
215         p->file_more = 1;
216     }
217 }
218
219 #define FILE_MATCH_BLANK "\t "
220
221 static char *fileMatchStr (ZebraHandle zh,
222                            zebra_rec_keys_t reckeys,
223                            const char *fname, const char *spec)
224 {
225     static char dstBuf[2048];      /* static here ??? */
226     char *dst = dstBuf;
227     const char *s = spec;
228
229     while (1)
230     {
231         for (; *s && strchr(FILE_MATCH_BLANK, *s); s++)
232             ;
233         if (!*s)
234             break;
235         if (*s == '(')
236         {
237             const char *ws[32];
238             char attset_str[64], attname_str[64];
239             data1_attset *attset;
240             int i;
241             int attSet = 1, attUse = 1;
242             int first = 1;
243             
244             for (s++; strchr(FILE_MATCH_BLANK, *s); s++)
245                 ;
246             for (i = 0; *s && *s != ',' && *s != ')' && 
247                      !strchr(FILE_MATCH_BLANK, *s); s++)
248                 if (i+1 < sizeof(attset_str))
249                     attset_str[i++] = *s;
250             attset_str[i] = '\0';
251             
252             for (; strchr(FILE_MATCH_BLANK, *s); s++)
253                 ;
254             if (*s == ',')
255             {
256                 for (s++; strchr(FILE_MATCH_BLANK, *s); s++)
257                     ;
258                 for (i = 0; *s && *s != ')' && 
259                          !strchr(FILE_MATCH_BLANK, *s); s++)
260                     if (i+1 < sizeof(attname_str))
261                         attname_str[i++] = *s;
262                 attname_str[i] = '\0';
263             }
264             
265             if ((attset = data1_get_attset (zh->reg->dh, attset_str)))
266             {
267                 data1_att *att;
268                 attSet = attset->reference;
269                 att = data1_getattbyname(zh->reg->dh, attset, attname_str);
270                 if (att)
271                     attUse = att->value;
272                 else
273                     attUse = atoi (attname_str);
274             }
275             searchRecordKey (zh, reckeys, attSet, attUse, ws, 32);
276
277             if (*s != ')')
278             {
279                 yaz_log (YLOG_WARN, "Missing ) in match criteria %s in group %s",
280                       spec, zh->m_group ? zh->m_group : "none");
281                 return NULL;
282             }
283             s++;
284
285             for (i = 0; i<32; i++)
286                 if (ws[i])
287                 {
288                     if (first)
289                     {
290                         *dst++ = ' ';
291                         first = 0;
292                     }
293                     strcpy (dst, ws[i]);
294                     dst += strlen(ws[i]);
295                 }
296             if (first)
297             {
298                 yaz_log (YLOG_WARN, "Record didn't contain match"
299                       " fields in (%s,%s)", attset_str, attname_str);
300                 return NULL;
301             }
302         }
303         else if (*s == '$')
304         {
305             int spec_len;
306             char special[64];
307             const char *spec_src = NULL;
308             const char *s1 = ++s;
309             while (*s1 && !strchr(FILE_MATCH_BLANK, *s1))
310                 s1++;
311
312             spec_len = s1 - s;
313             if (spec_len > sizeof(special)-1)
314                 spec_len = sizeof(special)-1;
315             memcpy (special, s, spec_len);
316             special[spec_len] = '\0';
317             s = s1;
318
319             if (!strcmp (special, "group"))
320                 spec_src = zh->m_group;
321             else if (!strcmp (special, "database"))
322                 spec_src = zh->basenames[0];
323             else if (!strcmp (special, "filename")) {
324                 spec_src = fname;
325             }
326             else if (!strcmp (special, "type"))
327                 spec_src = zh->m_record_type;
328             else 
329                 spec_src = NULL;
330             if (spec_src)
331             {
332                 strcpy (dst, spec_src);
333                 dst += strlen (spec_src);
334             }
335         }
336         else if (*s == '\"' || *s == '\'')
337         {
338             int stopMarker = *s++;
339             char tmpString[64];
340             int i = 0;
341
342             while (*s && *s != stopMarker)
343             {
344                 if (i+1 < sizeof(tmpString))
345                     tmpString[i++] = *s++;
346             }
347             if (*s)
348                 s++;
349             tmpString[i] = '\0';
350             strcpy (dst, tmpString);
351             dst += strlen (tmpString);
352         }
353         else
354         {
355             yaz_log (YLOG_WARN, "Syntax error in match criteria %s in group %s",
356                   spec, zh->m_group ? zh->m_group : "none");
357             return NULL;
358         }
359         *dst++ = 1;
360     }
361     if (dst == dstBuf)
362     {
363         yaz_log (YLOG_WARN, "No match criteria for record %s in group %s",
364               fname, zh->m_group ? zh->m_group : "none");
365         return NULL;
366     }
367     *dst = '\0';
368     return dstBuf;
369 }
370
371 struct recordLogInfo {
372     const char *fname;
373     int recordOffset;
374     struct recordGroup *rGroup;
375 };
376
377 static void init_extractCtrl(ZebraHandle zh, struct recExtractCtrl *ctrl)
378 {
379     int i;
380     for (i = 0; i<256; i++)
381     {
382         if (zebra_maps_is_positioned(zh->reg->zebra_maps, i))
383             ctrl->seqno[i] = 1;
384         else
385             ctrl->seqno[i] = 0;
386     }
387     ctrl->zebra_maps = zh->reg->zebra_maps;
388     ctrl->flagShowRecords = !zh->m_flag_rw;
389 }
390
391 static void all_matches_add(struct recExtractCtrl *ctrl)
392 {
393     RecWord word;
394     extract_init(ctrl, &word);
395     word.index_name = "allrecords";
396     word.index_type = 'w';
397     word.seqno = 1;
398     extract_add_index_string (&word, "", 0);
399 }
400
401 static ZEBRA_RES file_extract_record(ZebraHandle zh,
402                                      SYSNO *sysno, const char *fname,
403                                      int deleteFlag,
404                                      struct file_read_info *fi,
405                                      int force_update,
406                                      RecType recType,
407                                      void *recTypeClientData)
408 {
409     const char *match_str_to_print = "";
410     RecordAttr *recordAttr;
411     int r;
412     const char *matchStr = 0;
413     SYSNO sysnotmp;
414     Record rec;
415     off_t recordOffset = 0;
416     struct recExtractCtrl extractCtrl;
417     
418     /* announce database */
419     if (zebraExplain_curDatabase (zh->reg->zei, zh->basenames[0]))
420     {
421         if (zebraExplain_newDatabase (zh->reg->zei, zh->basenames[0],
422                                       zh->m_explain_database))
423             return ZEBRA_FAIL;
424     }
425
426     if (fi->fd != -1)
427     {
428         /* we are going to read from a file, so prepare the extraction */
429         zebra_rec_keys_reset(zh->reg->keys);
430
431 #if NATTR
432         zebra_rec_keys_reset(zh->reg->sortKeys);
433 #else
434         zh->reg->sortKeys.buf_used = 0;
435 #endif
436         recordOffset = fi->file_moffset;
437         extractCtrl.handle = zh;
438         extractCtrl.offset = fi->file_moffset;
439         extractCtrl.readf = file_read;
440         extractCtrl.seekf = file_seek;
441         extractCtrl.tellf = file_tell;
442         extractCtrl.endf = file_end;
443         extractCtrl.fh = fi;
444         extractCtrl.init = extract_init;
445         extractCtrl.tokenAdd = extract_token_add;
446         extractCtrl.schemaAdd = extract_schema_add;
447         extractCtrl.dh = zh->reg->dh;
448         extractCtrl.match_criteria[0] = '\0';
449         extractCtrl.staticrank = 0;
450         
451         extractCtrl.first_record = fi->file_offset ? 0 : 1;
452
453         extract_set_store_data_prepare(&extractCtrl);
454
455         init_extractCtrl(zh, &extractCtrl);
456
457         if (!zh->m_flag_rw)
458             printf ("File: %s " PRINTF_OFF_T "\n", fname, recordOffset);
459         if (zh->m_flag_rw)
460         {
461             char msg[512];
462             sprintf (msg, "%s:" PRINTF_OFF_T , fname, recordOffset);
463             yaz_log_init_prefix2 (msg);
464         }
465
466         r = (*recType->extract)(recTypeClientData, &extractCtrl);
467
468         yaz_log_init_prefix2 (0);
469         if (r == RECCTRL_EXTRACT_EOF)
470             return ZEBRA_FAIL;
471         else if (r == RECCTRL_EXTRACT_ERROR_GENERIC)
472         {
473             /* error occured during extraction ... */
474             if (zh->m_flag_rw &&
475                 zh->records_processed < zh->m_file_verbose_limit)
476             {
477                 yaz_log (YLOG_WARN, "fail %s %s " PRINTF_OFF_T, zh->m_record_type,
478                       fname, recordOffset);
479             }
480             return ZEBRA_FAIL;
481         }
482         else if (r == RECCTRL_EXTRACT_ERROR_NO_SUCH_FILTER)
483         {
484             /* error occured during extraction ... */
485             if (zh->m_flag_rw &&
486                 zh->records_processed < zh->m_file_verbose_limit)
487             {
488                 yaz_log (YLOG_WARN, "no filter for %s %s " 
489                       PRINTF_OFF_T, zh->m_record_type,
490                       fname, recordOffset);
491             }
492             return ZEBRA_FAIL;
493         }
494         all_matches_add(&extractCtrl);
495         if (extractCtrl.match_criteria[0])
496             matchStr = extractCtrl.match_criteria;
497     }
498
499     /* if matchStr is set now - we assume it's printable .
500        For internal matchStr (see below) we don't print */
501     if (matchStr)
502         match_str_to_print = matchStr;
503
504     /* perform internal match if sysno not known and if match criteria is
505        specified already */
506     if (!sysno) 
507     {
508         sysnotmp = 0;
509         sysno = &sysnotmp;
510
511         if (matchStr == 0 && zh->m_record_id && *zh->m_record_id)
512         {
513             matchStr = fileMatchStr (zh, zh->reg->keys, fname, 
514                                      zh->m_record_id);
515             if (!matchStr)
516             {
517                 yaz_log(YLOG_WARN, "Bad match criteria");
518                 return ZEBRA_FAIL;
519             }
520         }
521         if (matchStr)
522         {
523             int db_ord = zebraExplain_get_database_ord(zh->reg->zei);
524             char *rinfo = dict_lookup_ord(zh->reg->matchDict, db_ord,
525                                           matchStr);
526             if (rinfo)
527             {
528                 assert(*rinfo == sizeof(*sysno));
529                 memcpy (sysno, rinfo+1, sizeof(*sysno));
530             }
531         }
532     }
533     if (! *sysno && zebra_rec_keys_empty(zh->reg->keys) )
534     {
535          /* the extraction process returned no information - the record
536             is probably empty - unless flagShowRecords is in use */
537          if (!zh->m_flag_rw)
538              return ZEBRA_OK;
539   
540          if (zh->records_processed < zh->m_file_verbose_limit)
541              yaz_log (YLOG_WARN, "empty %s %s " PRINTF_OFF_T, zh->m_record_type,
542             fname, recordOffset);
543          return ZEBRA_OK;
544     }
545
546     if (! *sysno)
547     {
548         /* new record */
549         if (deleteFlag)
550         {
551             yaz_log (YLOG_LOG, "delete %s %s " PRINTF_OFF_T, zh->m_record_type,
552                   fname, recordOffset);
553             yaz_log (YLOG_WARN, "cannot delete record above (seems new)");
554             return ZEBRA_OK;
555         }
556
557         rec = rec_new (zh->reg->records);
558         
559         *sysno = rec->sysno;
560         
561         if (zh->records_processed < zh->m_file_verbose_limit)
562         {
563             yaz_log(YLOG_LOG, "add %s %s " PRINTF_OFF_T 
564                     " " ZINT_FORMAT " %s" ,
565                     zh->m_record_type,
566                     fname, recordOffset, *sysno, match_str_to_print);
567         }
568         recordAttr = rec_init_attr (zh->reg->zei, rec);
569         recordAttr->staticrank = extractCtrl.staticrank;
570
571         if (matchStr)
572         {
573             int db_ord = zebraExplain_get_database_ord(zh->reg->zei);
574             dict_insert_ord(zh->reg->matchDict, db_ord, matchStr,
575                             sizeof(*sysno), sysno);
576         }
577
578
579 #if NATTR
580         extract_flushSortKeys (zh, *sysno, 1, zh->reg->sortKeys);
581 #else
582         extract_flushSortKeys (zh, *sysno, 1, &zh->reg->sortKeys);
583 #endif
584         extract_flushRecordKeys (zh, *sysno, 1, zh->reg->keys,
585                                  recordAttr->staticrank);
586         zh->records_inserted++;
587     }
588     else
589     {
590         /* record already exists */
591         zebra_rec_keys_t delkeys = zebra_rec_keys_open();
592
593 #if NATTR
594         zebra_rec_keys_t sortKeys = zebra_rec_keys_open();
595 #else
596         struct sortKeys sortKeys;
597 #endif
598
599         rec = rec_get (zh->reg->records, *sysno);
600         assert (rec);
601         
602         recordAttr = rec_init_attr (zh->reg->zei, rec);
603
604         zebra_rec_keys_set_buf(delkeys,
605                                rec->info[recInfo_delKeys],
606                                rec->size[recInfo_delKeys],
607                                0);
608
609 #if NATTR
610         zebra_rec_keys_set_buf(sortKeys,
611                                rec->info[recInfo_sortKeys],
612                                rec->size[recInfo_sortKeys],
613                                0);
614         extract_flushSortKeys (zh, *sysno, 0, sortKeys);
615 #else
616         sortKeys.buf_used = rec->size[recInfo_sortKeys];
617         sortKeys.buf = rec->info[recInfo_sortKeys];
618         extract_flushSortKeys (zh, *sysno, 0, &sortKeys);
619 #endif
620
621         extract_flushRecordKeys (zh, *sysno, 0, delkeys,
622                                  recordAttr->staticrank); /* old values */  
623         if (deleteFlag)
624         {
625             /* record going to be deleted */
626             if (zebra_rec_keys_empty(delkeys))
627             {
628                 yaz_log (YLOG_LOG, "delete %s %s " PRINTF_OFF_T 
629                          " " ZINT_FORMAT,
630                          zh->m_record_type, fname, recordOffset, *sysno);
631                 yaz_log (YLOG_WARN, "cannot delete file above, storeKeys false (1)");
632             }
633             else
634             {
635                 if (zh->records_processed < zh->m_file_verbose_limit)
636                 {
637                     yaz_log(YLOG_LOG, "delete %s %s " PRINTF_OFF_T 
638                             " " ZINT_FORMAT " %s" ,
639                             zh->m_record_type,
640                             fname, recordOffset, *sysno, match_str_to_print);
641                 }
642                 zh->records_deleted++;
643                 if (matchStr)
644                 {
645                     int db_ord = zebraExplain_get_database_ord(zh->reg->zei);
646                     dict_delete_ord(zh->reg->matchDict, db_ord, matchStr);
647                 }
648                 rec_del (zh->reg->records, &rec);
649             }
650             rec_rm (&rec);
651             logRecord (zh);
652             return ZEBRA_OK;
653         }
654         else
655         {
656             /* flush new keys for sort&search etc */
657             if (zh->records_processed < zh->m_file_verbose_limit)
658             {
659                 yaz_log(YLOG_LOG, "update %s %s " PRINTF_OFF_T 
660                         " " ZINT_FORMAT " %s" ,
661                         zh->m_record_type,
662                         fname, recordOffset, *sysno, match_str_to_print);
663             }
664             recordAttr->staticrank = extractCtrl.staticrank;
665 #if NATTR
666             extract_flushSortKeys (zh, *sysno, 1, zh->reg->sortKeys);
667 #else
668             extract_flushSortKeys (zh, *sysno, 1, &zh->reg->sortKeys);
669 #endif
670             extract_flushRecordKeys (zh, *sysno, 1, zh->reg->keys,
671                                          recordAttr->staticrank);
672             zh->records_updated++;
673         }
674         zebra_rec_keys_close(delkeys);
675 #if NATTR
676         zebra_rec_keys_close(sortKeys);
677 #endif
678     }
679     /* update file type */
680     xfree (rec->info[recInfo_fileType]);
681     rec->info[recInfo_fileType] =
682         rec_strdup (zh->m_record_type, &rec->size[recInfo_fileType]);
683
684     /* update filename */
685     xfree (rec->info[recInfo_filename]);
686     rec->info[recInfo_filename] =
687         rec_strdup (fname, &rec->size[recInfo_filename]);
688
689     /* update delete keys */
690     xfree (rec->info[recInfo_delKeys]);
691     if (!zebra_rec_keys_empty(zh->reg->keys) && zh->m_store_keys == 1)
692     {
693         zebra_rec_keys_get_buf(zh->reg->keys,
694                                &rec->info[recInfo_delKeys],
695                                &rec->size[recInfo_delKeys]);
696     }
697     else
698     {
699         rec->info[recInfo_delKeys] = NULL;
700         rec->size[recInfo_delKeys] = 0;
701     }
702
703     /* update sort keys */
704     xfree (rec->info[recInfo_sortKeys]);
705
706 #if NATTR
707     zebra_rec_keys_get_buf(zh->reg->sortKeys,
708                            &rec->info[recInfo_sortKeys],
709                            &rec->size[recInfo_sortKeys]);
710 #else
711     rec->size[recInfo_sortKeys] = zh->reg->sortKeys.buf_used;
712     rec->info[recInfo_sortKeys] = zh->reg->sortKeys.buf;
713     zh->reg->sortKeys.buf = NULL;
714     zh->reg->sortKeys.buf_max = 0;
715 #endif
716
717     /* save file size of original record */
718     zebraExplain_recordBytesIncrement (zh->reg->zei,
719                                        - recordAttr->recordSize);
720     recordAttr->recordSize = fi->file_moffset - recordOffset;
721     if (!recordAttr->recordSize)
722         recordAttr->recordSize = fi->file_max - recordOffset;
723     zebraExplain_recordBytesIncrement (zh->reg->zei,
724                                        recordAttr->recordSize);
725
726     /* set run-number for this record */
727     recordAttr->runNumber = zebraExplain_runNumberIncrement (zh->reg->zei,
728                                                              0);
729
730     /* update store data */
731     xfree (rec->info[recInfo_storeData]);
732     if (zh->store_data_buf)
733     {
734         rec->size[recInfo_storeData] = zh->store_data_size;
735         rec->info[recInfo_storeData] = zh->store_data_buf;
736         zh->store_data_buf = 0;
737     }
738     else if (zh->m_store_data)
739     {
740         rec->size[recInfo_storeData] = recordAttr->recordSize;
741         rec->info[recInfo_storeData] = (char *)
742             xmalloc (recordAttr->recordSize);
743         if (lseek (fi->fd, recordOffset, SEEK_SET) < 0)
744         {
745             yaz_log (YLOG_ERRNO|YLOG_FATAL, "seek to " PRINTF_OFF_T " in %s",
746                   recordOffset, fname);
747             exit (1);
748         }
749         if (read (fi->fd, rec->info[recInfo_storeData], recordAttr->recordSize)
750             < recordAttr->recordSize)
751         {
752             yaz_log (YLOG_ERRNO|YLOG_FATAL, "read %d bytes of %s",
753                   recordAttr->recordSize, fname);
754             exit (1);
755         }
756     }
757     else
758     {
759         rec->info[recInfo_storeData] = NULL;
760         rec->size[recInfo_storeData] = 0;
761     }
762     /* update database name */
763     xfree (rec->info[recInfo_databaseName]);
764     rec->info[recInfo_databaseName] =
765         rec_strdup (zh->basenames[0], &rec->size[recInfo_databaseName]); 
766
767     /* update offset */
768     recordAttr->recordOffset = recordOffset;
769     
770     /* commit this record */
771     rec_put (zh->reg->records, &rec);
772     logRecord (zh);
773     return ZEBRA_OK;
774 }
775
776 ZEBRA_RES zebra_extract_file(ZebraHandle zh, SYSNO *sysno, const char *fname, 
777                              int deleteFlag)
778 {
779     ZEBRA_RES r = ZEBRA_OK;
780     int i, fd;
781     char gprefix[128];
782     char ext[128];
783     char ext_res[128];
784     struct file_read_info *fi;
785     const char *original_record_type = 0;
786     RecType recType;
787     void *recTypeClientData;
788
789     if (!zh->m_group || !*zh->m_group)
790         *gprefix = '\0';
791     else
792         sprintf (gprefix, "%s.", zh->m_group);
793     
794     yaz_log (YLOG_DEBUG, "fileExtract %s", fname);
795
796     /* determine file extension */
797     *ext = '\0';
798     for (i = strlen(fname); --i >= 0; )
799         if (fname[i] == '/')
800             break;
801         else if (fname[i] == '.')
802         {
803             strcpy (ext, fname+i+1);
804             break;
805         }
806     /* determine file type - depending on extension */
807     original_record_type = zh->m_record_type;
808     if (!zh->m_record_type)
809     {
810         sprintf (ext_res, "%srecordType.%s", gprefix, ext);
811         zh->m_record_type = res_get (zh->res, ext_res);
812     }
813     if (!zh->m_record_type)
814     {
815         if (zh->records_processed < zh->m_file_verbose_limit)
816             yaz_log (YLOG_LOG, "? %s", fname);
817         return 0;
818     }
819     /* determine match criteria */
820     if (!zh->m_record_id)
821     {
822         sprintf (ext_res, "%srecordId.%s", gprefix, ext);
823         zh->m_record_id = res_get (zh->res, ext_res);
824     }
825
826     if (!(recType =
827           recType_byName (zh->reg->recTypes, zh->res, zh->m_record_type,
828                           &recTypeClientData)))
829     {
830         yaz_log(YLOG_WARN, "No such record type: %s", zh->m_record_type);
831         return ZEBRA_FAIL;
832     }
833
834     switch(recType->version)
835     {
836     case 0:
837         break;
838     default:
839         yaz_log(YLOG_WARN, "Bad filter version: %s", zh->m_record_type);
840     }
841     if (sysno && deleteFlag)
842         fd = -1;
843     else
844     {
845         char full_rep[1024];
846
847         if (zh->path_reg && !yaz_is_abspath (fname))
848         {
849             strcpy (full_rep, zh->path_reg);
850             strcat (full_rep, "/");
851             strcat (full_rep, fname);
852         }
853         else
854             strcpy (full_rep, fname);
855         
856         if ((fd = open (full_rep, O_BINARY|O_RDONLY)) == -1)
857         {
858             yaz_log (YLOG_WARN|YLOG_ERRNO, "open %s", full_rep);
859             zh->m_record_type = original_record_type;
860             return ZEBRA_FAIL;
861         }
862     }
863     fi = file_read_start (fd);
864     while(1)
865     {
866         fi->file_moffset = fi->file_offset;
867         fi->file_more = 0;  /* file_end not called (yet) */
868         r = file_extract_record (zh, sysno, fname, deleteFlag, fi, 1,
869                                  recType, recTypeClientData);
870         if (fi->file_more)
871         {   /* file_end has been called so reset offset .. */
872             fi->file_offset = fi->file_moffset;
873             lseek(fi->fd, fi->file_moffset, SEEK_SET);
874         }
875         if (r != ZEBRA_OK)
876         {
877             break;
878         }
879         if (sysno)
880         {
881             break;
882         }
883     }
884     file_read_stop (fi);
885     if (fd != -1)
886         close (fd);
887     zh->m_record_type = original_record_type;
888     return r;
889 }
890
891 /*
892   If sysno is provided, then it's used to identify the reocord.
893   If not, and match_criteria is provided, then sysno is guessed
894   If not, and a record is provided, then sysno is got from there
895   
896  */
897 ZEBRA_RES buffer_extract_record(ZebraHandle zh, 
898                                 const char *buf, size_t buf_size,
899                                 int delete_flag,
900                                 int test_mode, 
901                                 const char *recordType,
902                                 SYSNO *sysno,
903                                 const char *match_criteria,
904                                 const char *fname,
905                                 int force_update,
906                                 int allow_update)
907 {
908     SYSNO sysno0 = 0;
909     RecordAttr *recordAttr;
910     struct recExtractCtrl extractCtrl;
911     int r;
912     const char *matchStr = 0;
913     RecType recType = NULL;
914     void *clientData;
915     Record rec;
916     long recordOffset = 0;
917     struct zebra_fetch_control fc;
918     const char *pr_fname = fname;  /* filename to print .. */
919     int show_progress = zh->records_processed < zh->m_file_verbose_limit ? 1:0;
920
921     if (!pr_fname)
922         pr_fname = "<no file>";  /* make it printable if file is omitted */
923
924     fc.fd = -1;
925     fc.record_int_buf = buf;
926     fc.record_int_len = buf_size;
927     fc.record_int_pos = 0;
928     fc.offset_end = 0;
929     fc.record_offset = 0;
930
931     extractCtrl.offset = 0;
932     extractCtrl.readf = zebra_record_int_read;
933     extractCtrl.seekf = zebra_record_int_seek;
934     extractCtrl.tellf = zebra_record_int_tell;
935     extractCtrl.endf = zebra_record_int_end;
936     extractCtrl.first_record = 1;
937     extractCtrl.fh = &fc;
938
939     zebra_rec_keys_reset(zh->reg->keys);
940
941 #if NATTR
942     zebra_rec_keys_reset(zh->reg->sortKeys);
943 #else
944     zh->reg->sortKeys.buf_used = 0;
945 #endif
946     if (zebraExplain_curDatabase (zh->reg->zei, zh->basenames[0]))
947     {
948         if (zebraExplain_newDatabase (zh->reg->zei, zh->basenames[0], 
949                                       zh->m_explain_database))
950             return ZEBRA_FAIL;
951     }
952     
953     if (recordType && *recordType)
954     {
955         yaz_log (YLOG_DEBUG, "Record type explicitly specified: %s", recordType);
956         recType = recType_byName (zh->reg->recTypes, zh->res, recordType,
957                                   &clientData);
958     } 
959     else
960     {
961         if (!(zh->m_record_type))
962         {
963             yaz_log (YLOG_WARN, "No such record type defined");
964             return ZEBRA_FAIL;
965         }
966         yaz_log (YLOG_DEBUG, "Get record type from rgroup: %s",zh->m_record_type);
967         recType = recType_byName (zh->reg->recTypes, zh->res,
968                                   zh->m_record_type, &clientData);
969         recordType = zh->m_record_type;
970     }
971     
972     if (!recType)
973     {
974         yaz_log (YLOG_WARN, "No such record type: %s", recordType);
975         return ZEBRA_FAIL;
976     }
977     
978     extractCtrl.init = extract_init;
979     extractCtrl.tokenAdd = extract_token_add;
980     extractCtrl.schemaAdd = extract_schema_add;
981     extractCtrl.dh = zh->reg->dh;
982     extractCtrl.handle = zh;
983     extractCtrl.match_criteria[0] = '\0';
984     extractCtrl.staticrank = 0;
985     
986     init_extractCtrl(zh, &extractCtrl);
987
988     extract_set_store_data_prepare(&extractCtrl);
989
990     r = (*recType->extract)(clientData, &extractCtrl);
991
992     if (r == RECCTRL_EXTRACT_EOF)
993         return ZEBRA_FAIL;
994     else if (r == RECCTRL_EXTRACT_ERROR_GENERIC)
995     {
996         /* error occured during extraction ... */
997         yaz_log (YLOG_WARN, "extract error: generic");
998         return ZEBRA_FAIL;
999     }
1000     else if (r == RECCTRL_EXTRACT_ERROR_NO_SUCH_FILTER)
1001     {
1002         /* error occured during extraction ... */
1003         yaz_log (YLOG_WARN, "extract error: no such filter");
1004         return ZEBRA_FAIL;
1005     }
1006
1007     all_matches_add(&extractCtrl);
1008         
1009     if (extractCtrl.match_criteria[0])
1010         match_criteria = extractCtrl.match_criteria;
1011
1012     if (!sysno) {
1013
1014         sysno = &sysno0;
1015
1016         if (match_criteria && *match_criteria) {
1017             matchStr = match_criteria;
1018         } else {
1019             if (zh->m_record_id && *zh->m_record_id) {
1020                 matchStr = fileMatchStr (zh, zh->reg->keys, pr_fname, 
1021                                          zh->m_record_id);
1022                 if (!matchStr)
1023                 {
1024                     yaz_log (YLOG_WARN, "Bad match criteria (recordID)");
1025                     return ZEBRA_FAIL;
1026                 }
1027             }
1028         }
1029         if (matchStr) 
1030         {
1031             int db_ord = zebraExplain_get_database_ord(zh->reg->zei);
1032             char *rinfo = dict_lookup_ord(zh->reg->matchDict, db_ord,
1033                                           matchStr);
1034             if (rinfo)
1035             {
1036                 assert(*rinfo == sizeof(*sysno));
1037                 memcpy (sysno, rinfo+1, sizeof(*sysno));
1038             }
1039         }
1040     }
1041     if (zebra_rec_keys_empty(zh->reg->keys))
1042     {
1043         /* the extraction process returned no information - the record
1044            is probably empty - unless flagShowRecords is in use */
1045         if (test_mode)
1046             return ZEBRA_OK;
1047     }
1048
1049     if (! *sysno)
1050     {
1051         /* new record */
1052         if (delete_flag)
1053         {
1054             yaz_log (YLOG_LOG, "delete %s %s %ld", recordType,
1055                          pr_fname, (long) recordOffset);
1056             yaz_log (YLOG_WARN, "cannot delete record above (seems new)");
1057             return ZEBRA_FAIL;
1058         }
1059         if (show_progress)
1060             yaz_log (YLOG_LOG, "add %s %s %ld", recordType, pr_fname,
1061                      (long) recordOffset);
1062         rec = rec_new (zh->reg->records);
1063
1064         *sysno = rec->sysno;
1065
1066         recordAttr = rec_init_attr (zh->reg->zei, rec);
1067         recordAttr->staticrank = extractCtrl.staticrank;
1068
1069         if (matchStr)
1070         {
1071             int db_ord = zebraExplain_get_database_ord(zh->reg->zei);
1072             dict_insert_ord(zh->reg->matchDict, db_ord, matchStr,
1073                             sizeof(*sysno), sysno);
1074         }
1075
1076
1077 #if NATTR
1078         extract_flushSortKeys (zh, *sysno, 1, zh->reg->sortKeys);
1079 #else
1080         extract_flushSortKeys (zh, *sysno, 1, &zh->reg->sortKeys);
1081 #endif
1082         
1083 #if 0
1084         print_rec_keys(zh, zh->reg->keys);
1085 #endif
1086         extract_flushRecordKeys (zh, *sysno, 1, zh->reg->keys,
1087                          recordAttr->staticrank);
1088         zh->records_inserted++;
1089     } 
1090     else
1091     {
1092         /* record already exists */
1093         zebra_rec_keys_t delkeys = zebra_rec_keys_open();
1094 #if NATTR
1095         zebra_rec_keys_t sortKeys = zebra_rec_keys_open();
1096 #else
1097         struct sortKeys sortKeys;
1098 #endif
1099
1100         if (!allow_update)
1101         {
1102             yaz_log (YLOG_LOG, "skipped %s %s %ld", 
1103                          recordType, pr_fname, (long) recordOffset);
1104             logRecord(zh);
1105             return ZEBRA_FAIL;
1106         }
1107
1108         rec = rec_get (zh->reg->records, *sysno);
1109         assert (rec);
1110         
1111         recordAttr = rec_init_attr (zh->reg->zei, rec);
1112
1113         zebra_rec_keys_set_buf(delkeys,
1114                                rec->info[recInfo_delKeys],
1115                                rec->size[recInfo_delKeys],
1116                                0);
1117 #if NATTR
1118         zebra_rec_keys_set_buf(sortKeys,
1119                                rec->info[recInfo_sortKeys],
1120                                rec->size[recInfo_sortKeys],
1121                                0);
1122 #else
1123         sortKeys.buf_used = rec->size[recInfo_sortKeys];
1124         sortKeys.buf = rec->info[recInfo_sortKeys];
1125 #endif
1126
1127 #if NATTR
1128         extract_flushSortKeys (zh, *sysno, 0, sortKeys);
1129 #else
1130         extract_flushSortKeys (zh, *sysno, 0, &sortKeys);
1131 #endif
1132         extract_flushRecordKeys (zh, *sysno, 0, delkeys,
1133                                  recordAttr->staticrank);
1134         if (delete_flag)
1135         {
1136             /* record going to be deleted */
1137             if (zebra_rec_keys_empty(delkeys))
1138             {
1139                 yaz_log (YLOG_LOG, "delete %s %s %ld", recordType,
1140                      pr_fname, (long) recordOffset);
1141                 yaz_log (YLOG_WARN, "cannot delete file above, "
1142                              "storeKeys false (3)");
1143             }
1144             else
1145             {
1146                 if (show_progress)
1147                     yaz_log (YLOG_LOG, "delete %s %s %ld", recordType,
1148                              pr_fname, (long) recordOffset);
1149                 zh->records_deleted++;
1150                 if (matchStr)
1151                 {
1152                     int db_ord = zebraExplain_get_database_ord(zh->reg->zei);
1153                     dict_delete_ord(zh->reg->matchDict, db_ord, matchStr);
1154                 }
1155                 rec_del (zh->reg->records, &rec);
1156             }
1157             rec_rm (&rec);
1158             logRecord(zh);
1159             return ZEBRA_OK;
1160         }
1161         else
1162         {
1163             if (show_progress)
1164                     yaz_log (YLOG_LOG, "update %s %s %ld", recordType,
1165                              pr_fname, (long) recordOffset);
1166             recordAttr->staticrank = extractCtrl.staticrank;
1167 #if NATTR
1168             extract_flushSortKeys (zh, *sysno, 1, zh->reg->sortKeys);
1169 #else
1170             extract_flushSortKeys (zh, *sysno, 1, &zh->reg->sortKeys);
1171 #endif
1172             extract_flushRecordKeys (zh, *sysno, 1, zh->reg->keys, 
1173                                          recordAttr->staticrank);
1174             zh->records_updated++;
1175         }
1176         zebra_rec_keys_close(delkeys);
1177 #if NATTR
1178         zebra_rec_keys_close(sortKeys);
1179 #endif
1180     }
1181     /* update file type */
1182     xfree (rec->info[recInfo_fileType]);
1183     rec->info[recInfo_fileType] =
1184         rec_strdup (recordType, &rec->size[recInfo_fileType]);
1185
1186     /* update filename */
1187     xfree (rec->info[recInfo_filename]);
1188     rec->info[recInfo_filename] =
1189         rec_strdup (fname, &rec->size[recInfo_filename]);
1190
1191     /* update delete keys */
1192     xfree (rec->info[recInfo_delKeys]);
1193     if (!zebra_rec_keys_empty(zh->reg->keys) && zh->m_store_keys == 1)
1194     {
1195         zebra_rec_keys_get_buf(zh->reg->keys,
1196                                &rec->info[recInfo_delKeys],
1197                                &rec->size[recInfo_delKeys]);
1198     }
1199     else
1200     {
1201         rec->info[recInfo_delKeys] = NULL;
1202         rec->size[recInfo_delKeys] = 0;
1203     }
1204     /* update sort keys */
1205     xfree (rec->info[recInfo_sortKeys]);
1206
1207 #if NATTR
1208     zebra_rec_keys_get_buf(zh->reg->sortKeys,
1209                            &rec->info[recInfo_sortKeys],
1210                            &rec->size[recInfo_sortKeys]);
1211 #else
1212     rec->size[recInfo_sortKeys] = zh->reg->sortKeys.buf_used;
1213     rec->info[recInfo_sortKeys] = zh->reg->sortKeys.buf;
1214     zh->reg->sortKeys.buf = NULL;
1215     zh->reg->sortKeys.buf_max = 0;
1216 #endif
1217
1218     /* save file size of original record */
1219     zebraExplain_recordBytesIncrement (zh->reg->zei,
1220                                        - recordAttr->recordSize);
1221 #if 0
1222     recordAttr->recordSize = fi->file_moffset - recordOffset;
1223     if (!recordAttr->recordSize)
1224         recordAttr->recordSize = fi->file_max - recordOffset;
1225 #else
1226     recordAttr->recordSize = buf_size;
1227 #endif
1228     zebraExplain_recordBytesIncrement (zh->reg->zei,
1229                                        recordAttr->recordSize);
1230
1231     /* set run-number for this record */
1232     recordAttr->runNumber =
1233         zebraExplain_runNumberIncrement (zh->reg->zei, 0);
1234
1235     /* update store data */
1236     xfree (rec->info[recInfo_storeData]);
1237
1238     /* update store data */
1239     if (zh->store_data_buf)
1240     {
1241         rec->size[recInfo_storeData] = zh->store_data_size;
1242         rec->info[recInfo_storeData] = zh->store_data_buf;
1243         zh->store_data_buf = 0;
1244     }
1245     else if (zh->m_store_data)
1246     {
1247         rec->size[recInfo_storeData] = recordAttr->recordSize;
1248         rec->info[recInfo_storeData] = (char *)
1249             xmalloc (recordAttr->recordSize);
1250         memcpy (rec->info[recInfo_storeData], buf, recordAttr->recordSize);
1251     }
1252     else
1253     {
1254         rec->info[recInfo_storeData] = NULL;
1255         rec->size[recInfo_storeData] = 0;
1256     }
1257     /* update database name */
1258     xfree (rec->info[recInfo_databaseName]);
1259     rec->info[recInfo_databaseName] =
1260         rec_strdup (zh->basenames[0], &rec->size[recInfo_databaseName]); 
1261
1262     /* update offset */
1263     recordAttr->recordOffset = recordOffset;
1264     
1265     /* commit this record */
1266     rec_put (zh->reg->records, &rec);
1267     logRecord(zh);
1268     return ZEBRA_OK;
1269 }
1270
1271 int explain_extract (void *handle, Record rec, data1_node *n)
1272 {
1273     ZebraHandle zh = (ZebraHandle) handle;
1274     struct recExtractCtrl extractCtrl;
1275
1276     if (zebraExplain_curDatabase (zh->reg->zei,
1277                                   rec->info[recInfo_databaseName]))
1278     {
1279         abort();
1280         if (zebraExplain_newDatabase (zh->reg->zei,
1281                                       rec->info[recInfo_databaseName], 0))
1282             abort ();
1283     }
1284
1285     zebra_rec_keys_reset(zh->reg->keys);
1286     
1287 #if NATTR
1288     zebra_rec_keys_reset(zh->reg->sortKeys);
1289 #else
1290     zh->reg->sortKeys.buf_used = 0;
1291 #endif
1292     extractCtrl.init = extract_init;
1293     extractCtrl.tokenAdd = extract_token_add;
1294     extractCtrl.schemaAdd = extract_schema_add;
1295     extractCtrl.dh = zh->reg->dh;
1296
1297     init_extractCtrl(zh, &extractCtrl);
1298
1299     extractCtrl.flagShowRecords = 0;
1300     extractCtrl.match_criteria[0] = '\0';
1301     extractCtrl.staticrank = 0;
1302     extractCtrl.handle = handle;
1303     extractCtrl.first_record = 1;
1304     
1305     extract_set_store_data_prepare(&extractCtrl);
1306
1307     if (n)
1308         grs_extract_tree(&extractCtrl, n);
1309
1310     if (rec->size[recInfo_delKeys])
1311     {
1312         zebra_rec_keys_t delkeys = zebra_rec_keys_open();
1313         
1314 #if NATTR
1315         zebra_rec_keys_t sortkeys = zebra_rec_keys_open();
1316 #else
1317         struct sortKeys sortkeys;
1318 #endif
1319
1320         zebra_rec_keys_set_buf(delkeys, rec->info[recInfo_delKeys],
1321                                rec->size[recInfo_delKeys],
1322                                0);
1323         extract_flushRecordKeys (zh, rec->sysno, 0, delkeys, 0);
1324         zebra_rec_keys_close(delkeys);
1325 #if NATTR
1326         zebra_rec_keys_set_buf(sortkeys, rec->info[recInfo_sortKeys],
1327                                rec->size[recInfo_sortKeys],
1328                                0);
1329
1330         extract_flushSortKeys (zh, rec->sysno, 0, sortkeys);
1331         zebra_rec_keys_close(sortkeys);
1332 #else
1333         sortkeys.buf_used = rec->size[recInfo_sortKeys];
1334         sortkeys.buf = rec->info[recInfo_sortKeys];
1335         extract_flushSortKeys (zh, rec->sysno, 0, &sortkeys);
1336 #endif
1337     }
1338     extract_flushRecordKeys (zh, rec->sysno, 1, zh->reg->keys, 0);
1339 #if NATTR
1340     extract_flushSortKeys (zh, rec->sysno, 1, zh->reg->sortKeys);
1341 #else
1342     extract_flushSortKeys (zh, rec->sysno, 1, &zh->reg->sortKeys);
1343 #endif
1344
1345     xfree (rec->info[recInfo_delKeys]);
1346     zebra_rec_keys_get_buf(zh->reg->keys,
1347                            &rec->info[recInfo_delKeys], 
1348                            &rec->size[recInfo_delKeys]);
1349
1350     xfree (rec->info[recInfo_sortKeys]);
1351 #if NATTR
1352     zebra_rec_keys_get_buf(zh->reg->sortKeys,
1353                            &rec->info[recInfo_sortKeys],
1354                            &rec->size[recInfo_sortKeys]);
1355 #else
1356     rec->size[recInfo_sortKeys] = zh->reg->sortKeys.buf_used;
1357     rec->info[recInfo_sortKeys] = zh->reg->sortKeys.buf;
1358     zh->reg->sortKeys.buf = NULL;
1359     zh->reg->sortKeys.buf_max = 0;
1360 #endif
1361
1362     return 0;
1363 }
1364
1365 void extract_rec_keys_adjust(ZebraHandle zh, int is_insert,
1366                              zebra_rec_keys_t reckeys)
1367 {
1368     ZebraExplainInfo zei = zh->reg->zei;
1369     struct ord_stat {
1370         int no;
1371         int ord;
1372         struct ord_stat *next;
1373     };
1374
1375     if (zebra_rec_keys_rewind(reckeys))
1376     {
1377         struct ord_stat *ord_list = 0;
1378         struct ord_stat *p;
1379         size_t slen;
1380         const char *str;
1381         struct it_key key_in;
1382         while(zebra_rec_keys_read(reckeys, &str, &slen, &key_in))
1383         {
1384             int ord = key_in.mem[0]; 
1385
1386             for (p = ord_list; p ; p = p->next)
1387                 if (p->ord == ord)
1388                 {
1389                     p->no++;
1390                     break;
1391                 }
1392             if (!p)
1393             {
1394                 p = xmalloc(sizeof(*p));
1395                 p->no = 1;
1396                 p->ord = ord;
1397                 p->next = ord_list;
1398                 ord_list = p;
1399             }
1400         }
1401
1402         p = ord_list;
1403         while (p)
1404         {
1405             struct ord_stat *p1 = p;
1406
1407             if (is_insert)
1408                 zebraExplain_ord_adjust_occurrences(zei, p->ord, p->no, 1);
1409             else
1410                 zebraExplain_ord_adjust_occurrences(zei, p->ord, - p->no, -1);
1411             p = p->next;
1412             xfree(p1);
1413         }
1414     }
1415 }
1416
1417 void extract_flushRecordKeys (ZebraHandle zh, SYSNO sysno,
1418                               int cmd,
1419                               zebra_rec_keys_t reckeys,
1420                               zint staticrank)
1421 {
1422     ZebraExplainInfo zei = zh->reg->zei;
1423
1424     extract_rec_keys_adjust(zh, cmd, reckeys);
1425
1426     if (!zh->reg->key_buf)
1427     {
1428         int mem= 1024*1024* atoi( res_get_def( zh->res, "memmax", "8"));
1429         if (mem <= 0)
1430         {
1431             yaz_log(YLOG_WARN, "Invalid memory setting, using default 8 MB");
1432             mem= 1024*1024*8;
1433         }
1434         /* FIXME: That "8" should be in a default settings include */
1435         /* not hard-coded here! -H */
1436         zh->reg->key_buf = (char**) xmalloc (mem);
1437         zh->reg->ptr_top = mem/sizeof(char*);
1438         zh->reg->ptr_i = 0;
1439         zh->reg->key_buf_used = 0;
1440         zh->reg->key_file_no = 0;
1441     }
1442     zebraExplain_recordCountIncrement (zei, cmd ? 1 : -1);
1443
1444     if (zebra_rec_keys_rewind(reckeys))
1445     {
1446         size_t slen;
1447         const char *str;
1448         struct it_key key_in;
1449         while(zebra_rec_keys_read(reckeys, &str, &slen, &key_in))
1450         {
1451             int ch = 0;
1452             struct it_key key_out;
1453             zint *keyp = key_out.mem;
1454
1455             assert(key_in.len == 4);
1456             
1457             /* check for buffer overflow */
1458             if (zh->reg->key_buf_used + 1024 > 
1459                 (zh->reg->ptr_top -zh->reg->ptr_i)*sizeof(char*))
1460                 extract_flushWriteKeys (zh, 0);
1461             
1462             ++(zh->reg->ptr_i);
1463             assert(zh->reg->ptr_i > 0);
1464             (zh->reg->key_buf)[zh->reg->ptr_top - zh->reg->ptr_i] =
1465                 (char*)zh->reg->key_buf + zh->reg->key_buf_used;
1466
1467             /* encode the ordinal value (field/use/attribute) .. */
1468             ch = (int) key_in.mem[0];
1469             zh->reg->key_buf_used +=
1470                 key_SU_encode(ch, (char*)zh->reg->key_buf +
1471                               zh->reg->key_buf_used);
1472
1473             /* copy the 0-terminated stuff from str to output */
1474             memcpy((char*)zh->reg->key_buf + zh->reg->key_buf_used, str, slen);
1475             zh->reg->key_buf_used += slen;
1476             ((char*)zh->reg->key_buf)[(zh->reg->key_buf_used)++] = '\0';
1477
1478             /* the delete/insert indicator */
1479             ((char*)zh->reg->key_buf)[(zh->reg->key_buf_used)++] = cmd;
1480
1481             if (zh->m_staticrank) /* rank config enabled ? */
1482             {
1483                 if (staticrank < 0)
1484                 {
1485                     yaz_log(YLOG_WARN, "staticrank = %ld. Setting to 0",
1486                             (long) staticrank);
1487                     staticrank = 0;
1488                 }
1489                 *keyp++ = staticrank;
1490                 key_out.len = 4;
1491             }
1492             else
1493                 key_out.len = 3;
1494             
1495             if (key_in.mem[1]) /* filter specified record ID */
1496                 *keyp++ = key_in.mem[1];
1497             else
1498                 *keyp++ = sysno;
1499             *keyp++ = key_in.mem[2];  /* section_id */
1500             *keyp++ = key_in.mem[3];  /* sequence .. */
1501             
1502             memcpy((char*)zh->reg->key_buf + zh->reg->key_buf_used,
1503                    &key_out, sizeof(key_out));
1504             (zh->reg->key_buf_used) += sizeof(key_out);
1505         }
1506     }
1507 }
1508
1509 void extract_flushWriteKeys (ZebraHandle zh, int final)
1510         /* optimizing: if final=1, and no files written yet */
1511         /* push the keys directly to merge, sidestepping the */
1512         /* temp file altogether. Speeds small updates */
1513 {
1514     FILE *outf;
1515     char out_fname[200];
1516     char *prevcp, *cp;
1517     struct encode_info encode_info;
1518     int ptr_i = zh->reg->ptr_i;
1519     int temp_policy;
1520 #if SORT_EXTRA
1521     int i;
1522 #endif
1523     if (!zh->reg->key_buf || ptr_i <= 0)
1524     {
1525         yaz_log (YLOG_DEBUG, "  nothing to flush section=%d buf=%p i=%d",
1526                zh->reg->key_file_no, zh->reg->key_buf, ptr_i);
1527         yaz_log (YLOG_DEBUG, "  buf=%p ",
1528                zh->reg->key_buf);
1529         yaz_log (YLOG_DEBUG, "  ptr=%d ",zh->reg->ptr_i);
1530         yaz_log (YLOG_DEBUG, "  reg=%p ",zh->reg);
1531                
1532         return;
1533     }
1534
1535     (zh->reg->key_file_no)++;
1536     yaz_log (YLOG_LOG, "sorting section %d", (zh->reg->key_file_no));
1537     yaz_log (YLOG_DEBUG, "  sort_buff at %p n=%d",
1538                     zh->reg->key_buf + zh->reg->ptr_top - ptr_i,ptr_i);
1539 #if !SORT_EXTRA
1540     qsort (zh->reg->key_buf + zh->reg->ptr_top - ptr_i, ptr_i,
1541                sizeof(char*), key_qsort_compare);
1542
1543     /* zebra.cfg: tempfiles:  
1544        Y: always use temp files (old way) 
1545        A: use temp files, if more than one (auto) 
1546           = if this is both the last and the first 
1547        N: never bother with temp files (new) */
1548
1549     temp_policy=toupper(res_get_def(zh->res,"tempfiles","auto")[0]);
1550     if (temp_policy != 'Y' && temp_policy != 'N' && temp_policy != 'A') {
1551         yaz_log (YLOG_WARN, "Illegal tempfiles setting '%c'. using 'Auto' ", 
1552                         temp_policy);
1553         temp_policy='A';
1554     }
1555
1556     if (   ( temp_policy =='N' )   ||     /* always from memory */
1557          ( ( temp_policy =='A' ) &&       /* automatic */
1558              (zh->reg->key_file_no == 1) &&  /* this is first time */
1559              (final) ) )                     /* and last (=only) time */
1560     { /* go directly from memory */
1561         zh->reg->key_file_no =0; /* signal not to read files */
1562         zebra_index_merge(zh); 
1563         zh->reg->ptr_i = 0;
1564         zh->reg->key_buf_used = 0; 
1565         return; 
1566     }
1567
1568     /* Not doing directly from memory, write into a temp file */
1569     extract_get_fname_tmp (zh, out_fname, zh->reg->key_file_no);
1570
1571     if (!(outf = fopen (out_fname, "wb")))
1572     {
1573         yaz_log (YLOG_FATAL|YLOG_ERRNO, "fopen %s", out_fname);
1574         exit (1);
1575     }
1576     yaz_log (YLOG_LOG, "writing section %d", zh->reg->key_file_no);
1577     prevcp = cp = (zh->reg->key_buf)[zh->reg->ptr_top - ptr_i];
1578     
1579     encode_key_init (&encode_info);
1580     encode_key_write (cp, &encode_info, outf);
1581     
1582     while (--ptr_i > 0)
1583     {
1584         cp = (zh->reg->key_buf)[zh->reg->ptr_top - ptr_i];
1585         if (strcmp (cp, prevcp))
1586         {
1587             encode_key_flush ( &encode_info, outf);
1588             encode_key_init (&encode_info);
1589             encode_key_write (cp, &encode_info, outf);
1590             prevcp = cp;
1591         }
1592         else
1593             encode_key_write (cp + strlen(cp), &encode_info, outf);
1594     }
1595     encode_key_flush ( &encode_info, outf);
1596 #else
1597     qsort (key_buf + ptr_top-ptr_i, ptr_i, sizeof(char*), key_x_compare);
1598     extract_get_fname_tmp (out_fname, key_file_no);
1599
1600     if (!(outf = fopen (out_fname, "wb")))
1601     {
1602         yaz_log (YLOG_FATAL|YLOG_ERRNO, "fopen %s", out_fname);
1603         exit (1);
1604     }
1605     yaz_log (YLOG_LOG, "writing section %d", key_file_no);
1606     i = ptr_i;
1607     prevcp =  key_buf[ptr_top-i];
1608     while (1)
1609         if (!--i || strcmp (prevcp, key_buf[ptr_top-i]))
1610         {
1611             key_y_len = strlen(prevcp)+1;
1612 #if 0
1613             yaz_log (YLOG_LOG, "key_y_len: %2d %02x %02x %s",
1614                       key_y_len, prevcp[0], prevcp[1], 2+prevcp);
1615 #endif
1616             qsort (key_buf + ptr_top-ptr_i, ptr_i - i,
1617                                    sizeof(char*), key_y_compare);
1618             cp = key_buf[ptr_top-ptr_i];
1619             --key_y_len;
1620             encode_key_init (&encode_info);
1621             encode_key_write (cp, &encode_info, outf);
1622             while (--ptr_i > i)
1623             {
1624                 cp = key_buf[ptr_top-ptr_i];
1625                 encode_key_write (cp+key_y_len, &encode_info, outf);
1626             }
1627             encode_key_flush ( &encode_info, outf);
1628             if (!i)
1629                 break;
1630             prevcp = key_buf[ptr_top-ptr_i];
1631         }
1632 #endif
1633     if (fclose (outf))
1634     {
1635         yaz_log (YLOG_FATAL|YLOG_ERRNO, "fclose %s", out_fname);
1636         exit (1);
1637     }
1638     yaz_log (YLOG_LOG, "finished section %d", zh->reg->key_file_no);
1639     zh->reg->ptr_i = 0;
1640     zh->reg->key_buf_used = 0;
1641 }
1642
1643 ZEBRA_RES zebra_snippets_rec_keys(ZebraHandle zh,
1644                                   zebra_rec_keys_t reckeys,
1645                                   zebra_snippets *snippets)
1646 {
1647     NMEM nmem = nmem_create();
1648     if (zebra_rec_keys_rewind(reckeys)) 
1649     {
1650         const char *str;
1651         size_t slen;
1652         struct it_key key;
1653         while (zebra_rec_keys_read(reckeys, &str, &slen, &key))
1654         {
1655             char dst_buf[IT_MAX_WORD];
1656             char *dst_term = dst_buf;
1657             int ord, seqno;
1658             int index_type;
1659             assert(key.len <= 4 && key.len > 2);
1660             seqno = (int) key.mem[key.len-1];
1661             ord = key.mem[0];
1662             
1663             zebraExplain_lookup_ord(zh->reg->zei, ord, &index_type,
1664                                     0/* db */, 0/* set */, 0/* use */,
1665                                     0 /* string_index */);
1666             assert(index_type);
1667             zebra_term_untrans_iconv(zh, nmem, index_type,
1668                                      &dst_term, str);
1669             zebra_snippets_append(snippets, seqno, ord, dst_term);
1670             nmem_reset(nmem);
1671         }
1672     }
1673     nmem_destroy(nmem);
1674     return ZEBRA_OK;
1675 }
1676
1677 void print_rec_keys(ZebraHandle zh, zebra_rec_keys_t reckeys)
1678 {
1679     yaz_log(YLOG_LOG, "print_rec_keys");
1680     if (zebra_rec_keys_rewind(reckeys))
1681     {
1682         const char *str;
1683         size_t slen;
1684         struct it_key key;
1685         while (zebra_rec_keys_read(reckeys, &str, &slen, &key))
1686         {
1687             char dst_buf[IT_MAX_WORD];
1688             int seqno;
1689             int index_type;
1690             const char *db = 0;
1691             assert(key.len <= 4 && key.len > 2);
1692
1693             zebraExplain_lookup_ord(zh->reg->zei,
1694                                     key.mem[0], &index_type, &db, 0, 0, 0);
1695             
1696             seqno = (int) key.mem[key.len-1];
1697             
1698             zebra_term_untrans(zh, index_type, dst_buf, str);
1699             
1700             yaz_log(YLOG_LOG, "ord=" ZINT_FORMAT " seqno=%d term=%s",
1701                     key.mem[0], seqno, dst_buf); 
1702         }
1703     }
1704 }
1705
1706 void extract_add_index_string(RecWord *p, const char *str, int length)
1707 {
1708     struct it_key key;
1709
1710     ZebraHandle zh = p->extractCtrl->handle;
1711     ZebraExplainInfo zei = zh->reg->zei;
1712     int ch;
1713
1714     if (p->index_name)
1715     {
1716         ch = zebraExplain_lookup_attr_str(zei, p->index_type, p->index_name);
1717         if (ch < 0)
1718             ch = zebraExplain_add_attr_str(zei, p->index_type, p->index_name);
1719     }
1720     else
1721     {
1722 #if NATTR
1723         return;
1724 #else
1725         ch = zebraExplain_lookup_attr_su(zei, p->index_type, 
1726                                          p->attrSet, p->attrUse);
1727         if (ch < 0)
1728             ch = zebraExplain_add_attr_su(zei, p->index_type,
1729                                           p->attrSet, p->attrUse);
1730 #endif
1731     }
1732     key.len = 4;
1733     key.mem[0] = ch;
1734     key.mem[1] = p->record_id;
1735     key.mem[2] = p->section_id;
1736     key.mem[3] = p->seqno;
1737
1738 #if 0
1739     if (1)
1740     {
1741         char strz[80];
1742         int i;
1743
1744         strz[0] = 0;
1745         for (i = 0; i<length && i < 20; i++)
1746             sprintf(strz+strlen(strz), "%02X", str[i] & 0xff);
1747         /* just for debugging .. */
1748         yaz_log(YLOG_LOG, "add: set=%d use=%d "
1749                 "record_id=%lld section_id=%lld seqno=%lld %s",
1750                 p->attrSet, p->attrUse, p->record_id, p->section_id, p->seqno,
1751                 strz);
1752     }
1753 #endif
1754
1755     zebra_rec_keys_write(zh->reg->keys, str, length, &key);
1756 }
1757
1758 #if NATTR
1759 static void extract_add_sort_string (RecWord *p, const char *str, int length)
1760 {
1761     struct it_key key;
1762
1763     ZebraHandle zh = p->extractCtrl->handle;
1764     ZebraExplainInfo zei = zh->reg->zei;
1765     int ch;
1766
1767     if (p->index_name)
1768     {
1769         ch = zebraExplain_lookup_attr_str(zei, p->index_type, p->index_name);
1770         if (ch < 0)
1771             ch = zebraExplain_add_attr_str(zei, p->index_type, p->index_name);
1772     }
1773     else
1774     {
1775         return;
1776     }
1777     key.len = 4;
1778     key.mem[0] = ch;
1779     key.mem[1] = p->record_id;
1780     key.mem[2] = p->section_id;
1781     key.mem[3] = p->seqno;
1782
1783     zebra_rec_keys_write(zh->reg->sortKeys, str, length, &key);
1784 }
1785 #else
1786 static void extract_add_sort_string (RecWord *p, const char *str, int length)
1787 {
1788     ZebraHandle zh = p->extractCtrl->handle;
1789     struct sortKeys *sk = &zh->reg->sortKeys;
1790     int off = 0;
1791
1792     while (off < sk->buf_used)
1793     {
1794         int set, use, slen;
1795
1796         off += key_SU_decode(&set, (unsigned char *) sk->buf + off);
1797         off += key_SU_decode(&use, (unsigned char *) sk->buf + off);
1798         off += key_SU_decode(&slen, (unsigned char *) sk->buf + off);
1799         off += slen;
1800         if (p->attrSet == set && p->attrUse == use)
1801             return;
1802     }
1803     assert (off == sk->buf_used);
1804     
1805     if (sk->buf_used + IT_MAX_WORD > sk->buf_max)
1806     {
1807         char *b;
1808         
1809         b = (char *) xmalloc (sk->buf_max += 128000);
1810         if (sk->buf_used > 0)
1811             memcpy (b, sk->buf, sk->buf_used);
1812         xfree (sk->buf);
1813         sk->buf = b;
1814     }
1815     off += key_SU_encode(p->attrSet, sk->buf + off);
1816     off += key_SU_encode(p->attrUse, sk->buf + off);
1817     off += key_SU_encode(length, sk->buf + off);
1818     memcpy (sk->buf + off, str, length);
1819     sk->buf_used = off + length;
1820 }
1821 #endif
1822
1823 void extract_add_string (RecWord *p, const char *string, int length)
1824 {
1825     assert (length > 0);
1826     if (zebra_maps_is_sort (p->zebra_maps, p->index_type))
1827         extract_add_sort_string (p, string, length);
1828     else
1829         extract_add_index_string (p, string, length);
1830 }
1831
1832 static void extract_add_incomplete_field (RecWord *p)
1833 {
1834     const char *b = p->term_buf;
1835     int remain = p->term_len;
1836     const char **map = 0;
1837     
1838     yaz_log(YLOG_DEBUG, "Incomplete field, w='%.*s'", p->term_len, p->term_buf);
1839
1840     if (remain > 0)
1841         map = zebra_maps_input(p->zebra_maps, p->index_type, &b, remain, 0);
1842
1843     while (map)
1844     {
1845         char buf[IT_MAX_WORD+1];
1846         int i, remain;
1847
1848         /* Skip spaces */
1849         while (map && *map && **map == *CHR_SPACE)
1850         {
1851             remain = p->term_len - (b - p->term_buf);
1852             if (remain > 0)
1853                 map = zebra_maps_input(p->zebra_maps, p->index_type, &b,
1854                                        remain, 0);
1855             else
1856                 map = 0;
1857         }
1858         if (!map)
1859             break;
1860         i = 0;
1861         while (map && *map && **map != *CHR_SPACE)
1862         {
1863             const char *cp = *map;
1864
1865             while (i < IT_MAX_WORD && *cp)
1866                 buf[i++] = *(cp++);
1867             remain = p->term_len - (b - p->term_buf);
1868             if (remain > 0)
1869                 map = zebra_maps_input(p->zebra_maps, p->index_type, &b, remain, 0);
1870             else
1871                 map = 0;
1872         }
1873         if (!i)
1874             return;
1875         extract_add_string (p, buf, i);
1876         p->seqno++;
1877     }
1878 }
1879
1880 static void extract_add_complete_field (RecWord *p)
1881 {
1882     const char *b = p->term_buf;
1883     char buf[IT_MAX_WORD+1];
1884     const char **map = 0;
1885     int i = 0, remain = p->term_len;
1886
1887     yaz_log(YLOG_DEBUG, "Complete field, w='%.*s'",
1888             p->term_len, p->term_buf);
1889
1890     if (remain > 0)
1891         map = zebra_maps_input (p->zebra_maps, p->index_type, &b, remain, 1);
1892
1893     while (remain > 0 && i < IT_MAX_WORD)
1894     {
1895         while (map && *map && **map == *CHR_SPACE)
1896         {
1897             remain = p->term_len - (b - p->term_buf);
1898
1899             if (remain > 0)
1900             {
1901                 int first = i ? 0 : 1;  /* first position */
1902                 map = zebra_maps_input(p->zebra_maps, p->index_type, &b, remain, first);
1903             }
1904             else
1905                 map = 0;
1906         }
1907         if (!map)
1908             break;
1909
1910         if (i && i < IT_MAX_WORD)
1911             buf[i++] = *CHR_SPACE;
1912         while (map && *map && **map != *CHR_SPACE)
1913         {
1914             const char *cp = *map;
1915
1916             if (**map == *CHR_CUT)
1917             {
1918                 i = 0;
1919             }
1920             else
1921             {
1922                 if (i >= IT_MAX_WORD)
1923                     break;
1924                 yaz_log(YLOG_DEBUG, "Adding string to index '%d'", **map);
1925                 while (i < IT_MAX_WORD && *cp)
1926                     buf[i++] = *(cp++);
1927             }
1928             remain = p->term_len  - (b - p->term_buf);
1929             if (remain > 0)
1930             {
1931                 map = zebra_maps_input (p->zebra_maps, p->index_type, &b,
1932                                         remain, 0);
1933             }
1934             else
1935                 map = 0;
1936         }
1937     }
1938     if (!i)
1939         return;
1940     extract_add_string (p, buf, i);
1941 }
1942
1943 void extract_token_add (RecWord *p)
1944 {
1945     WRBUF wrbuf;
1946 #if 0
1947     yaz_log (YLOG_LOG, "token_add "
1948              "reg_type=%c attrSet=%d attrUse=%d seqno=%d s=%.*s",
1949              p->reg_type, p->attrSet, p->attrUse, p->seqno, p->length,
1950              p->string);
1951 #endif
1952     if ((wrbuf = zebra_replace(p->zebra_maps, p->index_type, 0,
1953                                p->term_buf, p->term_len)))
1954     {
1955         p->term_buf = wrbuf_buf(wrbuf);
1956         p->term_len = wrbuf_len(wrbuf);
1957     }
1958     if (zebra_maps_is_complete (p->zebra_maps, p->index_type))
1959         extract_add_complete_field (p);
1960     else
1961         extract_add_incomplete_field(p);
1962 }
1963
1964 static void extract_set_store_data_cb(struct recExtractCtrl *p,
1965                                       void *buf, size_t sz)
1966 {
1967     ZebraHandle zh = (ZebraHandle) p->handle;
1968
1969     xfree(zh->store_data_buf);
1970     zh->store_data_buf = 0;
1971     zh->store_data_size = 0;
1972     if (buf && sz)
1973     {
1974         zh->store_data_buf = xmalloc(sz);
1975         zh->store_data_size = sz;
1976         memcpy(zh->store_data_buf, buf, sz);
1977     }
1978 }
1979
1980 static void extract_set_store_data_prepare(struct recExtractCtrl *p)
1981 {
1982     ZebraHandle zh = (ZebraHandle) p->handle;
1983     xfree(zh->store_data_buf);
1984     zh->store_data_buf = 0;
1985     zh->store_data_size = 0;
1986     p->setStoreData = extract_set_store_data_cb;
1987 }
1988
1989 void extract_schema_add (struct recExtractCtrl *p, Odr_oid *oid)
1990 {
1991     ZebraHandle zh = (ZebraHandle) p->handle;
1992     zebraExplain_addSchema (zh->reg->zei, oid);
1993 }
1994
1995 #if NATTR
1996 #error not done yet with zebra_rec_keys_t
1997 void extract_flushSortKeys (ZebraHandle zh, SYSNO sysno,
1998                             int cmd, struct recKeys *reckeys)
1999 {
2000     SortIdx sortIdx = zh->reg->sortIdx;
2001     void *decode_handle = iscz1_start();
2002     int off = 0;
2003     int ch = 0;
2004
2005     while (off < reckeys->buf_used)
2006     {
2007         const char *src = reckeys->buf + off;
2008         struct it_key key;
2009         char *dst = (char*) &key;
2010
2011         iscz1_decode(decode_handle, &dst, &src);
2012         assert(key.len == 4);
2013
2014         ch = (int) key.mem[0];  /* ordinal for field/use/attribute */
2015
2016         sortIdx_type(sortIdx, ch);
2017         if (cmd == 1)
2018             sortIdx_add(sortIdx, src, strlen(src));
2019         else
2020             sortIdx_add(sortIdx, "", 1);
2021         
2022         src += strlen(src);
2023         src++;
2024
2025         off = src - reckeys->buf;
2026     }
2027     assert (off == reckeys->buf_used);
2028     iscz1_stop(decode_handle);
2029 }
2030 #else
2031 void extract_flushSortKeys (ZebraHandle zh, SYSNO sysno,
2032                             int cmd, struct sortKeys *sk)
2033 {
2034     SortIdx sortIdx = zh->reg->sortIdx;
2035     int off = 0;
2036
2037     sortIdx_sysno (sortIdx, sysno);
2038
2039     while (off < sk->buf_used)
2040     {
2041         int set, use, slen;
2042         
2043         off += key_SU_decode(&set, (unsigned char *) sk->buf + off);
2044         off += key_SU_decode(&use, (unsigned char *) sk->buf + off);
2045         off += key_SU_decode(&slen, (unsigned char *) sk->buf + off);
2046         
2047         sortIdx_type(sortIdx, use);
2048         if (cmd == 1)
2049             sortIdx_add(sortIdx, sk->buf + off, slen);
2050         else
2051             sortIdx_add(sortIdx, "", 1);
2052         off += slen;
2053     }
2054 }
2055 #endif
2056
2057 void encode_key_init (struct encode_info *i)
2058 {
2059     i->sysno = 0;
2060     i->seqno = 0;
2061     i->cmd = -1;
2062     i->prevsys=0;
2063     i->prevseq=0;
2064     i->prevcmd=-1;
2065     i->keylen=0;
2066     i->encode_handle = iscz1_start();
2067     i->decode_handle = iscz1_start();
2068 }
2069
2070 #define OLDENCODE 1
2071
2072 #ifdef OLDENCODE
2073 /* this is the old encode_key_write 
2074  * may be deleted once we are confident that the new works
2075  * HL 15-oct-2002
2076  */
2077 void encode_key_write (char *k, struct encode_info *i, FILE *outf)
2078 {
2079     struct it_key key;
2080     char *bp = i->buf, *bp0;
2081     const char *src = (char *) &key;
2082
2083     /* copy term to output buf */
2084     while ((*bp++ = *k++))
2085         ;
2086     /* and copy & align key so we can mangle */
2087     memcpy (&key, k+1, sizeof(struct it_key));  /* *k is insert/delete */
2088
2089 #if 0
2090     /* debugging */
2091     key_logdump_txt(YLOG_LOG, &key, *k ? "i" : "d");
2092 #endif
2093     assert(key.mem[0] >= 0);
2094
2095     bp0 = bp++;
2096     iscz1_encode(i->encode_handle, &bp, &src);
2097
2098     *bp0 = (*k * 128) + bp - bp0 - 1; /* length and insert/delete combined */
2099     if (fwrite (i->buf, bp - i->buf, 1, outf) != 1)
2100     {
2101         yaz_log (YLOG_FATAL|YLOG_ERRNO, "fwrite");
2102         exit (1);
2103     }
2104
2105 #if 0
2106     /* debugging */
2107     if (1)
2108     {
2109         struct it_key key2;
2110         const char *src = bp0+1;
2111         char *dst = (char*) &key2;
2112         iscz1_decode(i->decode_handle, &dst, &src);
2113
2114         key_logdump_txt(YLOG_LOG, &key2, *k ? "i" : "d");
2115
2116         assert(key2.mem[1]);
2117     }
2118 #endif
2119 }
2120
2121 void encode_key_flush (struct encode_info *i, FILE *outf)
2122
2123     iscz1_stop(i->encode_handle);
2124     iscz1_stop(i->decode_handle);
2125 }
2126
2127 #else
2128
2129 /* new encode_key_write
2130  * The idea is to buffer one more key, and compare them
2131  * If we are going to delete and insert the same key, 
2132  * we may as well not bother. Should make a difference in 
2133  * updates with small modifications (appending to a mbox)
2134  */
2135 void encode_key_write (char *k, struct encode_info *i, FILE *outf)
2136 {
2137     struct it_key key;
2138     char *bp; 
2139
2140     if (*k)  /* first time for new key */
2141     {
2142         bp = i->buf;
2143         while ((*bp++ = *k++))
2144             ;
2145         i->keylen= bp - i->buf -1;    
2146         assert(i->keylen+1+sizeof(struct it_key) < ENCODE_BUFLEN);
2147     }
2148     else
2149     {
2150         bp=i->buf + i->keylen;
2151         *bp++=0;
2152         k++;
2153     }
2154
2155     memcpy (&key, k+1, sizeof(struct it_key));
2156     if (0==i->prevsys) /* no previous filter, fill up */
2157     {
2158         i->prevsys=key.sysno;
2159         i->prevseq=key.seqno;
2160         i->prevcmd=*k;
2161     }
2162     else if ( (i->prevsys==key.sysno) &&
2163               (i->prevseq==key.seqno) &&
2164               (i->prevcmd!=*k) )
2165     { /* same numbers, diff cmd, they cancel out */
2166         i->prevsys=0;
2167     }
2168     else 
2169     { /* different stuff, write previous, move buf */
2170         bp = encode_key_int ( (i->prevsys - i->sysno) * 2 + i->prevcmd, bp);
2171         if (i->sysno != i->prevsys)
2172         {
2173             i->sysno = i->prevsys;
2174             i->seqno = 0;
2175         }
2176         else if (!i->seqno && !i->prevseq && i->cmd == i->prevcmd)
2177         {
2178             return; /* ??? Filters some sort of duplicates away */
2179                     /* ??? Can this ever happen   -H 15oct02 */
2180         }
2181         bp = encode_key_int (i->prevseq - i->seqno, bp);
2182         i->seqno = i->prevseq;
2183         i->cmd = i->prevcmd;
2184         if (fwrite (i->buf, bp - i->buf, 1, outf) != 1)
2185         {
2186             yaz_log (YLOG_FATAL|YLOG_ERRNO, "fwrite");
2187             exit (1);
2188         }
2189         i->keylen=0; /* ok, it's written, forget it */
2190         i->prevsys=key.sysno;
2191         i->prevseq=key.seqno;
2192         i->prevcmd=*k;
2193     }
2194 }
2195
2196 void encode_key_flush (struct encode_info *i, FILE *outf)
2197 { /* flush the last key from i */
2198     char *bp =i->buf + i->keylen;
2199     if (0==i->prevsys)
2200     {
2201         return; /* nothing to flush */
2202     }
2203     *bp++=0;
2204     bp = encode_key_int ( (i->prevsys - i->sysno) * 2 + i->prevcmd, bp);
2205     if (i->sysno != i->prevsys)
2206     {
2207         i->sysno = i->prevsys;
2208         i->seqno = 0;
2209     }
2210     else if (!i->seqno && !i->prevseq && i->cmd == i->prevcmd)
2211     {
2212         return; /* ??? Filters some sort of duplicates away */
2213                 /* ??? Can this ever happen   -H 15oct02 */
2214     }
2215     bp = encode_key_int (i->prevseq - i->seqno, bp);
2216     i->seqno = i->prevseq;
2217     i->cmd = i->prevcmd;
2218     if (fwrite (i->buf, bp - i->buf, 1, outf) != 1)
2219     {
2220         yaz_log (YLOG_FATAL|YLOG_ERRNO, "fwrite");
2221         exit (1);
2222     }
2223     i->keylen=0; /* ok, it's written, forget it */
2224     i->prevsys=0; /* forget the values too */
2225     i->prevseq=0;
2226 }
2227 #endif
2228 /*
2229  * Local variables:
2230  * c-basic-offset: 4
2231  * indent-tabs-mode: nil
2232  * End:
2233  * vim: shiftwidth=4 tabstop=8 expandtab
2234  */
2235