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