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