]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Storage/FTS.pm
6dd03c03821b747f237e9cec7701d1a3a4ebf705
[Evergreen.git] / Open-ILS / src / perlmods / OpenILS / Application / Storage / FTS.pm
1 use OpenSRF::Utils::Logger qw/:level/;
2 my $log = 'OpenSRF::Utils::Logger';
3
4 #-------------------------------------------------------------------------------
5 package OpenILS::Application::Storage::FTS;
6 use OpenSRF::Utils::Logger qw/:level/;
7 use Parse::RecDescent;
8 use Unicode::Normalize;
9
10 my $_default_grammar_parser = new Parse::RecDescent ( <<'GRAMMAR' );
11
12 <autotree>
13
14 search_expression: or_expr(s) | and_expr(s) | expr(s)
15 or_expr: lexpr '||' rexpr
16 and_expr: lexpr '&&' rexpr
17 lexpr: expr
18 rexpr: expr
19 expr: phrase(s) | group(s) | word(s)
20 joiner: '||' | '&&'
21 phrase: '"' token(s) '"'
22 group : '(' search_expression ')'
23 word: numeric_range | negative_token | token
24 negative_token: '-' .../\D+/ token
25 token: /[-\w]+/
26 numeric_range: /\d+-\d*/
27
28 GRAMMAR
29
30 sub naco_normalize {
31
32     my $txt = lc(shift);
33     my $sf = shift;
34
35     $txt = NFD($txt);
36     $txt =~ s/\pM+//go; # Remove diacritics
37
38     $txt =~ s/\xE6/AE/go;   # Convert ae digraph
39     $txt =~ s/\x{153}/OE/go;# Convert oe digraph
40     $txt =~ s/\xFE/TH/go;   # Convert Icelandic thorn
41
42     $txt =~ tr/\x{2070}\x{2071}\x{2072}\x{2073}\x{2074}\x{2075}\x{2076}\x{2077}\x{2078}\x{2079}\x{207A}\x{207B}/0123456789+-/;# Convert superscript numbers
43     $txt =~ tr/\x{2080}\x{2081}\x{2082}\x{2083}\x{2084}\x{2085}\x{2086}\x{2087}\x{2088}\x{2089}\x{208A}\x{208B}/0123456889+-/;# Convert subscript numbers
44
45     $txt =~ tr/\x{0251}\x{03B1}\x{03B2}\x{0262}\x{03B3}/AABGG/;     # Convert Latin and Greek
46     $txt =~ tr/\x{2113}\xF0\!\"\(\)\-\{\}\<\>\;\:\.\?\xA1\xBF\/\\\@\*\%\=\xB1\+\xAE\xA9\x{2117}\$\xA3\x{FFE1}\xB0\^\_\~\`/LD /; # Convert Misc
47     $txt =~ tr/\'\[\]\|//d;                         # Remove Misc
48
49     if ($sf && $sf =~ /^a/o) {
50         my $commapos = index($txt,',');
51         if ($commapos > -1) {
52             if ($commapos != length($txt) - 1) {
53                 my @list = split /,/, $txt;
54                 my $first = shift @list;
55                 $txt = $first . ',' . join(' ', @list);
56             } else {
57                 $txt =~ s/,/ /go;
58             }
59         }
60     } else {
61         $txt =~ s/,/ /go;
62     }
63
64     $txt =~ s/\s+/ /go; # Compress multiple spaces
65     $txt =~ s/^\s+//o;  # Remove leading space
66     $txt =~ s/\s+$//o;  # Remove trailing space
67
68     return $txt;
69 }
70
71 #' stupid vim syntax highlighting ...
72
73 sub compile {
74
75         $log->debug("You must override me somewhere, or I will make searching really slow!!!!",ERROR);;
76
77         my $self = shift;
78         my $class = shift;
79         my $term = shift;
80
81         $self = ref($self) || $self;
82         $self = bless {} => $self;
83
84         $self->decompose($term);
85
86         for my $part ( $self->words, $self->phrases ) {
87                 $part = OpenILS::Application::Storage::CDBI->quote($part);
88                 push @{ $self->{ fts_query } },   "'\%$part\%'";
89         }
90
91         for my $part ( $self->nots ) {
92                 $part = OpenILS::Application::Storage::CDBI->quote($part);
93                 push @{ $self->{ fts_query_not } },   "'\%$part\%'";
94         }
95 }
96
97 sub decompose {
98         my $self = shift;
99         my $term = shift;
100         my $parser = shift || $_default_grammar_parser;
101
102         $term =~ s/:/ /go;
103         $term =~ s/\s+--\s+/ /go;
104         $term =~ s/(?:&[^;]+;)//go;
105         $term =~ s/\s+/ /go;
106         $term =~ s/(^|\s+)-(\w+)/$1!$2/go;
107         $term =~ s/\b(\+)(\w+)/$2/go;
108         $term =~ s/^\s*\b(.+)\b\s*$/$1/o;
109         #$term =~ s/^(?:an?|the)\b(.*)/$1/o;
110
111         $log->debug("Stripped search term string is [$term]",DEBUG);
112
113         my $parsetree = $parser->search_expression( $term );
114         my @words = $term =~ /\b((?<!!)\w+)\b/go;
115         my @nots = $term =~ /\b(?<=!)(\w+)\b/go;
116
117         $log->debug("Stripped words are[".join(', ',@words)."]",DEBUG);
118         $log->debug("Stripped nots are[".join(', ',@nots)."]",DEBUG);
119
120         my @parts;
121         while ($term =~ s/ ((?<!\\)"{1}) (.*?) ((?<!\\)"){1} //x) {
122                 my $part = $2;
123                 $part =~ s/^\s*//o;
124                 $part =~ s/\s*$//o;
125                 next unless $part;
126                 push @parts, lc($part);
127         }
128
129         $self->{ fts_op } = 'ILIKE';
130         $self->{ fts_col } = $self->{ text_col } = 'value';
131         $self->{ raw } = $term;
132         $self->{ parsetree } = $parsetree;
133         $self->{ words } = \@words;
134         $self->{ nots } = \@nots;
135         $self->{ phrases } = \@parts;
136
137         return $self;
138 }
139
140 sub fts_query_not {
141         my $self = shift;
142         return wantarray ? @{ $self->{fts_query_not} } : $self->{fts_query_not};
143 }
144
145 sub fts_rank {
146         my $self = shift;
147         return wantarray ? @{ $self->{fts_rank} } : $self->{fts_rank};
148 }
149
150 sub fts_query {
151         my $self = shift;
152         return wantarray ? @{ $self->{fts_query} } : $self->{fts_query};
153 }
154
155 sub raw {
156         my $self = shift;
157         return $self->{raw};
158 }
159
160 sub parse_tree {
161         my $self = shift;
162         return $self->{parsetree};
163 }
164
165 sub fts_col {
166         my $self = shift;
167         return $self->{fts_col};
168 }
169
170 sub text_col {
171         my $self = shift;
172         return $self->{text_col};
173 }
174
175 sub phrases {
176         my $self = shift;
177         return wantarray ? @{ $self->{phrases} } : $self->{phrases};
178 }
179
180 sub words {
181         my $self = shift;
182         return wantarray ? @{ $self->{words} } : $self->{words};
183 }
184
185 sub nots {
186         my $self = shift;
187         return wantarray ? @{ $self->{nots} } : $self->{nots};
188 }
189
190 sub sql_exact_phrase_match {
191         my $self = shift;
192         my $column = $self->text_col;
193         my $output = '';
194         for my $phrase ( $self->phrases ) {
195                 $phrase =~ s/%/\\%/go;
196                 $phrase =~ s/_/\\_/go;
197                 $phrase =~ s/'/\\'/go;
198                 $log->debug("Adding phrase [$phrase] to the match list", DEBUG);
199                 $output .= " AND $column ILIKE '\%$phrase\%'";
200         }
201         $log->debug("Phrase list is [$output]", DEBUG);
202         return $output;
203 }
204
205 sub sql_exact_word_bump {
206         my $self = shift;
207         my $bump = shift || '0.1';
208
209         my $column = $self->text_col;
210         my $output = '';
211         for my $word ( $self->words ) {
212                 $word =~ s/%/\\%/go;
213                 $word =~ s/_/\\_/go;
214                 $word =~ s/'/''/go;
215                 $log->debug("Adding word [$word] to the relevancy bump list", DEBUG);
216                 $output .= " + CASE WHEN $column ILIKE '\%$word\%' THEN $bump ELSE 0 END";
217         }
218         $log->debug("Word bump list is [$output]", DEBUG);
219         return $output;
220 }
221
222 sub sql_where_clause {
223         my $self = shift;
224         my @output;
225
226         for my $fts ( $self->fts_query ) {
227                 push @output, join(' ', $self->fts_col, $self->{fts_op}, $fts);
228         }
229
230         for my $fts ( $self->fts_query_not ) {
231                 push @output, 'NOT (' . join(' ', $self->fts_col, $self->{fts_op}, $fts) . ')';
232         }
233
234         my $phrase_match = $self->sql_exact_phrase_match();
235         return join(' AND ', @output); 
236 }
237
238 #-------------------------------------------------------------------------------
239 use Class::DBI;
240
241 package Class::DBI;
242
243 {
244         no warnings;
245         no strict;
246         sub _do_search {
247                 my ($proto, $search_type, @args) = @_;
248                 my $class = ref $proto || $proto;
249                 
250                 my (@cols, @vals);
251                 my $search_opts = (@args > 1 and ref($args[-1]) eq 'HASH') ? pop @args : {};
252
253                 @args = %{ $args[0] } if ref $args[0] eq "HASH";
254
255                 $search_opts->{offset} = int($search_opts->{page} - 1) * int($search_opts->{page_size})  if ($search_opts->{page_size});
256                 $search_opts->{_placeholder} ||= '?';
257
258                 my @frags;
259                 while (my ($col, $val) = splice @args, 0, 2) {
260                         my $column = $class->find_column($col)
261                                 || (List::Util::first { $_->accessor eq $col } $class->columns)
262                                 || $class->_croak("$col is not a column of $class");
263
264                         if (!defined($val)) {
265                                 push @frags, "$col IS NULL";
266                         } elsif (ref($val) and ref($val) eq 'ARRAY') {
267                                 push @frags, "$col IN (".join(',',map{'?'}@$val).")";
268                                 for my $v (@$val) {
269                                         push @vals, ''.$class->_deflated_column($column, $v);
270                                 }
271                         } else {
272                                 push @frags, "$col $search_type $$search_opts{_placeholder}";
273                                 push @vals, $class->_deflated_column($column, $val);
274                         }
275                 }
276
277                 my $frag = join " AND ", @frags;
278
279                 $frag .= " ORDER BY $search_opts->{order_by}"
280                         if $search_opts->{order_by};
281                 $frag .= " LIMIT $search_opts->{limit}"
282                         if $search_opts->{limit};
283                 $frag .= " OFFSET $search_opts->{offset}"
284                         if ($search_opts->{limit} && defined($search_opts->{offset}));
285
286                 return $class->sth_to_objects($class->sql_Retrieve($frag), \@vals);
287         }
288 }
289
290 1;
291