ICU functional for scan and snippets.
[idzebra-moved-to-github.git] / index / extract.c
1 /* $Id: extract.c,v 1.273 2007-12-13 11:09:20 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                              int deleteFlag)
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 && deleteFlag)
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                                      deleteFlag ? 
687                                      action_delete : action_update,
688                                      0, /* tst_mode */
689                                      zh->m_record_type,
690                                      sysno,
691                                      0, /*match_criteria */
692                                      fname,
693                                      recType, recTypeClientData);
694     if (streamp)
695         stream.destroy(streamp);
696     zh->m_record_type = original_record_type;
697     return r;
698 }
699
700 /*
701   If sysno is provided, then it's used to identify the reocord.
702   If not, and match_criteria is provided, then sysno is guessed
703   If not, and a record is provided, then sysno is got from there
704   
705  */
706
707 ZEBRA_RES zebra_buffer_extract_record(ZebraHandle zh, 
708                                       const char *buf, size_t buf_size,
709                                       enum zebra_recctrl_action_t action,
710                                       int test_mode, 
711                                       const char *recordType,
712                                       zint *sysno,
713                                       const char *match_criteria,
714                                       const char *fname)
715 {
716     struct ZebraRecStream stream;
717     ZEBRA_RES res;
718     void *clientData;
719     RecType recType = 0;
720
721     if (recordType && *recordType)
722     {
723         yaz_log(log_level_extract,
724                 "Record type explicitly specified: %s", recordType);
725         recType = recType_byName(zh->reg->recTypes, zh->res, recordType,
726                                   &clientData);
727     } 
728     else
729     {
730         if (!(zh->m_record_type))
731         {
732             yaz_log(YLOG_WARN, "No such record type defined");
733             return ZEBRA_FAIL;
734         }
735         yaz_log(log_level_extract, "Get record type from rgroup: %s",
736                 zh->m_record_type);
737         recType = recType_byName(zh->reg->recTypes, zh->res,
738                                   zh->m_record_type, &clientData);
739         recordType = zh->m_record_type;
740     }
741     
742     if (!recType)
743     {
744         yaz_log(YLOG_WARN, "No such record type: %s", recordType);
745         return ZEBRA_FAIL;
746     }
747
748     zebra_create_stream_mem(&stream, buf, buf_size);
749
750     res = zebra_extract_records_stream(zh, &stream,
751                                        action,
752                                        test_mode, 
753                                        recordType,
754                                        sysno,
755                                        match_criteria,
756                                        fname,
757                                        recType, clientData);
758     stream.destroy(&stream);
759     return res;
760 }
761
762 ZEBRA_RES zebra_extract_records_stream(ZebraHandle zh, 
763                                        struct ZebraRecStream *stream,
764                                        enum zebra_recctrl_action_t action,
765                                        int test_mode, 
766                                        const char *recordType,
767                                        zint *sysno,
768                                        const char *match_criteria,
769                                        const char *fname,
770                                        RecType recType,
771                                        void *recTypeClientData)
772 {
773     ZEBRA_RES res = ZEBRA_OK;
774     while (1)
775     {
776         int more = 0;
777         res = zebra_extract_record_stream(zh, stream,
778                                           action,
779                                           test_mode, 
780                                           recordType,
781                                           sysno,
782                                           match_criteria,
783                                           fname,
784                                           recType, recTypeClientData, &more);
785         if (!more)
786         {
787             res = ZEBRA_OK;
788             break;
789         }
790         if (res != ZEBRA_OK)
791             break;
792         if (sysno)
793             break;
794     }
795     return res;
796 }
797
798
799 static WRBUF wrbuf_hex_str(const char *cstr)
800 {
801     size_t i;
802     WRBUF w = wrbuf_alloc();
803     for (i = 0; cstr[i]; i++)
804     {
805         if (cstr[i] < ' ' || cstr[i] > 126)
806             wrbuf_printf(w, "\\%02X", cstr[i] & 0xff);
807         else
808             wrbuf_putc(w, cstr[i]);
809     }
810     return w;
811 }
812
813 ZEBRA_RES zebra_extract_record_stream(ZebraHandle zh, 
814                                       struct ZebraRecStream *stream,
815                                       enum zebra_recctrl_action_t action,
816                                       int test_mode, 
817                                       const char *recordType,
818                                       zint *sysno,
819                                       const char *match_criteria,
820                                       const char *fname,
821                                       RecType recType,
822                                       void *recTypeClientData,
823                                       int *more)
824
825 {
826     zint sysno0 = 0;
827     RecordAttr *recordAttr;
828     struct recExtractCtrl extractCtrl;
829     int r;
830     const char *matchStr = 0;
831     Record rec;
832     off_t start_offset = 0, end_offset = 0;
833     const char *pr_fname = fname;  /* filename to print .. */
834     int show_progress = zh->records_processed + zh->records_skipped 
835         < zh->m_file_verbose_limit ? 1:0;
836
837     zebra_init_log_level();
838
839     if (!pr_fname)
840         pr_fname = "<no file>";  /* make it printable if file is omitted */
841
842     zebra_rec_keys_reset(zh->reg->keys);
843     zebra_rec_keys_reset(zh->reg->sortKeys);
844
845     if (zebraExplain_curDatabase(zh->reg->zei, zh->basenames[0]))
846     {
847         if (zebraExplain_newDatabase(zh->reg->zei, zh->basenames[0], 
848                                       zh->m_explain_database))
849             return ZEBRA_FAIL;
850     }
851
852     if (stream)
853     {
854         off_t null_offset = 0;
855         extractCtrl.stream = stream;
856
857         start_offset = stream->tellf(stream);
858
859         extractCtrl.first_record = start_offset ? 0 : 1;
860         
861         stream->endf(stream, &null_offset);;
862
863         extractCtrl.init = extract_init;
864         extractCtrl.tokenAdd = extract_token_add;
865         extractCtrl.schemaAdd = extract_schema_add;
866         extractCtrl.dh = zh->reg->dh;
867         extractCtrl.handle = zh;
868         extractCtrl.match_criteria[0] = '\0';
869         extractCtrl.staticrank = 0;
870         extractCtrl.action = action;
871
872         init_extractCtrl(zh, &extractCtrl);
873
874         extract_set_store_data_prepare(&extractCtrl);
875         
876         r = (*recType->extract)(recTypeClientData, &extractCtrl);
877
878         if (action == action_update)
879         {
880             action = extractCtrl.action;
881         }
882         
883         switch (r)
884         {
885         case RECCTRL_EXTRACT_EOF:
886             return ZEBRA_FAIL;
887         case RECCTRL_EXTRACT_ERROR_GENERIC:
888             /* error occured during extraction ... */
889             yaz_log(YLOG_WARN, "extract error: generic");
890             return ZEBRA_FAIL;
891         case RECCTRL_EXTRACT_ERROR_NO_SUCH_FILTER:
892             /* error occured during extraction ... */
893             yaz_log(YLOG_WARN, "extract error: no such filter");
894             return ZEBRA_FAIL;
895         case RECCTRL_EXTRACT_SKIP:
896             if (show_progress)
897                 yaz_log(YLOG_LOG, "skip %s %s " ZINT_FORMAT,
898                          recordType, pr_fname, (zint) start_offset);
899             *more = 1;
900             
901             end_offset = stream->endf(stream, 0);
902             if (end_offset)
903                 stream->seekf(stream, end_offset);
904
905             return ZEBRA_OK;
906         case RECCTRL_EXTRACT_OK:
907             break;
908         default:
909             yaz_log(YLOG_WARN, "extract error: unknown error: %d", r);
910             return ZEBRA_FAIL;
911         }
912         end_offset = stream->endf(stream, 0);
913         if (end_offset)
914             stream->seekf(stream, end_offset);
915         else
916             end_offset = stream->tellf(stream);
917
918         if (extractCtrl.match_criteria[0])
919             match_criteria = extractCtrl.match_criteria;
920     }
921
922     *more = 1;
923     if (!sysno)
924     {
925         sysno = &sysno0;
926
927         if (match_criteria && *match_criteria) {
928             matchStr = match_criteria;
929         } else {
930             if (zh->m_record_id && *zh->m_record_id) {
931                 matchStr = get_match_from_spec(zh, zh->reg->keys, pr_fname, 
932                                                zh->m_record_id);
933                 if (!matchStr)
934                 {
935                     yaz_log(YLOG_LOG, "error %s %s " ZINT_FORMAT, recordType,
936                              pr_fname, (zint) start_offset);
937                     return ZEBRA_FAIL;
938                 }
939             }
940         }
941         if (matchStr) 
942         {
943             int db_ord = zebraExplain_get_database_ord(zh->reg->zei);
944             char *rinfo = dict_lookup_ord(zh->reg->matchDict, db_ord,
945                                           matchStr);
946
947             
948             if (log_level_extract)
949             {
950                 WRBUF w = wrbuf_hex_str(matchStr);
951                 yaz_log(log_level_extract, "matchStr: %s", wrbuf_cstr(w));
952                 wrbuf_destroy(w);
953             }
954             if (rinfo)
955             {
956                 assert(*rinfo == sizeof(*sysno));
957                 memcpy(sysno, rinfo+1, sizeof(*sysno));
958             }
959        }
960     }
961
962     if (zebra_rec_keys_empty(zh->reg->keys))
963     {
964         /* the extraction process returned no information - the record
965            is probably empty - unless flagShowRecords is in use */
966         if (test_mode)
967             return ZEBRA_OK;
968     }
969
970     if (! *sysno)
971     {
972         /* new record */
973         if (action == action_delete)
974         {
975             yaz_log(YLOG_LOG, "delete %s %s " ZINT_FORMAT, recordType,
976                          pr_fname, (zint) start_offset);
977             yaz_log(YLOG_WARN, "cannot delete record above (seems new)");
978             return ZEBRA_FAIL;
979         }
980         else if (action == action_replace)
981         {
982             yaz_log(YLOG_LOG, "update %s %s " ZINT_FORMAT, recordType,
983                          pr_fname, (zint) start_offset);
984             yaz_log(YLOG_WARN, "cannot update record above (seems new)");
985             return ZEBRA_FAIL;
986         }
987         if (show_progress)
988             yaz_log(YLOG_LOG, "add %s %s " ZINT_FORMAT, recordType, pr_fname,
989                      (zint) start_offset);
990         rec = rec_new(zh->reg->records);
991
992         *sysno = rec->sysno;
993
994
995         if (stream)
996         {
997             all_matches_add(&extractCtrl,
998                             zebra_rec_keys_get_custom_record_id(zh->reg->keys),
999                             *sysno);
1000         }
1001
1002
1003         recordAttr = rec_init_attr(zh->reg->zei, rec);
1004         if (extractCtrl.staticrank < 0)
1005         {
1006             yaz_log(YLOG_WARN, "Negative staticrank for record. Set to 0");
1007             extractCtrl.staticrank = 0;
1008         }
1009
1010         if (matchStr)
1011         {
1012             int db_ord = zebraExplain_get_database_ord(zh->reg->zei);
1013             dict_insert_ord(zh->reg->matchDict, db_ord, matchStr,
1014                             sizeof(*sysno), sysno);
1015         }
1016
1017         extract_flush_sort_keys(zh, *sysno, 1, zh->reg->sortKeys);
1018 #if FLUSH2
1019         extract_flush_record_keys2(zh, *sysno,
1020                                    zh->reg->keys, extractCtrl.staticrank,
1021                                    0, recordAttr->staticrank);
1022 #else
1023         extract_flush_record_keys(zh, *sysno, 1, zh->reg->keys,
1024                                   extractCtrl.staticrank);
1025 #endif
1026         recordAttr->staticrank = extractCtrl.staticrank;
1027         zh->records_inserted++;
1028     } 
1029     else
1030     {
1031         /* record already exists */
1032         zebra_rec_keys_t delkeys = zebra_rec_keys_open();
1033         zebra_rec_keys_t sortKeys = zebra_rec_keys_open();
1034         if (action == action_insert)
1035         {
1036             yaz_log(YLOG_LOG, "skipped %s %s " ZINT_FORMAT, 
1037                          recordType, pr_fname, (zint) start_offset);
1038             logRecord(zh);
1039             return ZEBRA_FAIL;
1040         }
1041
1042         rec = rec_get(zh->reg->records, *sysno);
1043         assert(rec);
1044
1045         if (stream)
1046         {
1047             all_matches_add(&extractCtrl,
1048                             zebra_rec_keys_get_custom_record_id(zh->reg->keys),
1049                             *sysno);
1050         }
1051         
1052         recordAttr = rec_init_attr(zh->reg->zei, rec);
1053
1054         /* decrease total size */
1055         zebraExplain_recordBytesIncrement(zh->reg->zei,
1056                                            - recordAttr->recordSize);
1057
1058         zebra_rec_keys_set_buf(delkeys,
1059                                rec->info[recInfo_delKeys],
1060                                rec->size[recInfo_delKeys],
1061                                0);
1062         zebra_rec_keys_set_buf(sortKeys,
1063                                rec->info[recInfo_sortKeys],
1064                                rec->size[recInfo_sortKeys],
1065                                0);
1066
1067         extract_flush_sort_keys(zh, *sysno, 0, sortKeys);
1068 #if !FLUSH2
1069         extract_flush_record_keys(zh, *sysno, 0, delkeys,
1070                                   recordAttr->staticrank);
1071 #endif
1072         if (action == action_delete)
1073         {
1074             /* record going to be deleted */
1075 #if FLUSH2
1076             extract_flush_record_keys2(zh, *sysno, 0, recordAttr->staticrank,
1077                                        delkeys, recordAttr->staticrank);
1078 #endif       
1079             if (zebra_rec_keys_empty(delkeys))
1080             {
1081                 yaz_log(YLOG_LOG, "delete %s %s " ZINT_FORMAT, recordType,
1082                         pr_fname, (zint) start_offset);
1083                 yaz_log(YLOG_WARN, "cannot delete file above, "
1084                         "storeKeys false (3)");
1085             }
1086             else
1087             {
1088                 if (show_progress)
1089                     yaz_log(YLOG_LOG, "delete %s %s " ZINT_FORMAT, recordType,
1090                             pr_fname, (zint) start_offset);
1091                 zh->records_deleted++;
1092                 if (matchStr)
1093                 {
1094                     int db_ord = zebraExplain_get_database_ord(zh->reg->zei);
1095                     dict_delete_ord(zh->reg->matchDict, db_ord, matchStr);
1096                 }
1097                 rec_del(zh->reg->records, &rec);
1098             }
1099             zebra_rec_keys_close(delkeys);
1100             zebra_rec_keys_close(sortKeys);
1101             rec_free(&rec);
1102             logRecord(zh);
1103             return ZEBRA_OK;
1104         }
1105         else
1106         {   /* update or special_update */
1107             if (show_progress)
1108                 yaz_log(YLOG_LOG, "update %s %s " ZINT_FORMAT, recordType,
1109                         pr_fname, (zint) start_offset);
1110             extract_flush_sort_keys(zh, *sysno, 1, zh->reg->sortKeys);
1111
1112 #if FLUSH2
1113             extract_flush_record_keys2(zh, *sysno,
1114                                        zh->reg->keys, extractCtrl.staticrank,
1115                                        delkeys, recordAttr->staticrank);
1116 #else
1117             extract_flush_record_keys(zh, *sysno, 1, 
1118                                       zh->reg->keys, extractCtrl.staticrank);
1119 #endif
1120             recordAttr->staticrank = extractCtrl.staticrank;
1121             zh->records_updated++;
1122         }
1123         zebra_rec_keys_close(delkeys);
1124         zebra_rec_keys_close(sortKeys);
1125     }
1126     /* update file type */
1127     xfree(rec->info[recInfo_fileType]);
1128     rec->info[recInfo_fileType] =
1129         rec_strdup(recordType, &rec->size[recInfo_fileType]);
1130
1131     /* update filename */
1132     xfree(rec->info[recInfo_filename]);
1133     rec->info[recInfo_filename] =
1134         rec_strdup(fname, &rec->size[recInfo_filename]);
1135
1136     /* update delete keys */
1137     xfree(rec->info[recInfo_delKeys]);
1138     if (!zebra_rec_keys_empty(zh->reg->keys) && zh->m_store_keys == 1)
1139     {
1140         zebra_rec_keys_get_buf(zh->reg->keys,
1141                                &rec->info[recInfo_delKeys],
1142                                &rec->size[recInfo_delKeys]);
1143     }
1144     else
1145     {
1146         rec->info[recInfo_delKeys] = NULL;
1147         rec->size[recInfo_delKeys] = 0;
1148     }
1149     /* update sort keys */
1150     xfree(rec->info[recInfo_sortKeys]);
1151
1152     zebra_rec_keys_get_buf(zh->reg->sortKeys,
1153                            &rec->info[recInfo_sortKeys],
1154                            &rec->size[recInfo_sortKeys]);
1155
1156     if (stream)
1157     {
1158         recordAttr->recordSize = end_offset - start_offset;
1159         zebraExplain_recordBytesIncrement(zh->reg->zei,
1160                                           recordAttr->recordSize);
1161     }
1162
1163     /* set run-number for this record */
1164     recordAttr->runNumber =
1165         zebraExplain_runNumberIncrement(zh->reg->zei, 0);
1166
1167     /* update store data */
1168     xfree(rec->info[recInfo_storeData]);
1169
1170     /* update store data */
1171     if (zh->store_data_buf)
1172     {
1173         rec->size[recInfo_storeData] = zh->store_data_size;
1174         rec->info[recInfo_storeData] = zh->store_data_buf;
1175         zh->store_data_buf = 0;
1176         recordAttr->recordSize = zh->store_data_size;
1177     }
1178     else if (zh->m_store_data)
1179     {
1180         off_t cur_offset = stream->tellf(stream);
1181
1182         rec->size[recInfo_storeData] = recordAttr->recordSize;
1183         rec->info[recInfo_storeData] = (char *)
1184             xmalloc(recordAttr->recordSize);
1185         stream->seekf(stream, start_offset);
1186         stream->readf(stream, rec->info[recInfo_storeData],
1187                       recordAttr->recordSize);
1188         stream->seekf(stream, cur_offset);
1189     }
1190     else
1191     {
1192         rec->info[recInfo_storeData] = NULL;
1193         rec->size[recInfo_storeData] = 0;
1194     }
1195     /* update database name */
1196     xfree(rec->info[recInfo_databaseName]);
1197     rec->info[recInfo_databaseName] =
1198         rec_strdup(zh->basenames[0], &rec->size[recInfo_databaseName]); 
1199
1200     /* update offset */
1201     recordAttr->recordOffset = start_offset;
1202     
1203     /* commit this record */
1204     rec_put(zh->reg->records, &rec);
1205     logRecord(zh);
1206     return ZEBRA_OK;
1207 }
1208
1209 ZEBRA_RES zebra_extract_explain(void *handle, Record rec, data1_node *n)
1210 {
1211     ZebraHandle zh = (ZebraHandle) handle;
1212     struct recExtractCtrl extractCtrl;
1213
1214     if (zebraExplain_curDatabase(zh->reg->zei,
1215                                   rec->info[recInfo_databaseName]))
1216     {
1217         abort();
1218         if (zebraExplain_newDatabase(zh->reg->zei,
1219                                       rec->info[recInfo_databaseName], 0))
1220             abort();
1221     }
1222
1223     zebra_rec_keys_reset(zh->reg->keys);
1224     zebra_rec_keys_reset(zh->reg->sortKeys);
1225
1226     extractCtrl.init = extract_init;
1227     extractCtrl.tokenAdd = extract_token_add;
1228     extractCtrl.schemaAdd = extract_schema_add;
1229     extractCtrl.dh = zh->reg->dh;
1230
1231     init_extractCtrl(zh, &extractCtrl);
1232
1233     extractCtrl.flagShowRecords = 0;
1234     extractCtrl.match_criteria[0] = '\0';
1235     extractCtrl.staticrank = 0;
1236     extractCtrl.action = action_update;
1237
1238     extractCtrl.handle = handle;
1239     extractCtrl.first_record = 1;
1240     
1241     extract_set_store_data_prepare(&extractCtrl);
1242
1243     if (n)
1244         grs_extract_tree(&extractCtrl, n);
1245
1246     if (rec->size[recInfo_delKeys])
1247     {
1248         zebra_rec_keys_t delkeys = zebra_rec_keys_open();
1249         
1250         zebra_rec_keys_t sortkeys = zebra_rec_keys_open();
1251
1252         zebra_rec_keys_set_buf(delkeys, rec->info[recInfo_delKeys],
1253                                rec->size[recInfo_delKeys],
1254                                0);
1255 #if FLUSH2
1256         extract_flush_record_keys2(zh, rec->sysno, 
1257                                    zh->reg->keys, 0, delkeys, 0);
1258 #else
1259         extract_flush_record_keys(zh, rec->sysno, 0, delkeys, 0);
1260         extract_flush_record_keys(zh, rec->sysno, 1, zh->reg->keys, 0);
1261 #endif
1262         zebra_rec_keys_close(delkeys);
1263
1264         zebra_rec_keys_set_buf(sortkeys, rec->info[recInfo_sortKeys],
1265                                rec->size[recInfo_sortKeys],
1266                                0);
1267
1268         extract_flush_sort_keys(zh, rec->sysno, 0, sortkeys);
1269         zebra_rec_keys_close(sortkeys);
1270     }
1271     else
1272     {
1273 #if FLUSH2
1274         extract_flush_record_keys2(zh, rec->sysno, zh->reg->keys, 0, 0, 0);
1275 #else
1276         extract_flush_record_keys(zh, rec->sysno, 1, zh->reg->keys, 0);        
1277 #endif
1278     }
1279     extract_flush_sort_keys(zh, rec->sysno, 1, zh->reg->sortKeys);
1280     
1281     xfree(rec->info[recInfo_delKeys]);
1282     zebra_rec_keys_get_buf(zh->reg->keys,
1283                            &rec->info[recInfo_delKeys], 
1284                            &rec->size[recInfo_delKeys]);
1285
1286     xfree(rec->info[recInfo_sortKeys]);
1287     zebra_rec_keys_get_buf(zh->reg->sortKeys,
1288                            &rec->info[recInfo_sortKeys],
1289                            &rec->size[recInfo_sortKeys]);
1290     return ZEBRA_OK;
1291 }
1292
1293 void extract_rec_keys_log(ZebraHandle zh, int is_insert,
1294                           zebra_rec_keys_t reckeys,
1295                           int level)
1296 {
1297     if (zebra_rec_keys_rewind(reckeys))
1298     {
1299         size_t slen;
1300         const char *str;
1301         struct it_key key;
1302         NMEM nmem = nmem_create();
1303
1304         while(zebra_rec_keys_read(reckeys, &str, &slen, &key))
1305         {
1306             char keystr[200]; /* room for zints to print */
1307             char *dst_term = 0;
1308             int ord = CAST_ZINT_TO_INT(key.mem[0]);
1309             const char *index_type;
1310             int i;
1311             const char *string_index;
1312             
1313             zebraExplain_lookup_ord(zh->reg->zei, ord, &index_type,
1314                                     0/* db */, &string_index);
1315             assert(index_type);
1316             zebra_term_untrans_iconv(zh, nmem, index_type,
1317                                      &dst_term, str);
1318             *keystr = '\0';
1319             for (i = 0; i<key.len; i++)
1320             {
1321                 sprintf(keystr + strlen(keystr), ZINT_FORMAT " ", key.mem[i]);
1322             }
1323
1324             if (*str < CHR_BASE_CHAR)
1325             {
1326                 int i;
1327                 char dst_buf[200]; /* room for special chars */
1328
1329                 strcpy(dst_buf , "?");
1330
1331                 if (!strcmp(str, ""))
1332                     strcpy(dst_buf, "alwaysmatches");
1333                 if (!strcmp(str, FIRST_IN_FIELD_STR))
1334                     strcpy(dst_buf, "firstinfield");
1335                 else if (!strcmp(str, CHR_UNKNOWN))
1336                     strcpy(dst_buf, "unknown");
1337                 else if (!strcmp(str, CHR_SPACE))
1338                     strcpy(dst_buf, "space");
1339                 
1340                 for (i = 0; i<slen; i++)
1341                 {
1342                     sprintf(dst_buf + strlen(dst_buf), " %d", str[i] & 0xff);
1343                 }
1344                 yaz_log(level, "%s%s %s %s", keystr, index_type,
1345                         string_index, dst_buf);
1346                 
1347             }
1348             else
1349                 yaz_log(level, "%s%s %s \"%s\"", keystr, index_type,
1350                         string_index, dst_term);
1351
1352             nmem_reset(nmem);
1353         }
1354         nmem_destroy(nmem);
1355     }
1356 }
1357
1358 void extract_rec_keys_adjust(ZebraHandle zh, int is_insert,
1359                              zebra_rec_keys_t reckeys)
1360 {
1361     ZebraExplainInfo zei = zh->reg->zei;
1362     struct ord_stat {
1363         int no;
1364         int ord;
1365         struct ord_stat *next;
1366     };
1367
1368     if (zebra_rec_keys_rewind(reckeys))
1369     {
1370         struct ord_stat *ord_list = 0;
1371         struct ord_stat *p;
1372         size_t slen;
1373         const char *str;
1374         struct it_key key_in;
1375         while(zebra_rec_keys_read(reckeys, &str, &slen, &key_in))
1376         {
1377             int ord = CAST_ZINT_TO_INT(key_in.mem[0]);
1378
1379             for (p = ord_list; p ; p = p->next)
1380                 if (p->ord == ord)
1381                 {
1382                     p->no++;
1383                     break;
1384                 }
1385             if (!p)
1386             {
1387                 p = xmalloc(sizeof(*p));
1388                 p->no = 1;
1389                 p->ord = ord;
1390                 p->next = ord_list;
1391                 ord_list = p;
1392             }
1393         }
1394
1395         p = ord_list;
1396         while (p)
1397         {
1398             struct ord_stat *p1 = p;
1399
1400             if (is_insert)
1401                 zebraExplain_ord_adjust_occurrences(zei, p->ord, p->no, 1);
1402             else
1403                 zebraExplain_ord_adjust_occurrences(zei, p->ord, - p->no, -1);
1404             p = p->next;
1405             xfree(p1);
1406         }
1407     }
1408 }
1409
1410 void extract_flush_record_keys2(ZebraHandle zh, zint sysno,
1411                                 zebra_rec_keys_t ins_keys, zint ins_rank,
1412                                 zebra_rec_keys_t del_keys, zint del_rank)
1413 {
1414     ZebraExplainInfo zei = zh->reg->zei;
1415     int normal = 0;
1416     int optimized = 0;
1417
1418     if (!zh->reg->key_block)
1419     {
1420         int mem = 1024*1024 * atoi( res_get_def( zh->res, "memmax", "8"));
1421         const char *key_tmp_dir = res_get_def(zh->res, "keyTmpDir", ".");
1422         int use_threads = atoi(res_get_def(zh->res, "threads", "1"));
1423         zh->reg->key_block = key_block_create(mem, key_tmp_dir, use_threads);
1424     }
1425
1426     if (ins_keys)
1427     {
1428         extract_rec_keys_adjust(zh, 1, ins_keys);
1429         if (!del_keys)
1430             zebraExplain_recordCountIncrement(zei, 1);
1431         zebra_rec_keys_rewind(ins_keys);
1432     }
1433     if (del_keys)
1434     {
1435         extract_rec_keys_adjust(zh, 0, del_keys);
1436         if (!ins_keys)
1437             zebraExplain_recordCountIncrement(zei, -1);
1438         zebra_rec_keys_rewind(del_keys);
1439     }
1440
1441     while (1)
1442     {
1443         size_t del_slen;
1444         const char *del_str;
1445         struct it_key del_key_in;
1446         int del = 0;
1447
1448         size_t ins_slen;
1449         const char *ins_str;
1450         struct it_key ins_key_in;
1451         int ins = 0;
1452
1453         if (del_keys)
1454             del = zebra_rec_keys_read(del_keys, &del_str, &del_slen,
1455                                       &del_key_in);
1456         if (ins_keys)
1457             ins = zebra_rec_keys_read(ins_keys, &ins_str, &ins_slen,
1458                                       &ins_key_in);
1459
1460         if (del && ins && ins_rank == del_rank
1461             && !key_compare(&del_key_in, &ins_key_in) 
1462             && ins_slen == del_slen && !memcmp(del_str, ins_str, del_slen))
1463         {
1464             optimized++;
1465             continue;
1466         }
1467         if (!del && !ins)
1468             break;
1469         
1470         normal++;
1471         if (del)
1472             key_block_write(zh->reg->key_block, sysno, 
1473                             &del_key_in, 0, del_str, del_slen,
1474                             del_rank, zh->m_staticrank);
1475         if (ins)
1476             key_block_write(zh->reg->key_block, sysno, 
1477                             &ins_key_in, 1, ins_str, ins_slen,
1478                             ins_rank, zh->m_staticrank);
1479     }
1480     yaz_log(log_level_extract, "normal=%d optimized=%d", normal, optimized);
1481 }
1482
1483
1484 ZEBRA_RES zebra_rec_keys_to_snippets1(ZebraHandle zh,
1485                                      zebra_rec_keys_t reckeys,
1486                                      zebra_snippets *snippets)
1487 {
1488     NMEM nmem = nmem_create();
1489     if (zebra_rec_keys_rewind(reckeys)) 
1490     {
1491         const char *str;
1492         size_t slen;
1493         struct it_key key;
1494         while (zebra_rec_keys_read(reckeys, &str, &slen, &key))
1495         {
1496             char *dst_term = 0;
1497             int ord;
1498             zint seqno;
1499             const char *index_type;
1500
1501             assert(key.len <= IT_KEY_LEVEL_MAX && key.len > 2);
1502             seqno = key.mem[key.len-1];
1503             ord = CAST_ZINT_TO_INT(key.mem[0]);
1504             
1505             zebraExplain_lookup_ord(zh->reg->zei, ord, &index_type,
1506                                     0/* db */, 0 /* string_index */);
1507             assert(index_type);
1508             zebra_term_untrans_iconv(zh, nmem, index_type,
1509                                      &dst_term, str);
1510             zebra_snippets_append(snippets, seqno, 0, ord, dst_term);
1511             nmem_reset(nmem);
1512         }
1513     }
1514     nmem_destroy(nmem);
1515     return ZEBRA_OK;
1516 }
1517
1518 void print_rec_keys(ZebraHandle zh, zebra_rec_keys_t reckeys)
1519 {
1520     yaz_log(YLOG_LOG, "print_rec_keys");
1521     if (zebra_rec_keys_rewind(reckeys))
1522     {
1523         const char *str;
1524         size_t slen;
1525         struct it_key key;
1526         while (zebra_rec_keys_read(reckeys, &str, &slen, &key))
1527         {
1528             char dst_buf[IT_MAX_WORD];
1529             zint seqno;
1530             const char *index_type;
1531             int ord = CAST_ZINT_TO_INT(key.mem[0]);
1532             const char *db = 0;
1533             assert(key.len <= IT_KEY_LEVEL_MAX && key.len > 2);
1534
1535             zebraExplain_lookup_ord(zh->reg->zei, ord, &index_type, &db, 0);
1536             
1537             seqno = key.mem[key.len-1];
1538             
1539             zebra_term_untrans(zh, index_type, dst_buf, str);
1540             
1541             yaz_log(YLOG_LOG, "ord=%d seqno=" ZINT_FORMAT 
1542                     " term=%s", ord, seqno, dst_buf); 
1543         }
1544     }
1545 }
1546
1547 static void extract_add_index_string(RecWord *p, zinfo_index_category_t cat,
1548                                      const char *str, int length)
1549 {
1550     struct it_key key;
1551     ZebraHandle zh = p->extractCtrl->handle;
1552     ZebraExplainInfo zei = zh->reg->zei;
1553     int ch, i;
1554
1555     ch = zebraExplain_lookup_attr_str(zei, cat, p->index_type, p->index_name);
1556     if (ch < 0)
1557         ch = zebraExplain_add_attr_str(zei, cat, p->index_type, p->index_name);
1558
1559     i = 0;
1560     key.mem[i++] = ch;
1561     key.mem[i++] = p->record_id;
1562     key.mem[i++] = p->section_id;
1563
1564     if (zh->m_segment_indexing)
1565         key.mem[i++] = p->segment;
1566     key.mem[i++] = p->seqno;
1567     key.len = i;
1568
1569     zebra_rec_keys_write(zh->reg->keys, str, length, &key);
1570 }
1571
1572 static void extract_add_sort_string(RecWord *p, const char *str, int length)
1573 {
1574     struct it_key key;
1575     ZebraHandle zh = p->extractCtrl->handle;
1576     ZebraExplainInfo zei = zh->reg->zei;
1577     int ch;
1578     zinfo_index_category_t cat = zinfo_index_category_sort;
1579
1580     ch = zebraExplain_lookup_attr_str(zei, cat, p->index_type, p->index_name);
1581     if (ch < 0)
1582         ch = zebraExplain_add_attr_str(zei, cat, p->index_type, p->index_name);
1583     key.len = 2;
1584     key.mem[0] = ch;
1585     key.mem[1] = p->record_id;
1586
1587     zebra_rec_keys_write(zh->reg->sortKeys, str, length, &key);
1588 }
1589
1590 static void extract_add_staticrank_string(RecWord *p,
1591                                           const char *str, int length)
1592 {
1593     char valz[40];
1594     struct recExtractCtrl *ctrl = p->extractCtrl;
1595
1596     if (length > sizeof(valz)-1)
1597         length = sizeof(valz)-1;
1598
1599     memcpy(valz, str, length);
1600     valz[length] = '\0';
1601     ctrl->staticrank = atozint(valz);
1602 }
1603
1604 static void extract_add_string(RecWord *p, zebra_map_t zm,
1605                                const char *string, int length)
1606 {
1607     assert(length > 0);
1608
1609     if (!p->index_name)
1610         return;
1611
1612     if (zebra_maps_is_index(zm))
1613     {
1614         extract_add_index_string(p, zinfo_index_category_index,
1615                                  string, length);
1616         if (zebra_maps_is_alwaysmatches(zm))
1617         {
1618             RecWord word;
1619             memcpy(&word, p, sizeof(word));
1620
1621             word.seqno = 1;
1622             extract_add_index_string(
1623                 &word, zinfo_index_category_alwaysmatches, "", 0);
1624         }
1625     }
1626     else if (zebra_maps_is_sort(zm))
1627     {
1628         extract_add_sort_string(p, string, length);
1629     }
1630     else if (zebra_maps_is_staticrank(zm))
1631     {
1632         extract_add_staticrank_string(p, string, length);
1633     }
1634 }
1635
1636 static void extract_add_incomplete_field(RecWord *p, zebra_map_t zm)
1637 {
1638     const char *b = p->term_buf;
1639     int remain = p->term_len;
1640     int first = 1;
1641     const char **map = 0;
1642     
1643     if (remain > 0)
1644         map = zebra_maps_input(zm, &b, remain, 0);
1645
1646     while (map)
1647     {
1648         char buf[IT_MAX_WORD+1];
1649         int i, remain;
1650
1651         /* Skip spaces */
1652         while (map && *map && **map == *CHR_SPACE)
1653         {
1654             remain = p->term_len - (b - p->term_buf);
1655             if (remain > 0)
1656                 map = zebra_maps_input(zm, &b, remain, 0);
1657             else
1658                 map = 0;
1659         }
1660         if (!map)
1661             break;
1662         i = 0;
1663         while (map && *map && **map != *CHR_SPACE)
1664         {
1665             const char *cp = *map;
1666
1667             while (i < IT_MAX_WORD && *cp)
1668                 buf[i++] = *(cp++);
1669             remain = p->term_len - (b - p->term_buf);
1670             if (remain > 0)
1671                 map = zebra_maps_input(zm, &b, remain, 0);
1672             else
1673                 map = 0;
1674         }
1675         if (!i)
1676             return;
1677
1678         if (first)
1679         {   
1680             first = 0;
1681             if (zebra_maps_is_first_in_field(zm))
1682             {
1683                 /* first in field marker */
1684                 extract_add_string(p, zm, FIRST_IN_FIELD_STR, FIRST_IN_FIELD_LEN);
1685                 p->seqno++;
1686             }
1687         }
1688         extract_add_string(p, zm, buf, i);
1689         p->seqno++;
1690     }
1691 }
1692
1693 static void extract_add_complete_field(RecWord *p, zebra_map_t zm)
1694 {
1695     const char *b = p->term_buf;
1696     char buf[IT_MAX_WORD+1];
1697     const char **map = 0;
1698     int i = 0, remain = p->term_len;
1699
1700     if (remain > 0)
1701         map = zebra_maps_input(zm, &b, remain, 1);
1702
1703     while (remain > 0 && i < IT_MAX_WORD)
1704     {
1705         while (map && *map && **map == *CHR_SPACE)
1706         {
1707             remain = p->term_len - (b - p->term_buf);
1708
1709             if (remain > 0)
1710             {
1711                 int first = i ? 0 : 1;  /* first position */
1712                 map = zebra_maps_input(zm, &b, remain, first);
1713             }
1714             else
1715                 map = 0;
1716         }
1717         if (!map)
1718             break;
1719
1720         if (i && i < IT_MAX_WORD)
1721             buf[i++] = *CHR_SPACE;
1722         while (map && *map && **map != *CHR_SPACE)
1723         {
1724             const char *cp = *map;
1725
1726             if (**map == *CHR_CUT)
1727             {
1728                 i = 0;
1729             }
1730             else
1731             {
1732                 if (i >= IT_MAX_WORD)
1733                     break;
1734                 while (i < IT_MAX_WORD && *cp)
1735                     buf[i++] = *(cp++);
1736             }
1737             remain = p->term_len  - (b - p->term_buf);
1738             if (remain > 0)
1739             {
1740                 map = zebra_maps_input(zm, &b, remain, 0);
1741             }
1742             else
1743                 map = 0;
1744         }
1745     }
1746     if (!i)
1747         return;
1748     extract_add_string(p, zm, buf, i);
1749 }
1750
1751 static void extract_add_icu(RecWord *p, zebra_map_t zm)
1752 {
1753     struct it_key key;
1754     const char *res_buf = 0;
1755     size_t res_len = 0;
1756     ZebraHandle zh = p->extractCtrl->handle;
1757     
1758     int cat = zinfo_index_category_index;
1759     int ch = zebraExplain_lookup_attr_str(zh->reg->zei, cat, 
1760                                           p->index_type, p->index_name);
1761     if (ch < 0)
1762         ch = zebraExplain_add_attr_str(zh->reg->zei, cat, 
1763                                        p->index_type, p->index_name);
1764     zebra_map_tokenize_start(zm, p->term_buf, p->term_len);
1765     while (zebra_map_tokenize_next(zm, &res_buf, &res_len, 0, 0))
1766     {
1767         int i = 0;
1768         key.mem[i++] = ch;
1769         key.mem[i++] = p->record_id;
1770         key.mem[i++] = p->section_id;
1771         
1772         if (zh->m_segment_indexing)
1773             key.mem[i++] = p->segment;
1774         key.mem[i++] = p->seqno;
1775         key.len = i;
1776
1777         zebra_rec_keys_write(zh->reg->keys, res_buf, res_len, &key);
1778         
1779         p->seqno++;
1780     }
1781 }
1782
1783
1784 /** \brief top-level indexing handler for recctrl system
1785     \param p token data to be indexed
1786
1787     Call sequence:
1788     extract_token_add
1789     extract_add_{in}_complete
1790     extract_add_string
1791     
1792     extract_add_index_string
1793     or
1794     extract_add_sort_string
1795     or
1796     extract_add_staticrank_string
1797     
1798 */
1799 static void extract_token_add(RecWord *p)
1800 {
1801     ZebraHandle zh = p->extractCtrl->handle;
1802     zebra_map_t zm = zebra_map_get_or_add(zh->reg->zebra_maps, p->index_type);
1803     WRBUF wrbuf;
1804
1805     if (log_level_details)
1806     {
1807         yaz_log(log_level_details, "extract_token_add "
1808                 "type=%s index=%s seqno=" ZINT_FORMAT " s=%.*s",
1809                 p->index_type, p->index_name, 
1810                 p->seqno, p->term_len, p->term_buf);
1811     }
1812     if ((wrbuf = zebra_replace(zm, 0, p->term_buf, p->term_len)))
1813     {
1814         p->term_buf = wrbuf_buf(wrbuf);
1815         p->term_len = wrbuf_len(wrbuf);
1816     }
1817     if (zebra_maps_is_icu(zm))
1818     {
1819         extract_add_icu(p, zm);
1820     }
1821     else
1822     {
1823         if (zebra_maps_is_complete(zm))
1824             extract_add_complete_field(p, zm);
1825         else
1826             extract_add_incomplete_field(p, zm);
1827     }
1828 }
1829
1830 static void extract_set_store_data_cb(struct recExtractCtrl *p,
1831                                       void *buf, size_t sz)
1832 {
1833     ZebraHandle zh = (ZebraHandle) p->handle;
1834
1835     xfree(zh->store_data_buf);
1836     zh->store_data_buf = 0;
1837     zh->store_data_size = 0;
1838     if (buf && sz)
1839     {
1840         zh->store_data_buf = xmalloc(sz);
1841         zh->store_data_size = sz;
1842         memcpy(zh->store_data_buf, buf, sz);
1843     }
1844 }
1845
1846 static void extract_set_store_data_prepare(struct recExtractCtrl *p)
1847 {
1848     ZebraHandle zh = (ZebraHandle) p->handle;
1849     xfree(zh->store_data_buf);
1850     zh->store_data_buf = 0;
1851     zh->store_data_size = 0;
1852     p->setStoreData = extract_set_store_data_cb;
1853 }
1854
1855 static void extract_schema_add(struct recExtractCtrl *p, Odr_oid *oid)
1856 {
1857     ZebraHandle zh = (ZebraHandle) p->handle;
1858     zebraExplain_addSchema(zh->reg->zei, oid);
1859 }
1860
1861 void extract_flush_sort_keys(ZebraHandle zh, zint sysno,
1862                              int cmd, zebra_rec_keys_t reckeys)
1863 {
1864 #if 0
1865     yaz_log(YLOG_LOG, "extract_flush_sort_keys cmd=%d sysno=" ZINT_FORMAT,
1866             cmd, sysno);
1867     extract_rec_keys_log(zh, cmd, reckeys, YLOG_LOG);
1868 #endif
1869
1870     if (zebra_rec_keys_rewind(reckeys))
1871     {
1872         zebra_sort_index_t si = zh->reg->sort_index;
1873         size_t slen;
1874         const char *str;
1875         struct it_key key_in;
1876
1877         zebra_sort_sysno(si, sysno);
1878
1879         while (zebra_rec_keys_read(reckeys, &str, &slen, &key_in))
1880         {
1881             int ord = CAST_ZINT_TO_INT(key_in.mem[0]);
1882             
1883             zebra_sort_type(si, ord);
1884             if (cmd == 1)
1885                 zebra_sort_add(si, str, slen);
1886             else
1887                 zebra_sort_delete(si);
1888         }
1889     }
1890 }
1891
1892 /*
1893  * Local variables:
1894  * c-basic-offset: 4
1895  * indent-tabs-mode: nil
1896  * End:
1897  * vim: shiftwidth=4 tabstop=8 expandtab
1898  */
1899