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