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