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