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