Make threading for index sort configurable.
[idzebra-moved-to-github.git] / index / extract.c
1 /* $Id: extract.c,v 1.240 2006-11-21 17:48:08 adam Exp $
2    Copyright (C) 1995-2006
3    Index Data ApS
4
5 This file is part of the Zebra server.
6
7 Zebra is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
10 version.
11
12 Zebra is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with 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 #include <stdio.h>
24 #include <assert.h>
25 #include <ctype.h>
26 #ifdef WIN32
27 #include <io.h>
28 #endif
29 #if HAVE_UNISTD_H
30 #include <unistd.h>
31 #endif
32 #include <fcntl.h>
33
34 #include "index.h"
35 #include "orddict.h"
36 #include <direntz.h>
37 #include <charmap.h>
38
39 static int log_level_extract = 0;
40 static int log_level_details = 0;
41 static int log_level_initialized = 0;
42
43 static void zebra_init_log_level(void)
44 {
45     if (!log_level_initialized)
46     {
47         log_level_initialized = 1;
48
49         log_level_extract = yaz_log_module_level("extract");
50         log_level_details = yaz_log_module_level("indexdetails");
51     }
52 }
53
54 static void extract_flushRecordKeys (ZebraHandle zh, SYSNO sysno,
55                                      int cmd, zebra_rec_keys_t reckeys,
56                                      zint staticrank);
57 static void extract_flushSortKeys (ZebraHandle zh, SYSNO sysno,
58                                    int cmd, zebra_rec_keys_t skp);
59 static void extract_schema_add (struct recExtractCtrl *p, Odr_oid *oid);
60 static void extract_token_add (RecWord *p);
61
62 static void logRecord (ZebraHandle zh)
63 {
64     ++zh->records_processed;
65     if (!(zh->records_processed % 1000))
66     {
67         yaz_log(YLOG_LOG, "Records: "ZINT_FORMAT" i/u/d "
68                 ZINT_FORMAT"/"ZINT_FORMAT"/"ZINT_FORMAT, 
69                 zh->records_processed, zh->records_inserted, 
70                 zh->records_updated, zh->records_deleted);
71     }
72 }
73
74 static void extract_add_index_string (RecWord *p, 
75                                       zinfo_index_category_t cat,
76                                       const char *str, int length);
77
78 static void extract_set_store_data_prepare(struct recExtractCtrl *p);
79
80 static void extract_init(struct recExtractCtrl *p, RecWord *w)
81 {
82     w->seqno = 1;
83     w->index_name = "any";
84     w->index_type = 'w';
85     w->extractCtrl = p;
86     w->record_id = 0;
87     w->section_id = 0;
88     w->segment = 0;
89 }
90
91 static void searchRecordKey(ZebraHandle zh,
92                             zebra_rec_keys_t reckeys,
93                             const char *index_name,
94                             const char **ws, int ws_length)
95 {
96     int i;
97     int ch = -1;
98     zinfo_index_category_t cat = zinfo_index_category_index;
99
100     for (i = 0; i<ws_length; i++)
101         ws[i] = NULL;
102
103     if (ch < 0)
104         ch = zebraExplain_lookup_attr_str(zh->reg->zei, cat, '0', index_name);
105     if (ch < 0)
106         ch = zebraExplain_lookup_attr_str(zh->reg->zei, cat, 'p', index_name);
107     if (ch < 0)
108         ch = zebraExplain_lookup_attr_str(zh->reg->zei, cat, 'w', index_name);
109
110     if (ch < 0)
111         return ;
112
113     if (zebra_rec_keys_rewind(reckeys))
114     {
115         zint startSeq = -1;
116         const char *str;
117         size_t slen;
118         struct it_key key;
119         zint seqno;
120         while (zebra_rec_keys_read(reckeys, &str, &slen, &key))
121         {
122             assert(key.len <= IT_KEY_LEVEL_MAX && key.len > 2);
123
124             seqno = key.mem[key.len-1];
125             
126             if (key.mem[0] == ch)
127             {
128                 zint woff;
129                 
130                 if (startSeq == -1)
131                     startSeq = seqno;
132                 woff = seqno - startSeq;
133                 if (woff >= 0 && woff < ws_length)
134                     ws[woff] = str;
135             }
136         }
137     }
138 }
139
140 #define FILE_MATCH_BLANK "\t "
141
142 static char *fileMatchStr (ZebraHandle zh,
143                            zebra_rec_keys_t reckeys,
144                            const char *fname, const char *spec)
145 {
146     static char dstBuf[2048];      /* static here ??? */
147     char *dst = dstBuf;
148     const char *s = spec;
149
150     while (1)
151     {
152         for (; *s && strchr(FILE_MATCH_BLANK, *s); s++)
153             ;
154         if (!*s)
155             break;
156         if (*s == '(')
157         {
158             const char *ws[32];
159             char attset_str[64], attname_str[64];
160             int i;
161             int first = 1;
162             
163             for (s++; strchr(FILE_MATCH_BLANK, *s); s++)
164                 ;
165             for (i = 0; *s && *s != ',' && *s != ')' && 
166                      !strchr(FILE_MATCH_BLANK, *s); s++)
167                 if (i+1 < sizeof(attset_str))
168                     attset_str[i++] = *s;
169             attset_str[i] = '\0';
170             
171             for (; strchr(FILE_MATCH_BLANK, *s); s++)
172                 ;
173             if (*s != ',')
174                 strcpy(attname_str, attset_str);
175             else
176             {
177                 for (s++; strchr(FILE_MATCH_BLANK, *s); s++)
178                     ;
179                 for (i = 0; *s && *s != ')' && 
180                          !strchr(FILE_MATCH_BLANK, *s); s++)
181                     if (i+1 < sizeof(attname_str))
182                         attname_str[i++] = *s;
183                 attname_str[i] = '\0';
184             }
185
186             searchRecordKey (zh, reckeys, attname_str, ws, 32);
187
188             if (*s != ')')
189             {
190                 yaz_log (YLOG_WARN, "Missing ) in match criteria %s in group %s",
191                       spec, zh->m_group ? zh->m_group : "none");
192                 return NULL;
193             }
194             s++;
195
196             for (i = 0; i<32; i++)
197                 if (ws[i])
198                 {
199                     if (first)
200                     {
201                         *dst++ = ' ';
202                         first = 0;
203                     }
204                     strcpy (dst, ws[i]);
205                     dst += strlen(ws[i]);
206                 }
207             if (first)
208             {
209                 yaz_log (YLOG_WARN, "Record didn't contain match"
210                       " fields in (%s,%s)", attset_str, attname_str);
211                 return NULL;
212             }
213         }
214         else if (*s == '$')
215         {
216             int spec_len;
217             char special[64];
218             const char *spec_src = NULL;
219             const char *s1 = ++s;
220             while (*s1 && !strchr(FILE_MATCH_BLANK, *s1))
221                 s1++;
222
223             spec_len = s1 - s;
224             if (spec_len > sizeof(special)-1)
225                 spec_len = sizeof(special)-1;
226             memcpy (special, s, spec_len);
227             special[spec_len] = '\0';
228             s = s1;
229
230             if (!strcmp (special, "group"))
231                 spec_src = zh->m_group;
232             else if (!strcmp (special, "database"))
233                 spec_src = zh->basenames[0];
234             else if (!strcmp (special, "filename")) {
235                 spec_src = fname;
236             }
237             else if (!strcmp (special, "type"))
238                 spec_src = zh->m_record_type;
239             else 
240                 spec_src = NULL;
241             if (spec_src)
242             {
243                 strcpy (dst, spec_src);
244                 dst += strlen (spec_src);
245             }
246         }
247         else if (*s == '\"' || *s == '\'')
248         {
249             int stopMarker = *s++;
250             char tmpString[64];
251             int i = 0;
252
253             while (*s && *s != stopMarker)
254             {
255                 if (i+1 < sizeof(tmpString))
256                     tmpString[i++] = *s++;
257             }
258             if (*s)
259                 s++;
260             tmpString[i] = '\0';
261             strcpy (dst, tmpString);
262             dst += strlen (tmpString);
263         }
264         else
265         {
266             yaz_log (YLOG_WARN, "Syntax error in match criteria %s in group %s",
267                   spec, zh->m_group ? zh->m_group : "none");
268             return NULL;
269         }
270         *dst++ = 1;
271     }
272     if (dst == dstBuf)
273     {
274         yaz_log (YLOG_WARN, "No match criteria for record %s in group %s",
275               fname, zh->m_group ? zh->m_group : "none");
276         return NULL;
277     }
278     *dst = '\0';
279     return dstBuf;
280 }
281
282 struct recordLogInfo {
283     const char *fname;
284     int recordOffset;
285     struct recordGroup *rGroup;
286 };
287
288 static void init_extractCtrl(ZebraHandle zh, struct recExtractCtrl *ctrl)
289 {
290     int i;
291     for (i = 0; i<256; i++)
292     {
293         if (zebra_maps_is_positioned(zh->reg->zebra_maps, i))
294             ctrl->seqno[i] = 1;
295         else
296             ctrl->seqno[i] = 0;
297     }
298     ctrl->flagShowRecords = !zh->m_flag_rw;
299 }
300
301 static void all_matches_add(struct recExtractCtrl *ctrl)
302 {
303     RecWord word;
304     extract_init(ctrl, &word);
305     word.index_name = "_ALLRECORDS";
306     word.index_type = 'w';
307     word.seqno = 1;
308     extract_add_index_string (&word, zinfo_index_category_alwaysmatches,
309                               "", 0);
310 }
311
312 ZEBRA_RES zebra_extract_file(ZebraHandle zh, SYSNO *sysno, const char *fname, 
313                              int deleteFlag)
314 {
315     ZEBRA_RES r = ZEBRA_OK;
316     int i, fd;
317     char gprefix[128];
318     char ext[128];
319     char ext_res[128];
320     struct file_read_info *fi = 0;
321     const char *original_record_type = 0;
322     RecType recType;
323     void *recTypeClientData;
324     struct ZebraRecStream stream, *streamp;
325
326     zebra_init_log_level();
327
328     if (!zh->m_group || !*zh->m_group)
329         *gprefix = '\0';
330     else
331         sprintf (gprefix, "%s.", zh->m_group);
332     
333     yaz_log(log_level_extract, "zebra_extract_file %s", fname);
334
335     /* determine file extension */
336     *ext = '\0';
337     for (i = strlen(fname); --i >= 0; )
338         if (fname[i] == '/')
339             break;
340         else if (fname[i] == '.')
341         {
342             strcpy (ext, fname+i+1);
343             break;
344         }
345     /* determine file type - depending on extension */
346     original_record_type = zh->m_record_type;
347     if (!zh->m_record_type)
348     {
349         sprintf (ext_res, "%srecordType.%s", gprefix, ext);
350         zh->m_record_type = res_get (zh->res, ext_res);
351     }
352     if (!zh->m_record_type)
353     {
354         if (zh->records_processed < zh->m_file_verbose_limit)
355             yaz_log (YLOG_LOG, "? %s", fname);
356         return 0;
357     }
358     /* determine match criteria */
359     if (!zh->m_record_id)
360     {
361         sprintf (ext_res, "%srecordId.%s", gprefix, ext);
362         zh->m_record_id = res_get (zh->res, ext_res);
363     }
364
365     if (!(recType =
366           recType_byName (zh->reg->recTypes, zh->res, zh->m_record_type,
367                           &recTypeClientData)))
368     {
369         yaz_log(YLOG_WARN, "No such record type: %s", zh->m_record_type);
370         return ZEBRA_FAIL;
371     }
372
373     switch(recType->version)
374     {
375     case 0:
376         break;
377     default:
378         yaz_log(YLOG_WARN, "Bad filter version: %s", zh->m_record_type);
379     }
380     if (sysno && deleteFlag)
381     {
382         streamp = 0;
383         fi = 0;
384     }
385     else
386     {
387         char full_rep[1024];
388
389         if (zh->path_reg && !yaz_is_abspath (fname))
390         {
391             strcpy (full_rep, zh->path_reg);
392             strcat (full_rep, "/");
393             strcat (full_rep, fname);
394         }
395         else
396             strcpy (full_rep, fname);
397         
398         if ((fd = open (full_rep, O_BINARY|O_RDONLY)) == -1)
399         {
400             yaz_log (YLOG_WARN|YLOG_ERRNO, "open %s", full_rep);
401             zh->m_record_type = original_record_type;
402             return ZEBRA_FAIL;
403         }
404         streamp = &stream;
405         zebra_create_stream_fd(streamp, fd, 0);
406     }
407     while(1)
408     {
409         r = zebra_extract_record_stream(zh, streamp,
410                                         deleteFlag,
411                                         0, /* tst_mode */
412                                         zh->m_record_type,
413                                         sysno,
414                                         0, /*match_criteria */
415                                         fname,
416                                         1, /* force_update */
417                                         1, /* allow_update */
418                                         recType, recTypeClientData);
419         if (r != ZEBRA_OK)
420         {
421             break;
422         }
423         if (sysno)
424         {
425             break;
426         }
427     }
428     if (streamp)
429         stream.destroy(streamp);
430     zh->m_record_type = original_record_type;
431     return r;
432 }
433
434 /*
435   If sysno is provided, then it's used to identify the reocord.
436   If not, and match_criteria is provided, then sysno is guessed
437   If not, and a record is provided, then sysno is got from there
438   
439  */
440
441 ZEBRA_RES zebra_buffer_extract_record(ZebraHandle zh, 
442                                       const char *buf, size_t buf_size,
443                                       int delete_flag,
444                                       int test_mode, 
445                                       const char *recordType,
446                                       SYSNO *sysno,
447                                       const char *match_criteria,
448                                       const char *fname,
449                                       int force_update,
450                                       int allow_update)
451 {
452     struct ZebraRecStream stream;
453     ZEBRA_RES res;
454     void *clientData;
455     RecType recType = 0;
456
457     if (recordType && *recordType)
458     {
459         yaz_log(log_level_extract,
460                 "Record type explicitly specified: %s", recordType);
461         recType = recType_byName (zh->reg->recTypes, zh->res, recordType,
462                                   &clientData);
463     } 
464     else
465     {
466         if (!(zh->m_record_type))
467         {
468             yaz_log (YLOG_WARN, "No such record type defined");
469             return ZEBRA_FAIL;
470         }
471         yaz_log(log_level_extract, "Get record type from rgroup: %s",
472                 zh->m_record_type);
473         recType = recType_byName (zh->reg->recTypes, zh->res,
474                                   zh->m_record_type, &clientData);
475         recordType = zh->m_record_type;
476     }
477     
478     if (!recType)
479     {
480         yaz_log (YLOG_WARN, "No such record type: %s", recordType);
481         return ZEBRA_FAIL;
482     }
483
484
485
486     zebra_create_stream_mem(&stream, buf, buf_size);
487
488     res = zebra_extract_record_stream(zh, &stream,
489                                       delete_flag,
490                                       test_mode, 
491                                       recordType,
492                                       sysno,
493                                       match_criteria,
494                                       fname,
495                                       force_update,
496                                       allow_update,
497                                       recType, clientData);
498     stream.destroy(&stream);
499     return res;
500 }
501
502
503 ZEBRA_RES zebra_extract_record_stream(ZebraHandle zh, 
504                                       struct ZebraRecStream *stream,
505                                       int delete_flag,
506                                       int test_mode, 
507                                       const char *recordType,
508                                       SYSNO *sysno,
509                                       const char *match_criteria,
510                                       const char *fname,
511                                       int force_update,
512                                       int allow_update,
513                                       RecType recType,
514                                       void *recTypeClientData)
515
516 {
517     SYSNO sysno0 = 0;
518     RecordAttr *recordAttr;
519     struct recExtractCtrl extractCtrl;
520     int r;
521     const char *matchStr = 0;
522     Record rec;
523     off_t start_offset = 0;
524     const char *pr_fname = fname;  /* filename to print .. */
525     int show_progress = zh->records_processed < zh->m_file_verbose_limit ? 1:0;
526
527     zebra_init_log_level();
528
529     if (!pr_fname)
530         pr_fname = "<no file>";  /* make it printable if file is omitted */
531
532     zebra_rec_keys_reset(zh->reg->keys);
533     zebra_rec_keys_reset(zh->reg->sortKeys);
534
535     if (zebraExplain_curDatabase (zh->reg->zei, zh->basenames[0]))
536     {
537         if (zebraExplain_newDatabase (zh->reg->zei, zh->basenames[0], 
538                                       zh->m_explain_database))
539             return ZEBRA_FAIL;
540     }
541
542     if (stream)
543     {
544         off_t null_offset = 0;
545         extractCtrl.stream = stream;
546
547         start_offset = stream->tellf(stream);
548
549         extractCtrl.first_record = start_offset ? 0 : 1;
550         
551         stream->endf(stream, &null_offset);;
552
553         extractCtrl.init = extract_init;
554         extractCtrl.tokenAdd = extract_token_add;
555         extractCtrl.schemaAdd = extract_schema_add;
556         extractCtrl.dh = zh->reg->dh;
557         extractCtrl.handle = zh;
558         extractCtrl.match_criteria[0] = '\0';
559         extractCtrl.staticrank = 0;
560
561     
562         init_extractCtrl(zh, &extractCtrl);
563         
564         extract_set_store_data_prepare(&extractCtrl);
565         
566         r = (*recType->extract)(recTypeClientData, &extractCtrl);
567         
568         if (r == RECCTRL_EXTRACT_EOF)
569             return ZEBRA_FAIL;
570         else if (r == RECCTRL_EXTRACT_ERROR_GENERIC)
571         {
572             /* error occured during extraction ... */
573             yaz_log (YLOG_WARN, "extract error: generic");
574             return ZEBRA_FAIL;
575         }
576         else if (r == RECCTRL_EXTRACT_ERROR_NO_SUCH_FILTER)
577         {
578             /* error occured during extraction ... */
579             yaz_log (YLOG_WARN, "extract error: no such filter");
580             return ZEBRA_FAIL;
581         }
582         
583         all_matches_add(&extractCtrl);
584         
585         if (extractCtrl.match_criteria[0])
586             match_criteria = extractCtrl.match_criteria;
587     }
588     if (!sysno) {
589
590         sysno = &sysno0;
591
592         if (match_criteria && *match_criteria) {
593             matchStr = match_criteria;
594         } else {
595             if (zh->m_record_id && *zh->m_record_id) {
596                 matchStr = fileMatchStr (zh, zh->reg->keys, pr_fname, 
597                                          zh->m_record_id);
598                 if (!matchStr)
599                 {
600                     yaz_log (YLOG_WARN, "Bad match criteria (recordID)");
601                     return ZEBRA_FAIL;
602                 }
603             }
604         }
605         if (matchStr) 
606         {
607             int db_ord = zebraExplain_get_database_ord(zh->reg->zei);
608             char *rinfo = dict_lookup_ord(zh->reg->matchDict, db_ord,
609                                           matchStr);
610             if (rinfo)
611             {
612                 assert(*rinfo == sizeof(*sysno));
613                 memcpy (sysno, rinfo+1, sizeof(*sysno));
614             }
615         }
616     }
617     if (zebra_rec_keys_empty(zh->reg->keys))
618     {
619         /* the extraction process returned no information - the record
620            is probably empty - unless flagShowRecords is in use */
621         if (test_mode)
622             return ZEBRA_OK;
623     }
624
625     if (! *sysno)
626     {
627         /* new record */
628         if (delete_flag)
629         {
630             yaz_log (YLOG_LOG, "delete %s %s " ZINT_FORMAT, recordType,
631                          pr_fname, (zint) start_offset);
632             yaz_log (YLOG_WARN, "cannot delete record above (seems new)");
633             return ZEBRA_FAIL;
634         }
635         if (show_progress)
636             yaz_log (YLOG_LOG, "add %s %s " ZINT_FORMAT, recordType, pr_fname,
637                      (zint) start_offset);
638         rec = rec_new (zh->reg->records);
639
640         *sysno = rec->sysno;
641
642         recordAttr = rec_init_attr (zh->reg->zei, rec);
643         recordAttr->staticrank = extractCtrl.staticrank;
644
645         if (matchStr)
646         {
647             int db_ord = zebraExplain_get_database_ord(zh->reg->zei);
648             dict_insert_ord(zh->reg->matchDict, db_ord, matchStr,
649                             sizeof(*sysno), sysno);
650         }
651
652
653         extract_flushSortKeys (zh, *sysno, 1, zh->reg->sortKeys);
654         extract_flushRecordKeys (zh, *sysno, 1, zh->reg->keys,
655                          recordAttr->staticrank);
656         zh->records_inserted++;
657     } 
658     else
659     {
660         /* record already exists */
661         zebra_rec_keys_t delkeys = zebra_rec_keys_open();
662         zebra_rec_keys_t sortKeys = zebra_rec_keys_open();
663         if (!allow_update)
664         {
665             yaz_log (YLOG_LOG, "skipped %s %s " ZINT_FORMAT, 
666                          recordType, pr_fname, (zint) start_offset);
667             logRecord(zh);
668             return ZEBRA_FAIL;
669         }
670
671         rec = rec_get (zh->reg->records, *sysno);
672         assert (rec);
673         
674         recordAttr = rec_init_attr (zh->reg->zei, rec);
675
676         zebra_rec_keys_set_buf(delkeys,
677                                rec->info[recInfo_delKeys],
678                                rec->size[recInfo_delKeys],
679                                0);
680         zebra_rec_keys_set_buf(sortKeys,
681                                rec->info[recInfo_sortKeys],
682                                rec->size[recInfo_sortKeys],
683                                0);
684
685         extract_flushSortKeys (zh, *sysno, 0, sortKeys);
686         extract_flushRecordKeys (zh, *sysno, 0, delkeys,
687                                  recordAttr->staticrank);
688         if (delete_flag)
689         {
690             /* record going to be deleted */
691             if (zebra_rec_keys_empty(delkeys))
692             {
693                 yaz_log(YLOG_LOG, "delete %s %s " ZINT_FORMAT, recordType,
694                         pr_fname, (zint) start_offset);
695                 yaz_log(YLOG_WARN, "cannot delete file above, "
696                         "storeKeys false (3)");
697             }
698             else
699             {
700                 if (show_progress)
701                     yaz_log(YLOG_LOG, "delete %s %s " ZINT_FORMAT, recordType,
702                             pr_fname, (zint) start_offset);
703                 zh->records_deleted++;
704                 if (matchStr)
705                 {
706                     int db_ord = zebraExplain_get_database_ord(zh->reg->zei);
707                     dict_delete_ord(zh->reg->matchDict, db_ord, matchStr);
708                 }
709                 rec_del (zh->reg->records, &rec);
710             }
711             rec_free(&rec);
712             logRecord(zh);
713             return ZEBRA_OK;
714         }
715         else
716         {
717             if (show_progress)
718                     yaz_log(YLOG_LOG, "update %s %s " ZINT_FORMAT, recordType,
719                             pr_fname, (zint) ZINT_FORMAT);
720             recordAttr->staticrank = extractCtrl.staticrank;
721             extract_flushSortKeys (zh, *sysno, 1, zh->reg->sortKeys);
722             extract_flushRecordKeys (zh, *sysno, 1, zh->reg->keys, 
723                                          recordAttr->staticrank);
724             zh->records_updated++;
725         }
726         zebra_rec_keys_close(delkeys);
727         zebra_rec_keys_close(sortKeys);
728     }
729     /* update file type */
730     xfree (rec->info[recInfo_fileType]);
731     rec->info[recInfo_fileType] =
732         rec_strdup (recordType, &rec->size[recInfo_fileType]);
733
734     /* update filename */
735     xfree (rec->info[recInfo_filename]);
736     rec->info[recInfo_filename] =
737         rec_strdup (fname, &rec->size[recInfo_filename]);
738
739     /* update delete keys */
740     xfree (rec->info[recInfo_delKeys]);
741     if (!zebra_rec_keys_empty(zh->reg->keys) && zh->m_store_keys == 1)
742     {
743         zebra_rec_keys_get_buf(zh->reg->keys,
744                                &rec->info[recInfo_delKeys],
745                                &rec->size[recInfo_delKeys]);
746     }
747     else
748     {
749         rec->info[recInfo_delKeys] = NULL;
750         rec->size[recInfo_delKeys] = 0;
751     }
752     /* update sort keys */
753     xfree (rec->info[recInfo_sortKeys]);
754
755     zebra_rec_keys_get_buf(zh->reg->sortKeys,
756                            &rec->info[recInfo_sortKeys],
757                            &rec->size[recInfo_sortKeys]);
758
759     /* save file size of original record */
760     zebraExplain_recordBytesIncrement (zh->reg->zei,
761                                        - recordAttr->recordSize);
762     if (stream)
763     {
764         off_t end_offset = stream->endf(stream, 0);
765
766         if (!end_offset)
767             end_offset = stream->tellf(stream);
768         else
769             stream->seekf(stream, end_offset);
770
771         recordAttr->recordSize = end_offset - start_offset;
772         zebraExplain_recordBytesIncrement(zh->reg->zei,
773                                           recordAttr->recordSize);
774     }
775
776     /* set run-number for this record */
777     recordAttr->runNumber =
778         zebraExplain_runNumberIncrement (zh->reg->zei, 0);
779
780     /* update store data */
781     xfree (rec->info[recInfo_storeData]);
782
783     /* update store data */
784     if (zh->store_data_buf)
785     {
786         rec->size[recInfo_storeData] = zh->store_data_size;
787         rec->info[recInfo_storeData] = zh->store_data_buf;
788         zh->store_data_buf = 0;
789         recordAttr->recordSize = zh->store_data_size;
790     }
791     else if (zh->m_store_data)
792     {
793         off_t cur_offset = stream->tellf(stream);
794
795         rec->size[recInfo_storeData] = recordAttr->recordSize;
796         rec->info[recInfo_storeData] = (char *)
797             xmalloc (recordAttr->recordSize);
798         stream->seekf(stream, start_offset);
799         stream->readf(stream, rec->info[recInfo_storeData],
800                       recordAttr->recordSize);
801         stream->seekf(stream, cur_offset);
802     }
803     else
804     {
805         rec->info[recInfo_storeData] = NULL;
806         rec->size[recInfo_storeData] = 0;
807     }
808     /* update database name */
809     xfree (rec->info[recInfo_databaseName]);
810     rec->info[recInfo_databaseName] =
811         rec_strdup (zh->basenames[0], &rec->size[recInfo_databaseName]); 
812
813     /* update offset */
814     recordAttr->recordOffset = start_offset;
815     
816     /* commit this record */
817     rec_put (zh->reg->records, &rec);
818     logRecord(zh);
819     return ZEBRA_OK;
820 }
821
822 ZEBRA_RES zebra_extract_explain(void *handle, Record rec, data1_node *n)
823 {
824     ZebraHandle zh = (ZebraHandle) handle;
825     struct recExtractCtrl extractCtrl;
826
827     if (zebraExplain_curDatabase (zh->reg->zei,
828                                   rec->info[recInfo_databaseName]))
829     {
830         abort();
831         if (zebraExplain_newDatabase (zh->reg->zei,
832                                       rec->info[recInfo_databaseName], 0))
833             abort ();
834     }
835
836     zebra_rec_keys_reset(zh->reg->keys);
837     zebra_rec_keys_reset(zh->reg->sortKeys);
838
839     extractCtrl.init = extract_init;
840     extractCtrl.tokenAdd = extract_token_add;
841     extractCtrl.schemaAdd = extract_schema_add;
842     extractCtrl.dh = zh->reg->dh;
843
844     init_extractCtrl(zh, &extractCtrl);
845
846     extractCtrl.flagShowRecords = 0;
847     extractCtrl.match_criteria[0] = '\0';
848     extractCtrl.staticrank = 0;
849     extractCtrl.handle = handle;
850     extractCtrl.first_record = 1;
851     
852     extract_set_store_data_prepare(&extractCtrl);
853
854     if (n)
855         grs_extract_tree(&extractCtrl, n);
856
857     if (rec->size[recInfo_delKeys])
858     {
859         zebra_rec_keys_t delkeys = zebra_rec_keys_open();
860         
861         zebra_rec_keys_t sortkeys = zebra_rec_keys_open();
862
863         zebra_rec_keys_set_buf(delkeys, rec->info[recInfo_delKeys],
864                                rec->size[recInfo_delKeys],
865                                0);
866         extract_flushRecordKeys (zh, rec->sysno, 0, delkeys, 0);
867         zebra_rec_keys_close(delkeys);
868
869         zebra_rec_keys_set_buf(sortkeys, rec->info[recInfo_sortKeys],
870                                rec->size[recInfo_sortKeys],
871                                0);
872
873         extract_flushSortKeys (zh, rec->sysno, 0, sortkeys);
874         zebra_rec_keys_close(sortkeys);
875     }
876     extract_flushRecordKeys (zh, rec->sysno, 1, zh->reg->keys, 0);
877     extract_flushSortKeys (zh, rec->sysno, 1, zh->reg->sortKeys);
878
879     xfree (rec->info[recInfo_delKeys]);
880     zebra_rec_keys_get_buf(zh->reg->keys,
881                            &rec->info[recInfo_delKeys], 
882                            &rec->size[recInfo_delKeys]);
883
884     xfree (rec->info[recInfo_sortKeys]);
885     zebra_rec_keys_get_buf(zh->reg->sortKeys,
886                            &rec->info[recInfo_sortKeys],
887                            &rec->size[recInfo_sortKeys]);
888     return ZEBRA_OK;
889 }
890
891 void extract_rec_keys_log(ZebraHandle zh, int is_insert,
892                           zebra_rec_keys_t reckeys,
893                           int level)
894 {
895     if (zebra_rec_keys_rewind(reckeys))
896     {
897         size_t slen;
898         const char *str;
899         struct it_key key;
900         NMEM nmem = nmem_create();
901
902         while(zebra_rec_keys_read(reckeys, &str, &slen, &key))
903         {
904             char keystr[200]; /* room for zints to print */
905             char *dst_term = 0;
906             int ord = CAST_ZINT_TO_INT(key.mem[0]);
907             int index_type, i;
908             const char *string_index;
909             
910             zebraExplain_lookup_ord(zh->reg->zei, ord, &index_type,
911                                     0/* db */, &string_index);
912             assert(index_type);
913             zebra_term_untrans_iconv(zh, nmem, index_type,
914                                      &dst_term, str);
915             *keystr = '\0';
916             for (i = 0; i<key.len; i++)
917             {
918                 sprintf(keystr + strlen(keystr), ZINT_FORMAT " ", key.mem[i]);
919             }
920
921             if (*str < CHR_BASE_CHAR)
922             {
923                 int i;
924                 char dst_buf[200]; /* room for special chars */
925
926                 strcpy(dst_buf , "?");
927
928                 if (!strcmp(str, ""))
929                     strcpy(dst_buf, "alwaysmatches");
930                 if (!strcmp(str, FIRST_IN_FIELD_STR))
931                     strcpy(dst_buf, "firstinfield");
932                 else if (!strcmp(str, CHR_UNKNOWN))
933                     strcpy(dst_buf, "unknown");
934                 else if (!strcmp(str, CHR_SPACE))
935                     strcpy(dst_buf, "space");
936                 
937                 for (i = 0; i<slen; i++)
938                 {
939                     sprintf(dst_buf + strlen(dst_buf), " %d", str[i] & 0xff);
940                 }
941                 yaz_log(level, "%s%c %s %s", keystr, index_type,
942                         string_index, dst_buf);
943                 
944             }
945             else
946                 yaz_log(level, "%s%c %s \"%s\"", keystr, index_type,
947                         string_index, dst_term);
948
949             nmem_reset(nmem);
950         }
951         nmem_destroy(nmem);
952     }
953 }
954
955 void extract_rec_keys_adjust(ZebraHandle zh, int is_insert,
956                              zebra_rec_keys_t reckeys)
957 {
958     ZebraExplainInfo zei = zh->reg->zei;
959     struct ord_stat {
960         int no;
961         int ord;
962         struct ord_stat *next;
963     };
964
965     if (zebra_rec_keys_rewind(reckeys))
966     {
967         struct ord_stat *ord_list = 0;
968         struct ord_stat *p;
969         size_t slen;
970         const char *str;
971         struct it_key key_in;
972         while(zebra_rec_keys_read(reckeys, &str, &slen, &key_in))
973         {
974             int ord = CAST_ZINT_TO_INT(key_in.mem[0]);
975
976             for (p = ord_list; p ; p = p->next)
977                 if (p->ord == ord)
978                 {
979                     p->no++;
980                     break;
981                 }
982             if (!p)
983             {
984                 p = xmalloc(sizeof(*p));
985                 p->no = 1;
986                 p->ord = ord;
987                 p->next = ord_list;
988                 ord_list = p;
989             }
990         }
991
992         p = ord_list;
993         while (p)
994         {
995             struct ord_stat *p1 = p;
996
997             if (is_insert)
998                 zebraExplain_ord_adjust_occurrences(zei, p->ord, p->no, 1);
999             else
1000                 zebraExplain_ord_adjust_occurrences(zei, p->ord, - p->no, -1);
1001             p = p->next;
1002             xfree(p1);
1003         }
1004     }
1005 }
1006
1007 void extract_flushRecordKeys(ZebraHandle zh, SYSNO sysno, int cmd,
1008                              zebra_rec_keys_t reckeys,
1009                              zint staticrank)
1010 {
1011     ZebraExplainInfo zei = zh->reg->zei;
1012
1013     extract_rec_keys_adjust(zh, cmd, reckeys);
1014
1015     if (log_level_details)
1016     {
1017         yaz_log(log_level_details, "Keys for record " ZINT_FORMAT " %s",
1018                 sysno, cmd ? "insert" : "delete");
1019         extract_rec_keys_log(zh, cmd, reckeys, log_level_details);
1020     }
1021
1022     if (!zh->reg->key_block)
1023     {
1024         int mem = 1024*1024 * atoi( res_get_def( zh->res, "memmax", "8"));
1025         const char *key_tmp_dir = res_get_def (zh->res, "keyTmpDir", ".");
1026         int use_threads = atoi(res_get_def (zh->res, "threads", "1"));
1027         zh->reg->key_block = key_block_create(mem, key_tmp_dir, use_threads);
1028     }
1029     zebraExplain_recordCountIncrement (zei, cmd ? 1 : -1);
1030
1031     if (zebra_rec_keys_rewind(reckeys))
1032     {
1033         size_t slen;
1034         const char *str;
1035         struct it_key key_in;
1036         while(zebra_rec_keys_read(reckeys, &str, &slen, &key_in))
1037         {
1038             key_block_write(zh->reg->key_block, sysno, 
1039                             &key_in, cmd, str, slen,
1040                             staticrank, zh->m_staticrank);
1041         }
1042     }
1043 }
1044
1045
1046 ZEBRA_RES zebra_rec_keys_to_snippets(ZebraHandle zh,
1047                                      zebra_rec_keys_t reckeys,
1048                                      zebra_snippets *snippets)
1049 {
1050     NMEM nmem = nmem_create();
1051     if (zebra_rec_keys_rewind(reckeys)) 
1052     {
1053         const char *str;
1054         size_t slen;
1055         struct it_key key;
1056         while (zebra_rec_keys_read(reckeys, &str, &slen, &key))
1057         {
1058             char dst_buf[IT_MAX_WORD];
1059             char *dst_term = dst_buf;
1060             int ord;
1061             zint seqno;
1062             int index_type;
1063
1064             assert(key.len <= IT_KEY_LEVEL_MAX && key.len > 2);
1065             seqno = key.mem[key.len-1];
1066             ord = CAST_ZINT_TO_INT(key.mem[0]);
1067             
1068             zebraExplain_lookup_ord(zh->reg->zei, ord, &index_type,
1069                                     0/* db */, 0 /* string_index */);
1070             assert(index_type);
1071             zebra_term_untrans_iconv(zh, nmem, index_type,
1072                                      &dst_term, str);
1073             zebra_snippets_append(snippets, seqno, ord, dst_term);
1074             nmem_reset(nmem);
1075         }
1076     }
1077     nmem_destroy(nmem);
1078     return ZEBRA_OK;
1079 }
1080
1081 void print_rec_keys(ZebraHandle zh, zebra_rec_keys_t reckeys)
1082 {
1083     yaz_log(YLOG_LOG, "print_rec_keys");
1084     if (zebra_rec_keys_rewind(reckeys))
1085     {
1086         const char *str;
1087         size_t slen;
1088         struct it_key key;
1089         while (zebra_rec_keys_read(reckeys, &str, &slen, &key))
1090         {
1091             char dst_buf[IT_MAX_WORD];
1092             zint seqno;
1093             int index_type;
1094             int ord = CAST_ZINT_TO_INT(key.mem[0]);
1095             const char *db = 0;
1096             assert(key.len <= IT_KEY_LEVEL_MAX && key.len > 2);
1097
1098             zebraExplain_lookup_ord(zh->reg->zei, ord, &index_type, &db, 0);
1099             
1100             seqno = key.mem[key.len-1];
1101             
1102             zebra_term_untrans(zh, index_type, dst_buf, str);
1103             
1104             yaz_log(YLOG_LOG, "ord=%d seqno=" ZINT_FORMAT 
1105                     " term=%s", ord, seqno, dst_buf); 
1106         }
1107     }
1108 }
1109
1110 static void extract_add_index_string(RecWord *p, zinfo_index_category_t cat,
1111                                      const char *str, int length)
1112 {
1113     struct it_key key;
1114     ZebraHandle zh = p->extractCtrl->handle;
1115     ZebraExplainInfo zei = zh->reg->zei;
1116     int ch, i;
1117
1118     ch = zebraExplain_lookup_attr_str(zei, cat, p->index_type, p->index_name);
1119     if (ch < 0)
1120         ch = zebraExplain_add_attr_str(zei, cat, p->index_type, p->index_name);
1121
1122     i = 0;
1123     key.mem[i++] = ch;
1124     key.mem[i++] = p->record_id;
1125     key.mem[i++] = p->section_id;
1126
1127     if (zh->m_segment_indexing)
1128         key.mem[i++] = p->segment;
1129     key.mem[i++] = p->seqno;
1130     key.len = i;
1131
1132     zebra_rec_keys_write(zh->reg->keys, str, length, &key);
1133 }
1134
1135 static void extract_add_sort_string(RecWord *p, const char *str, int length)
1136 {
1137     struct it_key key;
1138     ZebraHandle zh = p->extractCtrl->handle;
1139     ZebraExplainInfo zei = zh->reg->zei;
1140     int ch;
1141     zinfo_index_category_t cat = zinfo_index_category_sort;
1142
1143     ch = zebraExplain_lookup_attr_str(zei, cat, p->index_type, p->index_name);
1144     if (ch < 0)
1145         ch = zebraExplain_add_attr_str(zei, cat, p->index_type, p->index_name);
1146     key.len = 2;
1147     key.mem[0] = ch;
1148     key.mem[1] = p->record_id;
1149
1150     zebra_rec_keys_write(zh->reg->sortKeys, str, length, &key);
1151 }
1152
1153 static void extract_add_string(RecWord *p, const char *string, int length)
1154 {
1155     ZebraHandle zh = p->extractCtrl->handle;
1156     assert (length > 0);
1157
1158     if (!p->index_name)
1159         return;
1160
1161     if (zebra_maps_is_sort(zh->reg->zebra_maps, p->index_type))
1162         extract_add_sort_string(p, string, length);
1163     else
1164     {
1165         extract_add_index_string(p, zinfo_index_category_index,
1166                                  string, length);
1167         if (zebra_maps_is_alwaysmatches(zh->reg->zebra_maps, p->index_type))
1168         {
1169             RecWord word;
1170             memcpy(&word, p, sizeof(word));
1171
1172             word.seqno = 1;
1173             extract_add_index_string(
1174                 &word, zinfo_index_category_alwaysmatches, "", 0);
1175         }
1176     }
1177 }
1178
1179 static void extract_add_incomplete_field(RecWord *p)
1180 {
1181     ZebraHandle zh = p->extractCtrl->handle;
1182     const char *b = p->term_buf;
1183     int remain = p->term_len;
1184     const char **map = 0;
1185     
1186     if (remain > 0)
1187         map = zebra_maps_input(zh->reg->zebra_maps, p->index_type, &b, remain, 0);
1188
1189     if (map)
1190     {   
1191         if (zebra_maps_is_first_in_field(zh->reg->zebra_maps, p->index_type))
1192         {
1193              /* first in field marker */
1194             extract_add_string(p, FIRST_IN_FIELD_STR, FIRST_IN_FIELD_LEN);
1195             p->seqno++;
1196         }
1197     }
1198     while (map)
1199     {
1200         char buf[IT_MAX_WORD+1];
1201         int i, remain;
1202
1203         /* Skip spaces */
1204         while (map && *map && **map == *CHR_SPACE)
1205         {
1206             remain = p->term_len - (b - p->term_buf);
1207             if (remain > 0)
1208                 map = zebra_maps_input(zh->reg->zebra_maps, p->index_type, &b,
1209                                        remain, 0);
1210             else
1211                 map = 0;
1212         }
1213         if (!map)
1214             break;
1215         i = 0;
1216         while (map && *map && **map != *CHR_SPACE)
1217         {
1218             const char *cp = *map;
1219
1220             while (i < IT_MAX_WORD && *cp)
1221                 buf[i++] = *(cp++);
1222             remain = p->term_len - (b - p->term_buf);
1223             if (remain > 0)
1224                 map = zebra_maps_input(zh->reg->zebra_maps, p->index_type, &b, remain, 0);
1225             else
1226                 map = 0;
1227         }
1228         if (!i)
1229             return;
1230         extract_add_string (p, buf, i);
1231         p->seqno++;
1232     }
1233 }
1234
1235 static void extract_add_complete_field (RecWord *p)
1236 {
1237     ZebraHandle zh = p->extractCtrl->handle;
1238     const char *b = p->term_buf;
1239     char buf[IT_MAX_WORD+1];
1240     const char **map = 0;
1241     int i = 0, remain = p->term_len;
1242
1243     if (remain > 0)
1244         map = zebra_maps_input (zh->reg->zebra_maps, p->index_type, &b, remain, 1);
1245
1246     while (remain > 0 && i < IT_MAX_WORD)
1247     {
1248         while (map && *map && **map == *CHR_SPACE)
1249         {
1250             remain = p->term_len - (b - p->term_buf);
1251
1252             if (remain > 0)
1253             {
1254                 int first = i ? 0 : 1;  /* first position */
1255                 map = zebra_maps_input(zh->reg->zebra_maps, p->index_type, &b, remain, first);
1256             }
1257             else
1258                 map = 0;
1259         }
1260         if (!map)
1261             break;
1262
1263         if (i && i < IT_MAX_WORD)
1264             buf[i++] = *CHR_SPACE;
1265         while (map && *map && **map != *CHR_SPACE)
1266         {
1267             const char *cp = *map;
1268
1269             if (**map == *CHR_CUT)
1270             {
1271                 i = 0;
1272             }
1273             else
1274             {
1275                 if (i >= IT_MAX_WORD)
1276                     break;
1277                 while (i < IT_MAX_WORD && *cp)
1278                     buf[i++] = *(cp++);
1279             }
1280             remain = p->term_len  - (b - p->term_buf);
1281             if (remain > 0)
1282             {
1283                 map = zebra_maps_input (zh->reg->zebra_maps, p->index_type, &b,
1284                                         remain, 0);
1285             }
1286             else
1287                 map = 0;
1288         }
1289     }
1290     if (!i)
1291         return;
1292     extract_add_string (p, buf, i);
1293 }
1294
1295 static void extract_token_add(RecWord *p)
1296 {
1297     ZebraHandle zh = p->extractCtrl->handle;
1298     WRBUF wrbuf;
1299
1300     if (log_level_extract)
1301     {
1302         yaz_log(log_level_extract, "extract_token_add "
1303                 "type=%c index=%s seqno=" ZINT_FORMAT " s=%.*s",
1304                 p->index_type, p->index_name, 
1305                 p->seqno, p->term_len, p->term_buf);
1306     }
1307     if ((wrbuf = zebra_replace(zh->reg->zebra_maps, p->index_type, 0,
1308                                p->term_buf, p->term_len)))
1309     {
1310         p->term_buf = wrbuf_buf(wrbuf);
1311         p->term_len = wrbuf_len(wrbuf);
1312     }
1313     if (zebra_maps_is_complete (zh->reg->zebra_maps, p->index_type))
1314         extract_add_complete_field (p);
1315     else
1316         extract_add_incomplete_field(p);
1317 }
1318
1319 static void extract_set_store_data_cb(struct recExtractCtrl *p,
1320                                       void *buf, size_t sz)
1321 {
1322     ZebraHandle zh = (ZebraHandle) p->handle;
1323
1324     xfree(zh->store_data_buf);
1325     zh->store_data_buf = 0;
1326     zh->store_data_size = 0;
1327     if (buf && sz)
1328     {
1329         zh->store_data_buf = xmalloc(sz);
1330         zh->store_data_size = sz;
1331         memcpy(zh->store_data_buf, buf, sz);
1332     }
1333 }
1334
1335 static void extract_set_store_data_prepare(struct recExtractCtrl *p)
1336 {
1337     ZebraHandle zh = (ZebraHandle) p->handle;
1338     xfree(zh->store_data_buf);
1339     zh->store_data_buf = 0;
1340     zh->store_data_size = 0;
1341     p->setStoreData = extract_set_store_data_cb;
1342 }
1343
1344 static void extract_schema_add(struct recExtractCtrl *p, Odr_oid *oid)
1345 {
1346     ZebraHandle zh = (ZebraHandle) p->handle;
1347     zebraExplain_addSchema (zh->reg->zei, oid);
1348 }
1349
1350 void extract_flushSortKeys(ZebraHandle zh, SYSNO sysno,
1351                            int cmd, zebra_rec_keys_t reckeys)
1352 {
1353     if (zebra_rec_keys_rewind(reckeys))
1354     {
1355         SortIdx sortIdx = zh->reg->sortIdx;
1356         size_t slen;
1357         const char *str;
1358         struct it_key key_in;
1359
1360         sortIdx_sysno (sortIdx, sysno);
1361
1362         while (zebra_rec_keys_read(reckeys, &str, &slen, &key_in))
1363         {
1364             int ord = CAST_ZINT_TO_INT(key_in.mem[0]);
1365             
1366             sortIdx_type(sortIdx, ord);
1367             if (cmd == 1)
1368                 sortIdx_add(sortIdx, str, slen);
1369             else
1370                 sortIdx_add(sortIdx, "", 1);
1371         }
1372     }
1373 }
1374
1375 /*
1376  * Local variables:
1377  * c-basic-offset: 4
1378  * indent-tabs-mode: nil
1379  * End:
1380  * vim: shiftwidth=4 tabstop=8 expandtab
1381  */
1382