1d6f628ca38b9e5671e554dfbb3d1e99ab24b4f8
[idzebra-moved-to-github.git] / index / rpnscan.c
1 /* $Id: rpnscan.c,v 1.25 2008-01-24 16:17:03 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 #include <stdio.h>
24 #include <assert.h>
25 #ifdef WIN32
26 #include <io.h>
27 #endif
28 #if HAVE_UNISTD_H
29 #include <unistd.h>
30 #endif
31 #include <ctype.h>
32
33 #include <yaz/diagbib1.h>
34 #include "index.h"
35 #include <zebra_xpath.h>
36 #include <yaz/wrbuf.h>
37 #include <attrfind.h>
38 #include <charmap.h>
39 #include <rset.h>
40 #include <yaz/oid_db.h>
41
42 #define RPN_MAX_ORDS 32
43
44 /* convert APT SCAN term to internal cmap */
45 static ZEBRA_RES trans_scan_term(ZebraHandle zh, Z_AttributesPlusTerm *zapt,
46                                  char *termz, zebra_map_t zm)
47 {
48     char term_utf8[IT_MAX_WORD];
49
50     if (zapt_term_to_utf8(zh, zapt, term_utf8) == ZEBRA_FAIL)
51         return ZEBRA_FAIL;    /* error */
52     else if (zebra_maps_is_icu(zm))
53     {
54         const char *res_buf;
55         size_t res_len;
56         zebra_map_tokenize_start(zm, term_utf8, strlen(term_utf8));
57         
58         if (zebra_map_tokenize_next(zm, &res_buf, &res_len, 0, 0))
59         {
60             memcpy(termz, res_buf, res_len);
61             termz[res_len] = '\0';
62         }
63         else
64             termz[0] = '\0';
65     }
66     else
67     {
68         const char **map;
69         const char *cp = (const char *) term_utf8;
70         const char *cp_end = cp + strlen(cp);
71         const char *src;
72         int i = 0;
73         const char *space_map = NULL;
74         int len;
75             
76         while ((len = (cp_end - cp)) > 0)
77         {
78             map = zebra_maps_input(zm, &cp, len, 0);
79             if (**map == *CHR_SPACE)
80                 space_map = *map;
81             else
82             {
83                 if (i && space_map)
84                     for (src = space_map; *src; src++)
85                         termz[i++] = *src;
86                 space_map = NULL;
87                 for (src = *map; *src; src++)
88                     termz[i++] = *src;
89             }
90         }
91         termz[i] = '\0';
92     }
93     return ZEBRA_OK;
94 }
95
96 static void get_first_snippet_from_rset(ZebraHandle zh, 
97                                         RSET rset, zebra_snippets *snippets, 
98                                         zint *sysno)
99 {
100     struct it_key key;
101     RSFD rfd;
102     TERMID termid;
103     size_t sysno_mem_index = 0;
104
105     if (zh->m_staticrank)
106         sysno_mem_index = 1;
107
108     yaz_log(YLOG_DEBUG, "get_first_snippet_from_rset");
109
110     rfd = rset_open(rset, RSETF_READ);
111     *sysno = 0;
112     while (rset_read(rfd, &key, &termid))
113     {
114         if (key.mem[sysno_mem_index] != *sysno)
115         {
116             if (*sysno)
117                 break;
118             *sysno = key.mem[sysno_mem_index];
119         }
120         if (termid)
121         {
122             struct ord_list *ol;
123             for (ol = termid->ol; ol; ol = ol->next)
124             {
125                 zebra_snippets_append(snippets, key.mem[key.len-1], 0,
126                                       ol->ord, termid->name);
127             }
128         }
129     }
130     rset_close(rfd);
131 }
132
133 struct scan2_info_entry {
134     WRBUF term;
135     char prefix[20];
136     ISAM_P isam_p;
137     int pos_to_save;
138     int ord;
139 };
140
141 static int scan_handle2(char *name, const char *info, int pos, void *client)
142 {
143     int len_prefix;
144     struct scan2_info_entry *scan_info = (struct scan2_info_entry *) client;
145
146     if (scan_info->pos_to_save != pos)
147         return 0;
148
149     len_prefix = strlen(scan_info->prefix);
150     if (memcmp(name, scan_info->prefix, len_prefix))
151         return 1;
152
153     /* skip special terms such as first-in-field specials */
154     if (name[len_prefix] < CHR_BASE_CHAR)
155         return 1;
156
157     wrbuf_rewind(scan_info->term);
158     wrbuf_puts(scan_info->term, name+len_prefix);
159
160     assert(*info == sizeof(ISAM_P));
161     memcpy(&scan_info->isam_p, info+1, sizeof(ISAM_P));
162     return 0;
163 }
164
165
166 static int scan_save_set(ZebraHandle zh, ODR stream, NMEM nmem,
167                          struct rset_key_control *kc,
168                          Z_AttributesPlusTerm *zapt,
169                          RSET limit_set,
170                          const char *term, 
171                          const char *index_type,
172                          struct scan2_info_entry *ar, int ord_no,
173                          ZebraScanEntry *glist, int pos)
174 {
175     int i;
176     RSET rset = 0;
177     zint approx_limit = zh->approx_limit;
178     AttrType global_hits_limit_attr;
179     int l;
180     attr_init_APT(&global_hits_limit_attr, zapt, 12);
181             
182     l = attr_find(&global_hits_limit_attr, NULL);
183     if (l != -1)
184         approx_limit = l;
185     
186     for (i = 0; i < ord_no; i++)
187     {
188         if (ar[i].isam_p && strcmp(wrbuf_cstr(ar[i].term), term) == 0)
189         {
190             struct ord_list *ol = ord_list_create(nmem);
191             RSET rset_t;
192
193             ol = ord_list_append(nmem, ol, ar[i].ord);
194
195             assert(ol);
196             rset_t = rset_trunc(
197                     zh, &ar[i].isam_p, 1,
198                     wrbuf_buf(ar[i].term), wrbuf_len(ar[i].term),
199                     NULL, 1, zapt->term->which, nmem, 
200                     kc, kc->scope, ol, index_type, 
201                     0 /* hits_limit_value */,
202                     0 /* term_ref_id_str */);
203             if (!rset)
204                 rset = rset_t;
205             else
206             {
207                 RSET rsets[2];
208                 
209                 rsets[0] = rset;
210                 rsets[1] = rset_t;
211                 rset = rset_create_or(nmem, kc, kc->scope, 0 /* termid */,
212                                       2, rsets);
213             }
214             ar[i].isam_p = 0;
215         }
216     }
217     if (rset)
218     {
219         zint count;
220         /* merge with limit_set if given */
221         if (limit_set)
222         {
223             RSET rsets[2];
224             rsets[0] = rset;
225             rsets[1] = rset_dup(limit_set);
226             
227             rset = rset_create_and(nmem, kc, kc->scope, 2, rsets);
228         }
229         /* count it */
230         zebra_count_set(zh, rset, &count, approx_limit);
231
232         if (pos != -1)
233         {
234             zint sysno;
235             zebra_snippets *hit_snippets = zebra_snippets_create();
236
237             glist[pos].term = 0;
238             glist[pos].display_term = 0;
239             
240             get_first_snippet_from_rset(zh, rset, hit_snippets, &sysno);
241             if (sysno)
242             {
243                 zebra_snippets *rec_snippets = zebra_snippets_create();
244                 int code = zebra_get_rec_snippets(zh, sysno, rec_snippets);
245                 if (code == 0)
246                 {
247                     const struct zebra_snippet_word *w = 
248                         zebra_snippets_lookup(rec_snippets, hit_snippets);
249                     if (w)
250                     {
251                         glist[pos].display_term = odr_strdup(stream, w->term);
252                     }
253                     else
254                     {
255                         yaz_log(YLOG_WARN, "zebra_snippets_lookup failed for pos=%d", pos);
256                     }
257                 }
258                 zebra_snippets_destroy(rec_snippets);
259             }
260             if (zebra_term_untrans_iconv(zh, stream->mem, index_type,
261                                          &glist[pos].term, term))
262             {
263                 /* failed.. use display_term instead (which could be 0) */
264                 glist[pos].term = glist[pos].display_term;
265             }
266
267             if (!glist[pos].term)
268             {
269                 yaz_log(YLOG_WARN, "Could not generate scan term for pos=%d",
270                         pos);
271                 glist[pos].term = "None";
272             }
273             glist[pos].occurrences = count;
274             zebra_snippets_destroy(hit_snippets);
275         }
276         rset_delete(rset);
277         if (count > 0)
278             return 1;
279         else
280             return 0;
281     }
282     return 0;
283 }
284
285 static ZEBRA_RES rpn_scan_norm(ZebraHandle zh, ODR stream, NMEM nmem,
286                                struct rset_key_control *kc,
287                                Z_AttributesPlusTerm *zapt,
288                                int *position, int *num_entries, 
289                                ZebraScanEntry **list,
290                                int *is_partial, RSET limit_set,
291                                const char *index_type,
292                                int ord_no, int *ords)
293 {
294     struct scan2_info_entry *ar = nmem_malloc(nmem, sizeof(*ar) * ord_no);
295     struct rpn_char_map_info rcmi;
296     zebra_map_t zm = zebra_map_get_or_add(zh->reg->zebra_maps, index_type);
297     int i, dif;
298     int after_pos;
299     int pos = 0;
300
301     ZebraScanEntry *glist = (ZebraScanEntry *)
302         odr_malloc(stream, *num_entries * sizeof(*glist));
303
304     *is_partial = 0;
305     if (*position > *num_entries+1)
306     {
307         *is_partial = 1;
308         *position = 1;
309         *num_entries = 0;
310         return ZEBRA_OK;
311     }
312     rpn_char_map_prepare(zh->reg, zm, &rcmi);
313
314     for (i = 0; i < ord_no; i++)
315         ar[i].term = wrbuf_alloc();
316
317     for (i = 0; i < ord_no; i++)
318     {
319         char termz[IT_MAX_WORD+20];
320         int prefix_len = 0;
321         
322         prefix_len = key_SU_encode(ords[i], termz);
323         termz[prefix_len] = 0;
324         strcpy(ar[i].prefix, termz);
325         
326         if (trans_scan_term(zh, zapt, termz+prefix_len, zm) == 
327             ZEBRA_FAIL)
328         {
329             for (i = 0; i < ord_no; i++)
330                 wrbuf_destroy(ar[i].term);
331             return ZEBRA_FAIL;
332         }
333         wrbuf_rewind(ar[i].term);
334         wrbuf_puts(ar[i].term, termz + prefix_len);
335         ar[i].isam_p = 0;
336         ar[i].ord = ords[i];
337     }
338     /** deal with terms before position .. */
339     /* the glist index starts at zero (unlike scan positions */
340     for (pos = *position-2; pos >= 0; )
341     {
342         const char *hi = 0;
343
344         /* scan on all maximum terms */
345         for (i = 0; i < ord_no; i++)
346         {
347             if (ar[i].isam_p == 0)
348             {
349                 char termz[IT_MAX_WORD+20];
350                 int before = 1;
351                 int after = 0;
352
353                 ar[i].pos_to_save = -1;
354
355                 strcpy(termz, ar[i].prefix);
356                 strcat(termz, wrbuf_cstr(ar[i].term));
357                 dict_scan(zh->reg->dict, termz, &before, &after,
358                           ar+i, scan_handle2);
359             }
360         }
361         /* get maximum after scan */
362         for (i = 0; i < ord_no; i++)
363         {
364             if (ar[i].isam_p 
365                 && (hi == 0 || strcmp(wrbuf_cstr(ar[i].term), hi) > 0))
366                 hi = wrbuf_cstr(ar[i].term);
367         }
368         if (!hi)
369             break;
370         if (scan_save_set(zh, stream, nmem, kc, zapt, limit_set, hi,
371                           index_type, ar, ord_no, glist,
372                           (pos >= 0 && pos < *num_entries) ? pos : -1))
373             --pos;
374     }
375     /* see if we got all terms before.. */
376     dif = 1 + pos;
377     if (dif > 0)
378     {
379         /* did not get all terms; adjust the real position and reduce
380            number of entries */
381         yaz_log(YLOG_LOG, "before terms dif=%d", dif);
382         glist = glist + dif;
383         *num_entries -= dif;
384         *position -= dif;
385         *is_partial = 1;
386     }
387     for (i = 0; i < ord_no; i++)
388     {
389         char termz[IT_MAX_WORD+20];
390         int prefix_len = 0;
391         
392         prefix_len = key_SU_encode(ords[i], termz);
393         termz[prefix_len] = 0;
394         strcpy(ar[i].prefix, termz);
395         
396         if (trans_scan_term(zh, zapt, termz+prefix_len, zm) == 
397             ZEBRA_FAIL)
398             return ZEBRA_FAIL;
399         wrbuf_rewind(ar[i].term);
400         wrbuf_puts(ar[i].term, termz + prefix_len);
401         ar[i].isam_p = 0;
402         ar[i].ord = ords[i];
403     }
404
405     after_pos = 1;  /* immediate term first.. */
406     for (pos = *position-1; pos < *num_entries; )
407     {
408         const char *lo = 0;
409
410         /* scan on all minimum terms */
411         for (i = 0; i < ord_no; i++)
412         {
413             if (ar[i].isam_p == 0)
414             {
415                 char termz[IT_MAX_WORD+20];
416                 int before = 0;
417                 int after = after_pos;
418
419                 ar[i].pos_to_save = 1;
420
421                 strcpy(termz, ar[i].prefix);
422                 strcat(termz, wrbuf_cstr(ar[i].term));
423                 dict_scan(zh->reg->dict, termz, &before, &after,
424                           ar+i, scan_handle2);
425             }
426         }
427         after_pos = 2;  /* next round we grab following term */
428
429         /* get minimum after scan */
430         for (i = 0; i < ord_no; i++)
431         {
432             if (ar[i].isam_p 
433                 && (lo == 0 || strcmp(wrbuf_cstr(ar[i].term), lo) < 0))
434                 lo = wrbuf_cstr(ar[i].term);
435         }
436         if (!lo)
437             break;
438         if (scan_save_set(zh, stream, nmem, kc, zapt, limit_set, lo,
439                           index_type, ar, ord_no, glist,
440                           (pos >= 0 && pos < *num_entries) ? pos : -1))
441             pos++;
442
443     }
444     if (pos != *num_entries)
445     {
446         if (pos >= 0)
447             *num_entries = pos;
448         else
449             *num_entries = 0;
450         *is_partial = 1;
451     }
452
453     *list = glist;
454
455     for (i = 0; i < ord_no; i++)
456         wrbuf_destroy(ar[i].term);
457
458     return ZEBRA_OK;
459 }
460
461 struct scan1_info_entry {
462     char *term;
463     ISAM_P isam_p;
464 };
465
466 struct scan_info {
467     struct scan1_info_entry *list;
468     ODR odr;
469     int before, after;
470     char prefix[20];
471 };
472
473 ZEBRA_RES rpn_scan(ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
474                    const Odr_oid *attributeset,
475                    int num_bases, char **basenames,
476                    int *position, int *num_entries, ZebraScanEntry **list,
477                    int *is_partial, const char *set_name)
478 {
479     int base_no;
480     int ords[RPN_MAX_ORDS], ord_no = 0;
481
482     const char *index_type;
483     char *search_type = NULL;
484     char rank_type[128];
485     int complete_flag;
486     int sort_flag;
487     NMEM nmem;
488     ZEBRA_RES res;
489     struct rset_key_control *kc = 0;
490     RSET limit_set = 0;
491
492     *list = 0;
493     *is_partial = 0;
494
495     if (!attributeset)
496         attributeset = yaz_oid_attset_bib_1;
497
498     if (!set_name)
499     {
500         /* see if there is a @attr 8=set */
501         AttrType termset;
502         int termset_value_numeric;
503         const char *termset_value_string = 0;
504         attr_init_APT(&termset, zapt, 8);
505         termset_value_numeric =
506             attr_find_ex(&termset, NULL, &termset_value_string);
507         if (termset_value_numeric != -1)
508         {
509             if (termset_value_numeric != -2)
510             {
511                 char resname[32];
512                 sprintf(resname, "%d", termset_value_numeric);
513                 set_name = odr_strdup(stream, resname); 
514             }
515             else
516                 set_name = odr_strdup(stream, termset_value_string);
517         }
518     }
519
520     if (set_name)
521     {
522         limit_set = resultSetRef(zh, set_name);
523         
524         if (!limit_set)
525         {
526             zebra_setError(zh, 
527                            YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST,
528                            set_name);
529             return ZEBRA_FAIL;
530         }
531     }
532
533     yaz_log(YLOG_DEBUG, "position = %d, num = %d",
534             *position, *num_entries);
535         
536     if (zebra_maps_attr(zh->reg->zebra_maps, zapt, &index_type, &search_type,
537                         rank_type, &complete_flag, &sort_flag))
538     {
539         *num_entries = 0;
540         zebra_setError(zh, YAZ_BIB1_UNSUPP_ATTRIBUTE_TYPE, 0);
541         return ZEBRA_FAIL;
542     }
543     if (num_bases > RPN_MAX_ORDS)
544     {
545         zebra_setError(zh, YAZ_BIB1_TOO_MANY_DATABASES_SPECIFIED, 0);
546         return ZEBRA_FAIL;
547     }
548     for (base_no = 0; base_no < num_bases; base_no++)
549     {
550         int ord;
551
552         if (zebraExplain_curDatabase(zh->reg->zei, basenames[base_no]))
553         {
554             zebra_setError(zh, YAZ_BIB1_DATABASE_UNAVAILABLE,
555                            basenames[base_no]);
556             *num_entries = 0;
557             return ZEBRA_FAIL;
558         }
559         if (zebra_apt_get_ord(zh, zapt, index_type, 0, attributeset, &ord) 
560             != ZEBRA_OK)
561             continue;
562         ords[ord_no++] = ord;
563     }
564     if (ord_no == 0)
565     {
566         *num_entries = 0; /* zebra_apt_get_ord should set error reason */
567         return ZEBRA_FAIL;
568     }
569     if (*num_entries < 1)
570     {
571         *num_entries = 0;
572         return ZEBRA_OK;
573     }
574     nmem = nmem_create();
575     kc = zebra_key_control_create(zh);
576
577     res = rpn_scan_norm(zh, stream, nmem, kc, zapt, position, num_entries,
578                         list, is_partial, limit_set,
579                         index_type, ord_no, ords);
580     nmem_destroy(nmem);
581     (*kc->dec)(kc);
582     return res;
583 }
584
585 /*
586  * Local variables:
587  * c-basic-offset: 4
588  * indent-tabs-mode: nil
589  * End:
590  * vim: shiftwidth=4 tabstop=8 expandtab
591  */
592