Fix uninit variable (hits_limit)
[idzebra-moved-to-github.git] / index / rpnscan.c
1 /* This file is part of the Zebra server.
2    Copyright (C) 1994-2011 Index Data
3
4 Zebra is free software; you can redistribute it and/or modify it under
5 the terms of the GNU General Public License as published by the Free
6 Software Foundation; either version 2, or (at your option) any later
7 version.
8
9 Zebra is distributed in the hope that it will be useful, but WITHOUT ANY
10 WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17
18 */
19
20 #if HAVE_CONFIG_H
21 #include <config.h>
22 #endif
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     wrbuf_rewind(scan_info->term);
153     wrbuf_puts(scan_info->term, name+len_prefix);
154
155     assert(*info == sizeof(ISAM_P));
156     memcpy(&scan_info->isam_p, info+1, sizeof(ISAM_P));
157     return 0;
158 }
159
160
161 static int scan_save_set(ZebraHandle zh, ODR stream, NMEM nmem,
162                          struct rset_key_control *kc,
163                          Z_AttributesPlusTerm *zapt,
164                          RSET limit_set,
165                          const char *term, 
166                          const char *index_type,
167                          struct scan2_info_entry *ar, int ord_no,
168                          ZebraScanEntry *glist, int pos)
169 {
170     int i;
171     RSET rset = 0;
172     zint approx_limit = zh->approx_limit;
173     AttrType global_hits_limit_attr;
174     int l;
175     attr_init_APT(&global_hits_limit_attr, zapt, 12);
176             
177     l = attr_find(&global_hits_limit_attr, NULL);
178     if (l != -1)
179         approx_limit = l;
180     
181     for (i = 0; i < ord_no; i++)
182     {
183         if (ar[i].isam_p && strcmp(wrbuf_cstr(ar[i].term), term) == 0)
184         {
185             if (strcmp(term, FIRST_IN_FIELD_STR))
186             {
187                 struct ord_list *ol = ord_list_create(nmem);
188                 RSET rset_t;
189                 
190                 ol = ord_list_append(nmem, ol, ar[i].ord);
191                 
192                 assert(ol);
193                 rset_t = rset_trunc(
194                     zh, &ar[i].isam_p, 1,
195                     wrbuf_buf(ar[i].term), wrbuf_len(ar[i].term),
196                     NULL, 1, zapt->term->which, nmem, 
197                     kc, kc->scope, ol, index_type, 
198                     0 /* hits_limit_value */,
199                     0 /* term_ref_id_str */);
200                 if (!rset)
201                     rset = rset_t;
202                 else
203                 {
204                     RSET rsets[2];
205                     
206                     rsets[0] = rset;
207                     rsets[1] = rset_t;
208                     rset = rset_create_or(nmem, kc, kc->scope, 0 /* termid */,
209                                           2, rsets);
210                 }
211             }
212             ar[i].isam_p = 0;
213         }
214     }
215     if (rset)
216     {
217         zint count;
218         /* merge with limit_set if given */
219         if (limit_set)
220         {
221             RSET rsets[2];
222             rsets[0] = rset;
223             rsets[1] = rset_dup(limit_set);
224             
225             rset = rset_create_and(nmem, kc, kc->scope, 2, rsets);
226         }
227         /* count it */
228         zebra_count_set(zh, rset, &count, approx_limit);
229
230         if (pos != -1)
231         {
232             zint sysno;
233             zebra_snippets *hit_snippets = zebra_snippets_create();
234
235             glist[pos].term = 0;
236             glist[pos].display_term = 0;
237             
238             get_first_snippet_from_rset(zh, rset, hit_snippets, &sysno);
239             if (sysno)
240             {
241                 zebra_snippets *rec_snippets = zebra_snippets_create();
242                 int code = zebra_get_rec_snippets(zh, sysno, rec_snippets);
243                 if (code == 0)
244                 {
245                     const struct zebra_snippet_word *w = 
246                         zebra_snippets_lookup(rec_snippets, hit_snippets);
247                     if (w)
248                     {
249                         glist[pos].display_term = odr_strdup(stream, w->term);
250                     }
251                     else
252                     {
253                         yaz_log(YLOG_WARN, "zebra_snippets_lookup failed for pos=%d", pos);
254                     }
255                 }
256                 zebra_snippets_destroy(rec_snippets);
257             }
258             if (zebra_term_untrans_iconv(zh, stream->mem, index_type,
259                                          &glist[pos].term, term))
260             {
261                 /* failed.. use display_term instead (which could be 0) */
262                 glist[pos].term = glist[pos].display_term;
263             }
264
265             if (!glist[pos].term)
266             {
267                 yaz_log(YLOG_WARN, "Could not generate scan term for pos=%d",
268                         pos);
269                 glist[pos].term = "None";
270             }
271             glist[pos].occurrences = count;
272             zebra_snippets_destroy(hit_snippets);
273         }
274         rset_delete(rset);
275         if (count > 0)
276             return 1;
277         else
278             return 0;
279     }
280     return 0;
281 }
282
283 static ZEBRA_RES rpn_scan_norm(ZebraHandle zh, ODR stream, NMEM nmem,
284                                struct rset_key_control *kc,
285                                Z_AttributesPlusTerm *zapt,
286                                int *position, int *num_entries, 
287                                ZebraScanEntry **list,
288                                int *is_partial, RSET limit_set,
289                                const char *index_type,
290                                int ord_no, int *ords)
291 {
292     struct scan2_info_entry *ar = nmem_malloc(nmem, sizeof(*ar) * ord_no);
293     struct rpn_char_map_info rcmi;
294     zebra_map_t zm = zebra_map_get_or_add(zh->reg->zebra_maps, index_type);
295     int i, dif;
296     int after_pos;
297     int pos = 0;
298
299     ZebraScanEntry *glist = (ZebraScanEntry *)
300         odr_malloc(stream, *num_entries * sizeof(*glist));
301
302     *is_partial = 0;
303     rpn_char_map_prepare(zh->reg, zm, &rcmi);
304
305     for (i = 0; i < ord_no; i++)
306         ar[i].term = wrbuf_alloc();
307
308     for (i = 0; i < ord_no; i++)
309     {
310         char termz[IT_MAX_WORD+20];
311         int prefix_len = 0;
312         
313         prefix_len = key_SU_encode(ords[i], termz);
314         termz[prefix_len] = 0;
315         strcpy(ar[i].prefix, termz);
316         
317         if (trans_scan_term(zh, zapt, termz+prefix_len, zm) == 
318             ZEBRA_FAIL)
319         {
320             for (i = 0; i < ord_no; i++)
321                 wrbuf_destroy(ar[i].term);
322             return ZEBRA_FAIL;
323         }
324         wrbuf_rewind(ar[i].term);
325         wrbuf_puts(ar[i].term, termz + prefix_len);
326         ar[i].isam_p = 0;
327         ar[i].ord = ords[i];
328     }
329     /** deal with terms before position .. */
330     /* the glist index starts at zero (unlike scan positions */
331     for (pos = *position-2; pos >= 0; )
332     {
333         const char *hi = 0;
334
335         /* scan on all maximum terms */
336         for (i = 0; i < ord_no; i++)
337         {
338             if (ar[i].isam_p == 0)
339             {
340                 char termz[IT_MAX_WORD+20];
341                 int before = 1;
342                 int after = 0;
343
344                 ar[i].pos_to_save = -1;
345
346                 strcpy(termz, ar[i].prefix);
347                 strcat(termz, wrbuf_cstr(ar[i].term));
348                 dict_scan(zh->reg->dict, termz, &before, &after,
349                           ar+i, scan_handle2);
350             }
351         }
352         /* get maximum after scan */
353         for (i = 0; i < ord_no; i++)
354         {
355             if (ar[i].isam_p 
356                 && (hi == 0 || strcmp(wrbuf_cstr(ar[i].term), hi) > 0))
357                 hi = wrbuf_cstr(ar[i].term);
358         }
359         if (!hi)
360             break;
361         if (scan_save_set(zh, stream, nmem, kc, zapt, limit_set, hi,
362                           index_type, ar, ord_no, glist,
363                           (pos >= 0 && pos < *num_entries) ? pos : -1))
364             --pos;
365     }
366     /* see if we got all terms before.. */
367     dif = 1 + pos;
368     if (dif > 0)
369     {
370         /* did not get all terms; adjust the real position and reduce
371            number of entries */
372         if (dif < *num_entries)
373         {
374             glist = glist + dif;
375             *num_entries -= dif;
376         }
377         else
378             *num_entries = 0;
379         *position -= dif;
380         *is_partial = 1;
381     }
382     for (i = 0; i < ord_no; i++)
383     {
384         char termz[IT_MAX_WORD+20];
385         int prefix_len = 0;
386         
387         prefix_len = key_SU_encode(ords[i], termz);
388         termz[prefix_len] = 0;
389         strcpy(ar[i].prefix, termz);
390         
391         if (trans_scan_term(zh, zapt, termz+prefix_len, zm) == 
392             ZEBRA_FAIL)
393             return ZEBRA_FAIL;
394         wrbuf_rewind(ar[i].term);
395         wrbuf_puts(ar[i].term, termz + prefix_len);
396         ar[i].isam_p = 0;
397         ar[i].ord = ords[i];
398     }
399
400     after_pos = 1;  /* immediate term first.. */
401     for (pos = *position-1; pos < *num_entries; )
402     {
403         const char *lo = 0;
404
405         /* scan on all minimum terms */
406         for (i = 0; i < ord_no; i++)
407         {
408             if (ar[i].isam_p == 0)
409             {
410                 char termz[IT_MAX_WORD+20];
411                 int before = 0;
412                 int after = after_pos;
413
414                 ar[i].pos_to_save = 1;
415
416                 strcpy(termz, ar[i].prefix);
417                 strcat(termz, wrbuf_cstr(ar[i].term));
418                 dict_scan(zh->reg->dict, termz, &before, &after,
419                           ar+i, scan_handle2);
420             }
421         }
422         after_pos = 2;  /* next round we grab following term */
423
424         /* get minimum after scan */
425         for (i = 0; i < ord_no; i++)
426         {
427             if (ar[i].isam_p 
428                 && (lo == 0 || strcmp(wrbuf_cstr(ar[i].term), lo) < 0))
429                 lo = wrbuf_cstr(ar[i].term);
430         }
431         if (!lo)
432             break;
433         if (scan_save_set(zh, stream, nmem, kc, zapt, limit_set, lo,
434                           index_type, ar, ord_no, glist,
435                           (pos >= 0 && pos < *num_entries) ? pos : -1))
436             pos++;
437
438     }
439     if (pos < *num_entries)
440     {
441         if (pos >= 0)
442             *num_entries = pos;
443         else
444             *num_entries = 0;
445         *is_partial = 1;
446     }
447
448     *list = glist;
449
450     for (i = 0; i < ord_no; i++)
451         wrbuf_destroy(ar[i].term);
452
453     return ZEBRA_OK;
454 }
455
456 struct scan1_info_entry {
457     char *term;
458     ISAM_P isam_p;
459 };
460
461 struct scan_info {
462     struct scan1_info_entry *list;
463     ODR odr;
464     int before, after;
465     char prefix[20];
466 };
467
468 ZEBRA_RES rpn_scan(ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
469                    const Odr_oid *attributeset,
470                    int num_bases, char **basenames,
471                    int *position, int *num_entries, ZebraScanEntry **list,
472                    int *is_partial, const char *set_name)
473 {
474     int base_no;
475     int ords[RPN_MAX_ORDS], ord_no = 0;
476
477     const char *index_type;
478     char *search_type = NULL;
479     char rank_type[128];
480     int complete_flag;
481     int sort_flag;
482     NMEM nmem;
483     ZEBRA_RES res;
484     struct rset_key_control *kc = 0;
485     RSET limit_set = 0;
486
487     *list = 0;
488     *is_partial = 0;
489
490     if (!attributeset)
491         attributeset = yaz_oid_attset_bib_1;
492
493     if (!set_name)
494     {
495         /* see if there is a @attr 8=set */
496         AttrType termset;
497         int termset_value_numeric;
498         const char *termset_value_string = 0;
499         attr_init_APT(&termset, zapt, 8);
500         termset_value_numeric =
501             attr_find_ex(&termset, NULL, &termset_value_string);
502         if (termset_value_numeric != -1)
503         {
504             if (termset_value_numeric != -2)
505             {
506                 char resname[32];
507                 sprintf(resname, "%d", termset_value_numeric);
508                 set_name = odr_strdup(stream, resname); 
509             }
510             else
511                 set_name = odr_strdup(stream, termset_value_string);
512         }
513     }
514
515     if (set_name)
516     {
517         limit_set = resultSetRef(zh, set_name);
518         
519         if (!limit_set)
520         {
521             zebra_setError(zh, 
522                            YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST,
523                            set_name);
524             return ZEBRA_FAIL;
525         }
526     }
527
528     yaz_log(YLOG_DEBUG, "position = %d, num = %d",
529             *position, *num_entries);
530         
531     if (zebra_maps_attr(zh->reg->zebra_maps, zapt, &index_type, &search_type,
532                         rank_type, &complete_flag, &sort_flag))
533     {
534         *num_entries = 0;
535         zebra_setError(zh, YAZ_BIB1_UNSUPP_ATTRIBUTE_TYPE, 0);
536         return ZEBRA_FAIL;
537     }
538     if (num_bases > RPN_MAX_ORDS)
539     {
540         zebra_setError(zh, YAZ_BIB1_TOO_MANY_DATABASES_SPECIFIED, 0);
541         return ZEBRA_FAIL;
542     }
543     for (base_no = 0; base_no < num_bases; base_no++)
544     {
545         int ord;
546
547         if (zebraExplain_curDatabase(zh->reg->zei, basenames[base_no]))
548         {
549             zebra_setError(zh, YAZ_BIB1_DATABASE_UNAVAILABLE,
550                            basenames[base_no]);
551             *num_entries = 0;
552             return ZEBRA_FAIL;
553         }
554         if (zebra_apt_get_ord(zh, zapt, index_type, 0, attributeset, &ord) 
555             != ZEBRA_OK)
556             continue;
557         ords[ord_no++] = ord;
558     }
559     if (ord_no == 0)
560     {
561         *num_entries = 0; /* zebra_apt_get_ord should set error reason */
562         return ZEBRA_FAIL;
563     }
564     if (*num_entries < 1)
565     {
566         *num_entries = 0;
567         return ZEBRA_OK;
568     }
569     nmem = nmem_create();
570     kc = zebra_key_control_create(zh);
571
572     res = rpn_scan_norm(zh, stream, nmem, kc, zapt, position, num_entries,
573                         list, is_partial, limit_set,
574                         index_type, ord_no, ords);
575     nmem_destroy(nmem);
576     (*kc->dec)(kc);
577     return res;
578 }
579
580 /*
581  * Local variables:
582  * c-basic-offset: 4
583  * c-file-style: "Stroustrup"
584  * indent-tabs-mode: nil
585  * End:
586  * vim: shiftwidth=4 tabstop=8 expandtab
587  */
588