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