]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Storage/Driver/Pg/QueryParser.pm
LP#1549505: add flag to tweak popularity-adjusted relevance
[working/Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / Application / Storage / Driver / Pg / QueryParser.pm
1 use strict;
2 use warnings;
3
4 package OpenILS::Application::Storage::Driver::Pg::QueryParser;
5 use OpenILS::Application::Storage::QueryParser;
6 use base 'QueryParser';
7 use OpenSRF::Utils qw/:datetime/;
8 use OpenSRF::Utils::JSON;
9 use OpenILS::Application::AppUtils;
10 use OpenILS::Utils::CStoreEditor;
11 my $U = 'OpenILS::Application::AppUtils';
12
13 my ${spc} = ' ' x 2;
14 sub subquery_callback {
15     my ($invocant, $self, $struct, $filter, $params, $negate) = @_;
16
17     return sprintf(' ((%s)) ',
18         join(
19             ') || (',
20             map {
21                 $_->query_text
22             } @{
23                 OpenILS::Utils::CStoreEditor
24                     ->new
25                     ->search_actor_search_query({ id => $params })
26             }
27         )
28     );
29 }
30
31 sub filter_group_entry_callback {
32     my ($invocant, $self, $struct, $filter, $params, $negate) = @_;
33
34     return sprintf(' saved_query(%s)', 
35         join(
36             ',', 
37             map {
38                 $_->query
39             } @{
40                 OpenILS::Utils::CStoreEditor
41                     ->new
42                     ->search_actor_search_filter_group_entry({ id => $params })
43             }
44         )
45     );
46 }
47
48 sub format_callback {
49     my ($invocant, $self, $struct, $filter, $params, $negate) = @_;
50
51     my $return = '';
52     my $negate_flag = ($negate ? '-' : '');
53     my @returns;
54     for my $param (@$params) {
55         my ($t,$f) = split('-', $param);
56         my $treturn = '';
57         $treturn .= 'item_type(' . join(',',split('', $t)) . ')' if ($t);
58         $treturn .= ' ' if ($t and $f);
59         $treturn .= 'item_form(' . join(',',split('', $f)) . ')' if ($f);
60         $treturn = '(' . $treturn . ')' if ($t and $f);
61         push(@returns, $treturn) if $treturn;
62     }
63     $return = join(' || ', @returns);
64     $return = '(' . $return . ')' if(@returns > 1);
65     $return = $negate_flag.$return if($return);
66     return $return;
67 }
68
69 sub quote_value {
70     my $self = shift;
71     my $value = shift;
72
73     if ($value =~ /^\d/) { # may have to use non-$ quoting
74         $value =~ s/'/''/g;
75         $value =~ s/\\/\\\\/g;
76         return "E'$value'";
77     }
78     return "\$_$$\$$value\$_$$\$";
79 }
80
81 sub quote_phrase_value {
82     my $self = shift;
83     my $value = shift;
84     my $wb = shift;
85
86     my $left_anchored = '';
87     my $right_anchored = '';
88     my $left_wb = 0;
89     my $right_wb = 0;
90
91     $left_anchored  = $1 if $value =~ m/^([*\^])/;
92     $right_anchored = $1 if $value =~ m/([*\$])$/;
93
94     # We can't use word-boundary bracket expressions if the relevant char
95     # is not actually a "word" characters.
96     $left_wb  = $wb if $value =~ m/^\w+/;
97     $right_wb = $wb if $value =~ m/\w+$/;
98
99     $value =~ s/^[*\^]//   if $left_anchored;
100     $value =~ s/[*\$]$//  if $right_anchored;
101     $value = quotemeta($value);
102     $value = '^' . $value if $left_anchored eq '^';
103     $value = "$value\$"   if $right_anchored eq '$';
104     $value = '[[:<:]]' . $value if $left_wb && !$left_anchored;
105     $value .= '[[:>:]]' if $right_wb && !$right_anchored;
106     return $self->quote_value($value);
107 }
108
109 sub init {
110     my $class = shift;
111 }
112
113 sub default_preferred_language {
114     my $self = shift;
115     my $lang = shift;
116
117     $self->custom_data->{default_preferred_language} = $lang if ($lang);
118     return $self->custom_data->{default_preferred_language};
119 }
120
121 sub default_preferred_language_multiplier {
122     my $self = shift;
123     my $lang = shift;
124
125     $self->custom_data->{default_preferred_language_multiplier} = $lang if ($lang);
126     return $self->custom_data->{default_preferred_language_multiplier};
127 }
128
129 sub max_popularity_importance_multiplier {
130     my $self = shift;
131     my $max = shift;
132
133     $self->custom_data->{max_popularity_importance_multiplier} = $max if defined($max);
134     return $self->custom_data->{max_popularity_importance_multiplier};
135 }
136
137 sub simple_plan {
138     my $self = shift;
139
140     return 0 unless $self->parse_tree;
141     return 0 if @{$self->parse_tree->filters};
142     return 0 if @{$self->parse_tree->modifiers};
143     for my $node ( @{ $self->parse_tree->query_nodes } ) {
144         return 0 if (!ref($node) && $node eq '|');
145         next unless (ref($node));
146         return 0 if ($node->isa('QueryParser::query_plan'));
147     }
148
149     return 1;
150 }
151
152 sub toSQL {
153     my $self = shift;
154     return $self->parse_tree->toSQL;
155 }
156
157 sub dynamic_filters {
158     my $self = shift;
159     my $new = shift;
160
161     $self->custom_data->{dynamic_filters} ||= [];
162     push(@{$self->custom_data->{dynamic_filters}}, $new) if ($new);
163     return $self->custom_data->{dynamic_filters};
164 }
165
166 sub dynamic_sorters {
167     my $self = shift;
168     my $new = shift;
169
170     $self->custom_data->{dynamic_sorters} ||= [];
171     push(@{$self->custom_data->{dynamic_sorters}}, $new) if ($new);
172     return $self->custom_data->{dynamic_sorters};
173 }
174
175 sub facet_field_id_map {
176     my $self = shift;
177     my $map = shift;
178
179     $self->custom_data->{facet_field_id_map} ||= {};
180     $self->custom_data->{facet_field_id_map} = $map if ($map);
181     return $self->custom_data->{facet_field_id_map};
182 }
183
184 sub add_facet_field_id_map {
185     my $self = shift;
186     my $class = shift;
187     my $field = shift;
188     my $id = shift;
189     my $weight = shift;
190
191     $self->add_facet_field( $class => $field );
192     $self->facet_field_id_map->{by_id}{$id} = { classname => $class, field => $field, weight => $weight };
193     $self->facet_field_id_map->{by_class}{$class}{$field} = $id;
194
195     return {
196         by_id => { $id => { classname => $class, field => $field, weight => $weight } },
197         by_class => { $class => { $field => $id } }
198     };
199 }
200
201 sub facet_field_class_by_id {
202     my $self = shift;
203     my $id = shift;
204
205     return $self->facet_field_id_map->{by_id}{$id};
206 }
207
208 sub facet_field_ids_by_class {
209     my $self = shift;
210     my $class = shift;
211     my $field = shift;
212
213     return undef unless ($class);
214
215     if ($field) {
216         return [$self->facet_field_id_map->{by_class}{$class}{$field}];
217     }
218
219     return [values( %{ $self->facet_field_id_map->{by_class}{$class} } )];
220 }
221
222 sub search_field_id_map {
223     my $self = shift;
224     my $map = shift;
225
226     $self->custom_data->{search_field_id_map} ||= {};
227     $self->custom_data->{search_field_id_map} = $map if ($map);
228     return $self->custom_data->{search_field_id_map};
229 }
230
231 sub add_search_field_id_map {
232     my $self = shift;
233     my $class = shift;
234     my $field = shift;
235     my $id = shift;
236     my $weight = shift;
237     my $combined = shift;
238
239     $self->add_search_field( $class => $field );
240     $self->search_field_id_map->{by_id}{$id} = { classname => $class, field => $field, weight => $weight };
241     $self->search_field_id_map->{by_class}{$class}{$field} = $id;
242
243     return {
244         by_id => { $id => { classname => $class, field => $field, weight => $weight } },
245         by_class => { $class => { $field => $id } }
246     };
247 }
248
249 sub search_field_class_by_id {
250     my $self = shift;
251     my $id = shift;
252
253     return $self->search_field_id_map->{by_id}{$id};
254 }
255
256 sub search_field_ids_by_class {
257     my $self = shift;
258     my $class = shift;
259     my $field = shift;
260
261     return undef unless ($class);
262
263     if ($field) {
264         return [$self->search_field_id_map->{by_class}{$class}{$field}];
265     }
266
267     return [values( %{ $self->search_field_id_map->{by_class}{$class} } )];
268 }
269
270 sub relevance_bumps {
271     my $self = shift;
272     my $bumps = shift;
273
274     $self->custom_data->{rel_bumps} ||= {};
275     $self->custom_data->{rel_bumps} = $bumps if ($bumps);
276     return $self->custom_data->{rel_bumps};
277 }
278
279 sub find_relevance_bumps {
280     my $self = shift;
281     my $class = shift;
282     my $field = shift;
283
284     return $self->relevance_bumps->{$class}{$field};
285 }
286
287 sub add_relevance_bump {
288     my $self = shift;
289     my $class = shift;
290     my $field = shift;
291     my $type = shift;
292     my $multiplier = shift;
293     my $active = shift;
294
295     if (defined($active) and $active eq 'f') {
296         $active = 0;
297     } else {
298         $active = 1;
299     }
300
301     $self->relevance_bumps->{$class}{$field}{$type} = { multiplier => $multiplier, active => $active };
302
303     return { $class => { $field => { $type => { multiplier => $multiplier, active => $active } } } };
304 }
305
306 sub search_class_weights {
307     my $self = shift;
308     my $class = shift;
309     my $a_weight = shift;
310     my $b_weight = shift;
311     my $c_weight = shift;
312     my $d_weight = shift;
313
314     $self->custom_data->{class_weights} ||= {};
315     # Note: This reverses the A-D order, putting D first, because that is how the call actually works in PG
316     $self->custom_data->{class_weights}->{$class} ||= [0.1, 0.2, 0.4, 1.0];
317     $self->custom_data->{class_weights}->{$class} = [$d_weight, $c_weight, $b_weight, $a_weight] if $a_weight;
318     return $self->custom_data->{class_weights}->{$class};
319 }
320
321 sub search_class_combined {
322     my $self = shift;
323     my $class = shift;
324     my $c = shift;
325
326     $self->custom_data->{class_combined} ||= {};
327     # Note: This reverses the A-D order, putting D first, because that is how the call actually works in PG
328     $self->custom_data->{class_combined}->{$class} ||= 0;
329     $self->custom_data->{class_combined}->{$class} = 1 if $c && $c =~ /^(?:t|y|1)/i;
330     return $self->custom_data->{class_combined}->{$class};
331 }
332
333 sub class_ts_config {
334     my $self = shift;
335     my $class = shift;
336     my $lang = shift || 'DEFAULT';
337     my $always = shift;
338     my $ts_config = shift;
339
340     $self->custom_data->{class_ts_config} ||= {};
341     $self->custom_data->{class_ts_config}->{$class} ||= {};
342     $self->custom_data->{class_ts_config}->{$class}->{$lang} ||= {};
343     $self->custom_data->{class_ts_config}->{$class}->{$lang}->{normal} ||= [];
344     $self->custom_data->{class_ts_config}->{$class}->{$lang}->{always} ||= [];
345     $self->custom_data->{class_ts_config}->{$class}->{'DEFAULT'} ||= {};
346     $self->custom_data->{class_ts_config}->{$class}->{'DEFAULT'}->{normal} ||= [];
347     $self->custom_data->{class_ts_config}->{$class}->{'DEFAULT'}->{always} ||= [];
348
349     if ($ts_config) {
350         push @{$self->custom_data->{class_ts_config}->{$class}->{$lang}->{normal}}, $ts_config unless $always;
351         push @{$self->custom_data->{class_ts_config}->{$class}->{$lang}->{always}}, $ts_config if $always;
352     }
353
354     my $return = [];
355     push @$return, @{$self->custom_data->{class_ts_config}->{$class}->{$lang}->{always}};
356     push @$return, @{$self->custom_data->{class_ts_config}->{$class}->{$lang}->{normal}} unless $always;
357     if($lang ne 'DEFAULT') {
358         push @$return, @{$self->custom_data->{class_ts_config}->{$class}->{'DEFAULT'}->{always}};
359         push @$return, @{$self->custom_data->{class_ts_config}->{$class}->{'DEFAULT'}->{normal}} unless $always;
360     }
361     return $return;
362 }
363
364 sub field_ts_config {
365     my $self = shift;
366     my $class = shift;
367     my $field = shift;
368     my $lang = shift || 'DEFAULT';
369     my $ts_config = shift;
370
371     $self->custom_data->{field_ts_config} ||= {};
372     $self->custom_data->{field_ts_config}->{$class} ||= {};
373     $self->custom_data->{field_ts_config}->{$class}->{$field} ||= {};
374     $self->custom_data->{field_ts_config}->{$class}->{$field}->{$lang} ||= [];
375     $self->custom_data->{field_ts_config}->{$class}->{$field}->{'DEFAULT'} ||= [];
376
377     if ($ts_config) {
378         push @{$self->custom_data->{field_ts_config}->{$class}->{$field}->{$lang}}, $ts_config;
379     }
380
381     my $return = [];
382     push @$return, @{$self->custom_data->{field_ts_config}->{$class}->{$field}->{$lang}};
383     if($lang ne 'DEFAULT') {
384         push @$return, @{$self->custom_data->{field_ts_config}->{$class}->{$field}->{'DEFAULT'}};
385     }
386     # Make it easy on us: Grab any "always" for the class here. If we have none we grab them all.
387     push @$return, @{$self->class_ts_config($class, $lang, scalar(@$return))};
388     return $return;
389 }
390
391 sub initialize_search_field_id_map {
392     my $self = shift;
393     my $cmf_list = shift;
394
395     for my $cmf (@$cmf_list) {
396         __PACKAGE__->add_search_field_id_map( $cmf->field_class, $cmf->name, $cmf->id, $cmf->weight ) if ($U->is_true($cmf->search_field));
397         __PACKAGE__->add_facet_field_id_map( $cmf->field_class, $cmf->name, $cmf->id, $cmf->weight ) if ($U->is_true($cmf->facet_field));
398     }
399
400     return $self->search_field_id_map;
401 }
402
403 sub initialize_aliases {
404     my $self = shift;
405     my $cmsa_list = shift;
406
407     for my $cmsa (@$cmsa_list) {
408         if (!$cmsa->field) {
409             __PACKAGE__->add_search_class_alias( $cmsa->field_class, $cmsa->alias );
410         } else {
411             my $c = $self->search_field_class_by_id( $cmsa->field );
412             __PACKAGE__->add_search_field_alias( $cmsa->field_class, $c->{field}, $cmsa->alias );
413         }
414     }
415 }
416
417 sub initialize_relevance_bumps {
418     my $self = shift;
419     my $sra_list = shift;
420
421     for my $sra (@$sra_list) {
422         my $c = $self->search_field_class_by_id( $sra->field );
423         __PACKAGE__->add_relevance_bump( $c->{classname}, $c->{field}, $sra->bump_type, $sra->multiplier, $sra->active );
424     }
425
426     return $self->relevance_bumps;
427 }
428
429 sub initialize_query_normalizers {
430     my $self = shift;
431     my $tree = shift; # open-ils.cstore.direct.config.metabib_field_index_norm_map.search.atomic { "id" : { "!=" : null } }, { "flesh" : 1, "flesh_fields" : { "cmfinm" : ["norm"] }, "order_by" : [{ "class" : "cmfinm", "field" : "pos" }] }
432
433     for my $cmfinm ( @$tree ) {
434         my $field_info = $self->search_field_class_by_id( $cmfinm->field );
435         next unless $field_info;
436         __PACKAGE__->add_query_normalizer( $field_info->{classname}, $field_info->{field}, $cmfinm->norm->func, OpenSRF::Utils::JSON->JSON2perl($cmfinm->params) );
437     }
438 }
439
440 sub initialize_dynamic_filters {
441     my $self = shift;
442     my $list = shift; # open-ils.cstore.direct.config.record_attr_definition.search.atomic { "id" : { "!=" : null } }
443
444     for my $crad ( @$list ) {
445         __PACKAGE__->dynamic_filters( __PACKAGE__->add_search_filter( $crad->name ) ) if ($U->is_true($crad->filter));
446         __PACKAGE__->dynamic_sorters( $crad->name ) if ($U->is_true($crad->sorter));
447     }
448 }
449
450 sub initialize_filter_normalizers {
451     my $self = shift;
452     my $tree = shift; # open-ils.cstore.direct.config.record_attr_index_norm_map.search.atomic { "id" : { "!=" : null } }, { "flesh" : 1, "flesh_fields" : { "crainm" : ["norm"] }, "order_by" : [{ "class" : "crainm", "field" : "pos" }] }
453
454     for my $crainm ( @$tree ) {
455         __PACKAGE__->add_filter_normalizer( $crainm->attr, $crainm->norm->func, OpenSRF::Utils::JSON->JSON2perl($crainm->params) );
456     }
457 }
458
459 sub initialize_search_class_weights {
460     my $self = shift;
461     my $classes = shift;
462
463     for my $search_class (@$classes) {
464         __PACKAGE__->search_class_weights( $search_class->name, $search_class->a_weight, $search_class->b_weight, $search_class->c_weight, $search_class->d_weight );
465         __PACKAGE__->search_class_combined( $search_class->name, $search_class->combined );
466     }
467 }
468
469 sub initialize_class_ts_config {
470     my $self = shift;
471     my $class_entries = shift;
472
473     for my $search_class_entry (@$class_entries) {
474         __PACKAGE__->class_ts_config($search_class_entry->field_class,$search_class_entry->search_lang,$U->is_true($search_class_entry->always),$search_class_entry->ts_config);
475     }
476 }
477
478 sub initialize_field_ts_config {
479     my $self = shift;
480     my $field_entries = shift;
481     my $field_objects = shift;
482     my %field_hash = map { $_->id => $_ } @$field_objects;
483
484     for my $search_field_entry (@$field_entries) {
485         my $field_object = $field_hash{$search_field_entry->metabib_field};
486         __PACKAGE__->field_ts_config($field_object->field_class,$field_object->name,$search_field_entry->search_lang,$search_field_entry->ts_config);
487     }
488 }
489
490 our $_complete = 0;
491 sub initialization_complete {
492     return $_complete;
493 }
494
495 sub initialize {
496     my $self = shift;
497     my %args = @_;
498
499     return $_complete if ($_complete);
500
501     # tsearch rank normalization adjustments. see http://www.postgresql.org/docs/9.0/interactive/textsearch-controls.html#TEXTSEARCH-RANKING for details
502     $self->custom_data->{rank_cd_weight_map} = {
503         CD_logDocumentLength    => 1,
504         CD_documentLength       => 2,
505         CD_meanHarmonic         => 4,
506         CD_uniqueWords          => 8,
507         CD_logUniqueWords       => 16,
508         CD_selfPlusOne          => 32
509     };
510
511     $self->add_search_modifier( $_ ) for (keys %{ $self->custom_data->{rank_cd_weight_map} });
512
513     $self->initialize_search_field_id_map( $args{config_metabib_field} )
514         if ($args{config_metabib_field});
515
516     $self->initialize_aliases( $args{config_metabib_search_alias} )
517         if ($args{config_metabib_search_alias});
518
519     $self->initialize_relevance_bumps( $args{search_relevance_adjustment} )
520         if ($args{search_relevance_adjustment});
521
522     $self->initialize_query_normalizers( $args{config_metabib_field_index_norm_map} )
523         if ($args{config_metabib_field_index_norm_map});
524
525     $self->initialize_dynamic_filters( $args{config_record_attr_definition} )
526         if ($args{config_record_attr_definition});
527
528     $self->initialize_filter_normalizers( $args{config_record_attr_index_norm_map} )
529         if ($args{config_record_attr_index_norm_map});
530
531     $self->initialize_search_class_weights( $args{config_metabib_class} )
532         if ($args{config_metabib_class});
533
534     $self->initialize_class_ts_config( $args{config_metabib_class_ts_map} )
535         if ($args{config_metabib_class_ts_map});
536
537     $self->initialize_field_ts_config( $args{config_metabib_field_ts_map}, $args{config_metabib_field} )
538         if ($args{config_metabib_field_ts_map} && $args{config_metabib_field});
539
540     $_complete = 1 if (
541         $args{config_metabib_field_index_norm_map} &&
542         $args{search_relevance_adjustment} &&
543         $args{config_metabib_search_alias} &&
544         $args{config_metabib_field} &&
545         $args{config_record_attr_definition}
546     );
547
548     return $_complete;
549 }
550
551 sub TEST_SETUP {
552     
553     __PACKAGE__->allow_nested_modifiers(1);
554
555     __PACKAGE__->add_search_field_id_map( series => seriestitle => 1 => 1 );
556
557     __PACKAGE__->add_search_field_id_map( series => seriestitle => 1 => 1 );
558     __PACKAGE__->add_relevance_bump( series => seriestitle => first_word => 1.5 );
559     __PACKAGE__->add_relevance_bump( series => seriestitle => full_match => 20 );
560     
561     __PACKAGE__->add_search_field_id_map( title => abbreviated => 2 => 1 );
562     __PACKAGE__->add_relevance_bump( title => abbreviated => first_word => 1.5 );
563     __PACKAGE__->add_relevance_bump( title => abbreviated => full_match => 20 );
564     
565     __PACKAGE__->add_search_field_id_map( title => translated => 3 => 1 );
566     __PACKAGE__->add_relevance_bump( title => translated => first_word => 1.5 );
567     __PACKAGE__->add_relevance_bump( title => translated => full_match => 20 );
568     
569     __PACKAGE__->add_search_field_id_map( title => proper => 6 => 1 );
570     __PACKAGE__->add_query_normalizer( title => proper => 'search_normalize' );
571     __PACKAGE__->add_relevance_bump( title => proper => first_word => 1.5 );
572     __PACKAGE__->add_relevance_bump( title => proper => full_match => 20 );
573     __PACKAGE__->add_relevance_bump( title => proper => word_order => 10 );
574     
575     __PACKAGE__->add_search_field_id_map( author => corporate => 7 => 1 );
576     __PACKAGE__->add_relevance_bump( author => corporate => first_word => 1.5 );
577     __PACKAGE__->add_relevance_bump( author => corporate => full_match => 20 );
578     
579     __PACKAGE__->add_facet_field_id_map( author => personal => 8 => 1 );
580
581     __PACKAGE__->add_search_field_id_map( author => personal => 8 => 1 );
582     __PACKAGE__->add_relevance_bump( author => personal => first_word => 1.5 );
583     __PACKAGE__->add_relevance_bump( author => personal => full_match => 20 );
584     __PACKAGE__->add_query_normalizer( author => personal => 'search_normalize' );
585     __PACKAGE__->add_query_normalizer( author => personal => 'split_date_range' );
586     
587     __PACKAGE__->add_facet_field_id_map( subject => topic => 14 => 1 );
588
589     __PACKAGE__->add_search_field_id_map( subject => topic => 14 => 1 );
590     __PACKAGE__->add_relevance_bump( subject => topic => first_word => 1 );
591     __PACKAGE__->add_relevance_bump( subject => topic => full_match => 1 );
592     
593     __PACKAGE__->add_search_field_id_map( subject => complete => 16 => 1 );
594     __PACKAGE__->add_relevance_bump( subject => complete => first_word => 1 );
595     __PACKAGE__->add_relevance_bump( subject => complete => full_match => 1 );
596     
597     __PACKAGE__->add_search_field_id_map( keyword => keyword => 15 => 1 );
598     __PACKAGE__->add_relevance_bump( keyword => keyword => first_word => 1 );
599     __PACKAGE__->add_relevance_bump( keyword => keyword => full_match => 1 );
600     
601     __PACKAGE__->class_ts_config( 'series', undef, 1, 'english_nostop' );
602     __PACKAGE__->class_ts_config( 'title', undef, 1, 'english_nostop' );
603     __PACKAGE__->class_ts_config( 'author', undef, 1, 'english_nostop' );
604     __PACKAGE__->class_ts_config( 'subject', undef, 1, 'english_nostop' );
605     __PACKAGE__->class_ts_config( 'keyword', undef, 1, 'english_nostop' );
606     __PACKAGE__->class_ts_config( 'series', undef, 1, 'simple' );
607     __PACKAGE__->class_ts_config( 'title', undef, 1, 'simple' );
608     __PACKAGE__->class_ts_config( 'author', undef, 1, 'simple' );
609     __PACKAGE__->class_ts_config( 'subject', undef, 1, 'simple' );
610     __PACKAGE__->class_ts_config( 'keyword', undef, 1, 'simple' );
611
612     # French! To test language limiters
613     __PACKAGE__->class_ts_config( 'series', 'fre', 1, 'french_nostop' );
614     __PACKAGE__->class_ts_config( 'title', 'fre', 1, 'french_nostop' );
615     __PACKAGE__->class_ts_config( 'author', 'fre', 1, 'french_nostop' );
616     __PACKAGE__->class_ts_config( 'subject', 'fre', 1, 'french_nostop' );
617     __PACKAGE__->class_ts_config( 'keyword', 'fre', 1, 'french_nostop' );
618
619     # Not a default config by any means, but good for some testing
620     __PACKAGE__->field_ts_config( 'author', 'personal', 'eng', 'english' );
621     __PACKAGE__->field_ts_config( 'author', 'personal', 'fre', 'french' );
622     
623     __PACKAGE__->add_search_class_alias( keyword => 'kw' );
624     __PACKAGE__->add_search_class_alias( title => 'ti' );
625     __PACKAGE__->add_search_class_alias( author => 'au' );
626     __PACKAGE__->add_search_class_alias( author => 'name' );
627     __PACKAGE__->add_search_class_alias( author => 'dc.contributor' );
628     __PACKAGE__->add_search_class_alias( subject => 'su' );
629     __PACKAGE__->add_search_class_alias( subject => 'bib.subject(?:Title|Place|Occupation)' );
630     __PACKAGE__->add_search_class_alias( series => 'se' );
631     __PACKAGE__->add_search_class_alias( keyword => 'dc.identifier' );
632     
633     __PACKAGE__->add_query_normalizer( author => corporate => 'search_normalize' );
634     __PACKAGE__->add_query_normalizer( keyword => keyword => 'search_normalize' );
635     
636     __PACKAGE__->add_search_field_alias( subject => name => 'bib.subjectName' );
637     
638 }
639
640 __PACKAGE__->default_search_class( 'keyword' );
641
642 # implements EG-specific stored subqueries
643 __PACKAGE__->add_search_filter( 'saved_query', sub { return __PACKAGE__->subquery_callback(@_) } );
644 __PACKAGE__->add_search_filter( 'filter_group_entry', sub { return __PACKAGE__->filter_group_entry_callback(@_) } );
645
646 # will be retained simply for back-compat
647 __PACKAGE__->add_search_filter( 'format', sub { return __PACKAGE__->format_callback(@_) } );
648
649 # grumble grumble, special cases against date1 and date2
650 __PACKAGE__->add_search_filter( 'before' );
651 __PACKAGE__->add_search_filter( 'after' );
652 __PACKAGE__->add_search_filter( 'between' );
653 __PACKAGE__->add_search_filter( 'during' );
654
655 # various filters for limiting in various ways
656 __PACKAGE__->add_search_filter( 'edit_date' );
657 __PACKAGE__->add_search_filter( 'create_date' );
658 __PACKAGE__->add_search_filter( 'statuses' );
659 __PACKAGE__->add_search_filter( 'locations' );
660 __PACKAGE__->add_search_filter( 'location_groups' );
661 __PACKAGE__->add_search_filter( 'bib_source' );
662 __PACKAGE__->add_search_filter( 'badge_orgs' );
663 __PACKAGE__->add_search_filter( 'badges' );
664 __PACKAGE__->add_search_filter( 'site' );
665 __PACKAGE__->add_search_filter( 'pref_ou' );
666 __PACKAGE__->add_search_filter( 'lasso' );
667 __PACKAGE__->add_search_filter( 'my_lasso' );
668 __PACKAGE__->add_search_filter( 'depth' );
669 __PACKAGE__->add_search_filter( 'language' );
670 __PACKAGE__->add_search_filter( 'offset' );
671 __PACKAGE__->add_search_filter( 'limit' );
672 __PACKAGE__->add_search_filter( 'check_limit' );
673 __PACKAGE__->add_search_filter( 'skip_check' );
674 __PACKAGE__->add_search_filter( 'superpage' );
675 __PACKAGE__->add_search_filter( 'superpage_size' );
676 __PACKAGE__->add_search_filter( 'estimation_strategy' );
677 __PACKAGE__->add_search_modifier( 'available' );
678 __PACKAGE__->add_search_modifier( 'staff' );
679 __PACKAGE__->add_search_modifier( 'deleted' );
680 __PACKAGE__->add_search_modifier( 'lucky' );
681
682 # Start from container data (bre, acn, acp): container(bre,bookbag,123,deadb33fdeadb33fdeadb33fdeadb33f)
683 __PACKAGE__->add_search_filter( 'container' );
684
685 # Start from a list of record ids, either bre or metarecords, depending on the #metabib modifier
686 __PACKAGE__->add_search_filter( 'record_list' );
687
688 __PACKAGE__->add_search_filter( 'has_browse_entry' );
689
690 # used internally, but generally not user-settable
691 __PACKAGE__->add_search_filter( 'preferred_language' );
692 __PACKAGE__->add_search_filter( 'preferred_language_weight' );
693 __PACKAGE__->add_search_filter( 'preferred_language_multiplier' );
694 __PACKAGE__->add_search_filter( 'core_limit' );
695
696 # XXX Valid values to be supplied by SVF
697 __PACKAGE__->add_search_filter( 'sort' );
698
699 # modifies core query, not configurable
700 __PACKAGE__->add_search_modifier( 'descending' );
701 __PACKAGE__->add_search_modifier( 'ascending' );
702 __PACKAGE__->add_search_modifier( 'nullsfirst' );
703 __PACKAGE__->add_search_modifier( 'nullslast' );
704 __PACKAGE__->add_search_modifier( 'metarecord' );
705 __PACKAGE__->add_search_modifier( 'metabib' );
706
707
708 #-------------------------------
709 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan;
710 use base 'QueryParser::query_plan';
711 use OpenSRF::Utils::Logger qw($logger);
712 use OpenSRF::Utils qw/:datetime/;
713 use Data::Dumper;
714 use OpenILS::Application::AppUtils;
715 my $apputils = "OpenILS::Application::AppUtils";
716
717 our %_dfilter_controlled_cache = ();
718 our %_dfilter_stats_cache = ();
719 our $_pg_version = 0;
720
721 sub dynamic_filter_compile {
722     my ($self, $filter, $params, $negate) = @_;
723     my $e = OpenILS::Utils::CStoreEditor->new;
724
725     $negate = $negate ? '!' : '';
726
727     if (!$_pg_version) {
728         ($_pg_version = $e->json_query({from => ['version']})->[0]->{version}) =~ s/^.+?(\d\.\d).+$/$1/;
729     }
730
731     my $common = 0;
732     if ($_pg_version >= 9.2) {
733         if (!scalar keys %_dfilter_stats_cache) {
734             my $data = $e->json_query({from => ['evergreen.pg_statistics', 'record_attr_vector_list', 'vlist']});
735             %_dfilter_stats_cache = map {
736                 ( $_->{element}, $_->{frequency} )
737             } grep { $_->{frequency} > 5 } @$data; # Pin floor to 5% of the table
738         }
739     } else {
740         $common = 1; # Assume it's expensive
741     }
742
743     if (!exists($_dfilter_controlled_cache{$filter})) {
744         my $crad = $e->retrieve_config_record_attr_definition($filter);
745         my $ccvm_list = $e->search_config_coded_value_map({ctype =>$filter});
746
747         $_dfilter_controlled_cache{$filter} = $crad->to_bare_hash;
748         $_dfilter_controlled_cache{$filter}{controlled} = scalar @$ccvm_list;
749     }
750
751     my $method = $_dfilter_controlled_cache{$filter}{controlled} ?
752         'search_config_coded_value_map' : 'search_metabib_uncontrolled_record_attr_value';
753     my $attr_field = $_dfilter_controlled_cache{$filter}{controlled} ?
754         'ctype' : 'attr';
755     my $value_field = $_dfilter_controlled_cache{$filter}{controlled} ?
756         'code' : 'value';
757
758     my $attr_objects = $e->$method({ $attr_field => $filter, $value_field => $params });
759     $common = scalar(grep { exists($_dfilter_stats_cache{$_->id}) } @$attr_objects) unless $common;
760     
761     return (sprintf('%s(%s)', $negate,
762         join(
763             '|', 
764             map { $_->id } @$attr_objects
765         )
766     ), $common);
767 }
768
769 sub toSQL {
770     my $self = shift;
771
772     my %filters;
773
774     for my $f ( qw/preferred_language preferred_language_multiplier preferred_language_weight core_limit check_limit skip_check superpage superpage_size/ ) {
775         my $col = $f;
776         $col = 'preferred_language_multiplier' if ($f eq 'preferred_language_weight');
777         my ($filter) = $self->find_filter($f);
778         if ($filter and @{$filter->args}) {
779             $filters{$col} = $filter->args->[0];
780         }
781     }
782
783     $self->QueryParser->superpage($filters{superpage}) if ($filters{superpage});
784     $self->QueryParser->superpage_size($filters{superpage_size}) if ($filters{superpage_size});
785     $self->QueryParser->core_limit($filters{core_limit}) if ($filters{core_limit});
786
787     $logger->debug("Query plan:\n".Dumper($self));
788
789     my $flat_plan = $self->flatten;
790
791     # generate the relevance ranking
792     my $rel = '1'; # Default to something simple in case rank_list is empty.
793     if (@{$$flat_plan{rank_list}}) {
794         $rel = "AVG(\n"
795              . ${spc} x 5 ."("
796              . join(")\n" . ${spc} x 5 . "+ (", @{$$flat_plan{rank_list}})
797              . ")\n"
798              . ${spc} x 4 . ")+1";
799     }
800
801     # find any supplied sort option
802     my ($sort_filter) = $self->find_filter('sort');
803     if ($sort_filter) {
804         $sort_filter = $sort_filter->args->[0];
805     } else {
806         $sort_filter = 'rel';
807     }
808
809     my $lang_join = '';
810     if (($filters{preferred_language} || $self->QueryParser->default_preferred_language) && ($filters{preferred_language_multiplier} || $self->QueryParser->default_preferred_language_multiplier)) {
811     
812         my $pl = $self->QueryParser->quote_value( $filters{preferred_language} ? $filters{preferred_language} : $self->QueryParser->default_preferred_language );
813         $$flat_plan{with} .= ',' if $$flat_plan{with};
814         $$flat_plan{with} .= "lang_with AS (SELECT id FROM config.coded_value_map WHERE ctype = 'item_lang' AND code = $pl)";
815         $lang_join = ",lang_with";
816
817         my $plw = $filters{preferred_language_multiplier} ? $filters{preferred_language_multiplier} : $self->QueryParser->default_preferred_language_multiplier;
818         $rel = "($rel * COALESCE( NULLIF( FIRST(mrv.vlist \@> ARRAY[lang_with.id]), FALSE )::INT * $plw, 1))";
819         $$flat_plan{uses_mrv} = 1;
820     }
821
822     my $mrv_join = '';
823     if ($$flat_plan{uses_mrv}) {
824         $mrv_join = 'INNER JOIN metabib.record_attr_vector_list mrv ON m.source = mrv.source';
825     }
826
827     my $mra_join = '';
828     if ($$flat_plan{uses_mrd}) {
829         $mra_join = 'INNER JOIN metabib.record_attr mrd ON m.source = mrd.id';
830     }
831
832     my $pubdate_join = "LEFT JOIN metabib.record_sorter pubdate_t ON m.source = pubdate_t.source AND attr = 'pubdate'";
833
834     my $bre_join = '';
835     if ($self->find_modifier('deleted')) {
836         $bre_join = 'INNER JOIN biblio.record_entry bre ON m.source = bre.id AND bre.deleted';
837         # The above suffices for filters too when the #deleted modifier
838         # is in use.
839     } elsif ($$flat_plan{uses_bre}) {
840         $bre_join = 'INNER JOIN biblio.record_entry bre ON m.source = bre.id';
841     }
842     
843     my $desc = 'ASC';
844     $desc = 'DESC' if ($self->find_modifier('descending'));
845
846     my $nullpos = 'NULLS LAST';
847     $nullpos = 'NULLS FIRST' if ($self->find_modifier('nullsfirst'));
848
849     # Do we have a badges() filter?
850     my $badges = '';
851     my ($badge_filter) = $self->find_filter('badges');
852     if ($badge_filter && @{$badge_filter->args}) {
853         $badges = join (',', grep /^\d+$/, @{$badge_filter->args});
854     }
855
856     # Do we have a badge_orgs() filter? (used for calculating popularity)
857     my $borgs = '';
858     my ($bo_filter) = $self->find_filter('badge_orgs');
859     if ($bo_filter && @{$bo_filter->args}) {
860         $borgs = join (',', grep /^\d+$/, @{$bo_filter->args});
861     }
862
863     # Build the badge-ish WITH query
864     my $pop_with = <<'    WITH';
865         pop_with AS (
866             SELECT  record,
867                     ARRAY_AGG(badge) AS badges,
868                     SUM(s.score::NUMERIC*b.weight::NUMERIC)/SUM(b.weight::NUMERIC) AS total_score
869               FROM  rating.record_badge_score s
870                     JOIN rating.badge b ON (
871                         b.id = s.badge
872     WITH
873
874     $pop_with .= " AND b.id = ANY ('{$badges}')" if ($badges);
875     $pop_with .= " AND b.scope = ANY ('{$borgs}')" if ($borgs);
876     $pop_with .= ') GROUP BY 1)'; 
877
878     my $pop_join = $badges ? # inner join if we are restricting via badges()
879         'INNER JOIN pop_with ON ( m.source = pop_with.record )' : 
880         'LEFT JOIN pop_with ON ( m.source = pop_with.record )';
881
882     $$flat_plan{with} .= ',' if $$flat_plan{with};
883     $$flat_plan{with} .= $pop_with;
884
885
886     my $rank;
887     my $pop_extra_sort = '';
888     if (grep {$_ eq $sort_filter} @{$self->QueryParser->dynamic_sorters}) {
889         $rank = "FIRST((SELECT value FROM metabib.record_sorter rbr WHERE rbr.source = m.source and attr = '$sort_filter'))"
890     } elsif ($sort_filter eq 'create_date') {
891         $rank = "FIRST((SELECT create_date FROM biblio.record_entry rbr WHERE rbr.id = m.source))";
892     } elsif ($sort_filter eq 'edit_date') {
893         $rank = "FIRST((SELECT edit_date FROM biblio.record_entry rbr WHERE rbr.id = m.source))";
894     } elsif ($sort_filter eq 'poprel') {
895         my $max_mult = $self->QueryParser->max_popularity_importance_multiplier() // 2.0;
896         $max_mult = 0.1 if $max_mult < 0.1; # keep it within reasonable bounds,
897                                             # and avoid the division-by-zero error
898                                             # you'd get if you allowed it to be
899                                             # zero
900
901         if ( $max_mult == 1.0 ) { # no adjustment requested by the configuration
902             $rank = "1.0/($rel)::NUMERIC";
903         } else { # calculate adjustment
904
905             # Scale the 0-5 effect of popularity badges by providing a multiplier
906             # for the badge average based on the overall maximum
907             # multiplier.  Two examples, comparing the effect to the default
908             # $max_mult value of 2.0, which causes a $adjusted_scale value
909             # of 0.2:
910             #
911             #  * Given the default $max_mult of 2.0, the value of
912             #    $adjusted_scale will be 0.2 [($max_mult - 1.0) / 5.0].
913             #    For a record whose average badge score is the maximum
914             #    of 5.0, that would make the relevance multiplier be
915             #    2.0:
916             #       1.0 + (5.0 [average score] * 0.2 [ $adjusted_scale ],
917             #    This would have the effect of doubling the effective
918             #    relevance of highly popular items.
919             #
920             #  * Given a $max_mult of 1.1, the value of $adjusted_scale
921             #    will be 0.02, meaning that the average badge value will be
922             #    multiplied by 0.02 rather than 0.2, then added to 1.0 and
923             #    used as a multiplier against the base relevance.  Thus a
924             #    change of at most 10% to the base relevance for a record
925             #    with a 5.0 average badge score. This will allow records
926             #    that are naturally very relevant to avoid being pushed
927             #    below badge-heavy records.
928             #
929             #  * Given a $max_mult of 3.0, the value of $adjusted_scale
930             #    will be 0.4, meaning that the average badge value will be
931             #    multiplied by 0.4 rather than 0.2, then added to 1.0 and
932             #    used as a multiplier against the base relevance. Thus a
933             #    change of as much as 200% to (or three times the size of)
934             #    the base relevance for a record with a 5.0 average badge
935             #    score.  This in turn will cause badges to outweigh
936             #    relevance to a very large degree.
937             #
938             # The maximum badge multiplier can be set to a value less than
939             # 1.0; this would have the effect of making less popular items
940             # show up higher in the results.  While this is not a likely
941             # option for production use, it could be useful for identifying
942             # interesting long-tail hits, particularly in a database
943             # where enough badges are configured so that very few records
944             # have an overage badge score of zero.
945
946             my $adjusted_scale = ( $max_mult - 1.0 ) / 5.0;
947             $rank = "1.0/(( $rel ) * (1.0 + (AVG(COALESCE(pop_with.total_score::NUMERIC,0.0)) * $adjusted_scale)))::NUMERIC";
948         }
949     } elsif ($sort_filter =~ /^pop/) {
950         $rank = '1.0/(AVG(COALESCE(pop_with.total_score::NUMERIC,0.0)) + 5.0)::NUMERIC';
951         my $pop_desc = $desc eq 'ASC' ? 'DESC' : 'ASC';
952         $pop_extra_sort = "3 $pop_desc $nullpos,";
953     } else {
954         # default to rel ranking
955         $rank = "1.0/($rel)::NUMERIC";
956     }
957
958     my $key = 'm.source';
959     $key = 'm.metarecord' if (grep {$_->name eq 'metarecord' or $_->name eq 'metabib'} @{$self->modifiers});
960
961     my $core_limit = $self->QueryParser->core_limit || 25000;
962     $core_limit = 1 if($self->find_modifier('lucky'));
963
964     my $flat_where = $$flat_plan{where};
965     if ($flat_where ne '') {
966         $flat_where = "AND (\n" . ${spc} x 5 . $flat_where . "\n" . ${spc} x 4 . ")";
967     }
968     my $with = $$flat_plan{with};
969     $with= "\nWITH $with" if $with;
970
971     # Need an array for query parser db function; this gives a better plan
972     # than the ARRAY_AGG(DISTINCT m.source) option as of PostgreSQL 9.1
973     my $agg_records = 'ARRAY[m.source] AS records';
974     if ($key =~ /metarecord/) {
975         # metarecord searches still require the ARRAY_AGG approach
976         $agg_records = 'ARRAY_AGG(DISTINCT m.source) AS records';
977     }
978
979     my $sql = <<SQL;
980 $with
981 SELECT  $key AS id,
982         $agg_records,
983         $rel AS rel,
984         $rank AS rank, 
985         FIRST(pubdate_t.value) AS tie_break,
986         STRING_AGG(ARRAY_TO_STRING(pop_with.badges,','),',') AS badges,
987         AVG(COALESCE(pop_with.total_score::NUMERIC,0.0))::NUMERIC(2,1) AS popularity
988   FROM  metabib.metarecord_source_map m
989         $$flat_plan{from}
990         $mra_join
991         $mrv_join
992         $bre_join
993         $pop_join
994         $pubdate_join
995         $lang_join
996   WHERE 1=1
997         $flat_where
998   GROUP BY 1
999   ORDER BY 4 $desc $nullpos, $pop_extra_sort 5 DESC $nullpos, 3 DESC
1000   LIMIT $core_limit
1001 SQL
1002
1003     warn $sql if $self->QueryParser->debug;
1004     return $sql;
1005
1006 }
1007
1008 sub flatten {
1009     my $self = shift;
1010
1011     die 'ERROR: nesting too deep or boolean list too long' if ($self->plan_level > 40);
1012
1013     my $from = shift || '';
1014     my $where = shift || '';
1015     my $with = '';
1016     my $uses_bre = 0;
1017     my $uses_mrd = 0;
1018     my $uses_mrv = 0;
1019
1020     my @rank_list;
1021     for my $node ( @{$self->query_nodes} ) {
1022
1023         if (ref($node)) {
1024             if ($node->isa( 'QueryParser::query_plan::node' )) {
1025
1026                 unless (@{$node->only_atoms}) {
1027                     push @rank_list, '1';
1028                     $where .= 'TRUE';
1029                     next;
1030                 }
1031
1032                 my $table = $node->table;
1033                 my $ctable = $node->combined_table;
1034                 my $talias = $node->table_alias;
1035
1036                 my $node_rank = 'COALESCE(' . $node->rank . " * ${talias}.weight, 0.0)";
1037
1038                 $from .= "\n" . ${spc} x 4 ."LEFT JOIN (\n"
1039                       . ${spc} x 5 . "SELECT fe.*, fe_weight.weight, ${talias}_xq.tsq, ${talias}_xq.tsq_rank /* search */\n"
1040                       . ${spc} x 6 . "FROM  $table AS fe";
1041                 $from .= "\n" . ${spc} x 7 . "JOIN config.metabib_field AS fe_weight ON (fe_weight.id = fe.field)";
1042
1043                 my @bump_fields;
1044                 my @field_ids;
1045                 if (@{$node->fields} > 0) {
1046                     @bump_fields = @{$node->fields};
1047
1048                     @field_ids = grep defined, (
1049                         map {
1050                             $self->QueryParser->search_field_ids_by_class(
1051                                 $node->classname, $_
1052                             )->[0]
1053                         } @bump_fields
1054                     );
1055                 } else {
1056                     @bump_fields = @{$self->QueryParser->search_fields->{$node->classname}};
1057                 }
1058
1059                 if ($node->dummy_count < @{$node->only_atoms} ) {
1060                     $with .= ",\n     " if $with;
1061                     $with .= "${talias}_xq AS (SELECT ". $node->tsquery ." AS tsq,". $node->tsquery_rank ." AS tsq_rank )";
1062                     if ($node->combined_search) {
1063                         $from .= "\n" . ${spc} x 6 . "JOIN $ctable AS com ON (com.record = fe.source";
1064                         if (@field_ids) {
1065                             $from .= " AND com.metabib_field IN (" . join(',',@field_ids) . "))";
1066                         } else {
1067                             $from .= " AND com.metabib_field IS NULL)";
1068                         }
1069                         $from .= "\n" . ${spc} x 6 . "JOIN ${talias}_xq ON (com.index_vector @@ ${talias}_xq.tsq)";
1070                     } else {
1071                         $from .= "\n" . ${spc} x 6 . "JOIN ${talias}_xq ON (fe.index_vector @@ ${talias}_xq.tsq)";
1072                     }
1073                 } else {
1074                     $from .= "\n" . ${spc} x 6 . ", (SELECT NULL::tsquery AS tsq, NULL:tsquery AS tsq_rank ) AS ${talias}_xq";
1075                 }
1076
1077                 if (@field_ids) {
1078                     $from .= "\n" . ${spc} x 6 . "WHERE fe_weight.id IN  (" .
1079                         join(',', @field_ids) . ")";
1080                 }
1081
1082                 $from .= "\n" . ${spc} x 4 . ") AS $talias ON (m.source = ${talias}.source)";
1083
1084                 my %used_bumps;
1085                 my @bumps;
1086                 my @bumpmults;
1087                 for my $field ( @bump_fields ) {
1088                     my $bumps = $self->QueryParser->find_relevance_bumps( $node->classname => $field );
1089                     for my $b (keys %$bumps) {
1090                         next if (!$$bumps{$b}{active});
1091                         next if ($used_bumps{$b});
1092                         $used_bumps{$b} = 1;
1093
1094                         next if ($$bumps{$b}{multiplier} == 1); # optimization to remove unneeded bumps
1095                         push @bumps, $b;
1096                         push @bumpmults, $$bumps{$b}{multiplier};
1097                     }
1098                 }
1099
1100                 if(scalar @bumps > 0 && scalar @{$node->only_positive_atoms} > 0) {
1101                     # Note: Previous rank function used search_normalize outright. Duplicating that here.
1102                     $node_rank .= "\n" . ${spc} x 5 . "* evergreen.rel_bump(('{' || quote_literal(search_normalize(";
1103                     $node_rank .= join(")) || ',' || quote_literal(search_normalize(",map { $self->QueryParser->quote_phrase_value($_->content) } @{$node->only_positive_atoms});
1104                     $node_rank .= ")) || '}')::TEXT[], " . $node->table_alias . ".value, '{" . join(",",@bumps) . "}'::TEXT[], '{" . join(",",@bumpmults) . "}'::NUMERIC[])";
1105                 }
1106
1107                 my $NOT = '';
1108                 $NOT = 'NOT ' if $node->negate;
1109
1110                 $where .= "$NOT(" . $talias . ".id IS NOT NULL";
1111                 if (@{$node->phrases}) {
1112                     $where .= ' AND ' . join(' AND ', map {
1113                         "${talias}.value ~* ".$self->QueryParser->quote_phrase_value($_, 1)
1114                     } @{$node->phrases});
1115                 } else {
1116                     for my $atom (@{$node->only_real_atoms}) {
1117                         next unless $atom->{content} && $atom->{content} =~ /(^\^|\$$)/;
1118                         $where .= " AND ${talias}.value ~* ".$self->QueryParser->quote_phrase_value($atom->{content});
1119                     }
1120                 }
1121                 $where .= ')';
1122
1123                 push @rank_list, $node_rank;
1124
1125             } elsif ($node->isa( 'QueryParser::query_plan::facet' )) {
1126
1127                 my $talias = $node->table_alias;
1128
1129                 my @field_ids;
1130                 if (@{$node->fields} > 0) {
1131                     push(@field_ids, $self->QueryParser->facet_field_ids_by_class( $node->classname, $_ )->[0]) for (@{$node->fields});
1132                 } else {
1133                     @field_ids = @{ $self->QueryParser->facet_field_ids_by_class( $node->classname ) };
1134                 }
1135
1136                 my $join_type = ($node->negate or !$self->top_plan) ? 'LEFT' : 'INNER';
1137                 $from .= "\n${spc}$join_type JOIN /* facet */ metabib.facet_entry $talias ON (\n"
1138                       . ${spc} x 2 . "m.source = ${talias}.source\n"
1139                       . ${spc} x 2 . "AND SUBSTRING(${talias}.value,1,1024) IN ("
1140                       . join(",", map { $self->QueryParser->quote_value($_) } @{$node->values}) . ")\n"
1141                       . ${spc} x 2 ."AND ${talias}.field IN (". join(',', @field_ids) . ")\n"
1142                       . "${spc})";
1143
1144                 if ($join_type ne 'INNER') {
1145                     my $NOT = $node->negate ? '' : ' NOT';
1146                     $where .= "${talias}.id IS$NOT NULL";
1147                 } elsif ($where ne '') {
1148                     # Strip extra joiner
1149                     $where =~ s/(\s|\n)+(AND|OR)\s$//;
1150                 }
1151
1152             } else {
1153                 my $subnode = $node->flatten;
1154
1155                 # strip the trailing bool from the previous loop if there is 
1156                 # nothing to add to the where within this loop.
1157                 if ($$subnode{where} eq '') {
1158                     $where =~ s/(\s|\n)+(AND|OR)\s$//;
1159                 }
1160
1161                 push(@rank_list, @{$$subnode{rank_list}});
1162                 $from .= $$subnode{from};
1163
1164                 my $NOT = '';
1165                 $NOT = 'NOT ' if $node->negate;
1166
1167                 if ($$subnode{where} ne '') {
1168                     $where .= "$NOT(\n"
1169                            . ${spc} x ($self->plan_level + 6) . $$subnode{where} . "\n"
1170                            . ${spc} x ($self->plan_level + 5) . ')';
1171                 }
1172
1173                 if ($$subnode{with}) {
1174                     $with .= ",\n     " if $with;
1175                     $with .= $$subnode{with};
1176                 }
1177
1178                 $uses_bre = $$subnode{uses_bre};
1179                 $uses_mrd = $$subnode{uses_mrd};
1180                 $uses_mrv = $$subnode{uses_mrv};
1181             }
1182         } else {
1183
1184             warn "flatten(): appending WHERE bool to: $where\n" if $self->QueryParser->debug;
1185
1186             if ($where ne '') {
1187                 $where .= "\n" . ${spc} x ( $self->plan_level + 5 ) . 'AND ' if ($node eq '&');
1188                 $where .= "\n" . ${spc} x ( $self->plan_level + 5 ) . 'OR ' if ($node eq '|');
1189             }
1190         }
1191     }
1192
1193     my $joiner = "\n" . ${spc} x ( $self->plan_level + 5 ) . ($self->joiner eq '&' ? 'AND ' : 'OR ');
1194
1195     my @dlist = ();
1196     my $common = 0;
1197     # for each dynamic filter, build more of the WHERE clause
1198     for my $filter (@{$self->filters}) {
1199         my $NOT = $filter->negate ? 'NOT ' : '';
1200         if (grep { $_ eq $filter->name } @{ $self->QueryParser->dynamic_filters }) {
1201
1202             my $fname = $filter->name;
1203             $fname = 'item_lang' if $fname eq 'language'; #XXX filter aliases 
1204
1205             warn "flatten(): processing dynamic filter ". $filter->name ."\n"
1206                 if $self->QueryParser->debug;
1207
1208             my $vlist_query;
1209             ($vlist_query, $common) = $self->dynamic_filter_compile( $fname, $filter->args, $filter->negate );
1210
1211             # bool joiner for intra-plan nodes/filters
1212             push(@dlist, $self->joiner) if @dlist;
1213             push(@dlist, $vlist_query);
1214             $uses_mrv = 1;
1215         } else {
1216             if ($filter->name eq 'before') {
1217                 if (@{$filter->args} == 1) {
1218                     $where .= $joiner if $where ne '';
1219                     $where .= "${NOT}COALESCE(pubdate_t.value <= "
1220                            . $self->QueryParser->quote_value($filter->args->[0])
1221                            . ", false)";
1222                 }
1223             } elsif ($filter->name eq 'after') {
1224                 if (@{$filter->args} == 1) {
1225                     $where .= $joiner if $where ne '';
1226                     $where .= "${NOT}COALESCE(pubdate_t.value >= "
1227                            . $self->QueryParser->quote_value($filter->args->[0])
1228                            . ", false)";
1229                 }
1230             } elsif ($filter->name eq 'during') {
1231                 if (@{$filter->args} == 1) {
1232                     $where .= $joiner if $where ne '';
1233                     $where .= "${NOT}COALESCE("
1234                            . $self->QueryParser->quote_value($filter->args->[0])
1235                            . " BETWEEN pubdate_t.value AND (mrd.attrs->'date2'), false)";
1236                     $uses_mrd = 1;
1237                 }
1238             } elsif ($filter->name eq 'between') {
1239                 if (@{$filter->args} == 2) {
1240                     $where .= $joiner if $where ne '';
1241                     $where .= "${NOT}COALESCE(pubdate_t.value BETWEEN "
1242                            . $self->QueryParser->quote_value($filter->args->[0])
1243                            . " AND "
1244                            . $self->QueryParser->quote_value($filter->args->[1])
1245                            . ", false)";
1246                 }
1247             } elsif ($filter->name eq 'container') {
1248                 if (@{$filter->args} >= 3) {
1249                     my ($class, $ctype, $cid, $token) = @{$filter->args};
1250                     my $perm_join = '';
1251                     my $rec_join = '';
1252                     my $rec_field = 'ci.target_biblio_record_entry';
1253                     if ($class eq 'bre') {
1254                         $class = 'biblio_record_entry';
1255                     } elsif ($class eq 'acn') {
1256                         $class = 'call_number';
1257                         $rec_field = 'cn.record';
1258                         $rec_join = 'JOIN asset.call_number cn ON (ci.target_call_number = cn.id)';
1259                     } elsif ($class eq 'acp') {
1260                         $class = 'copy';
1261                         $rec_field = 'cn.record';
1262                         $rec_join = 'JOIN asset.copy cp ON (ci.target_copy = cp.id) JOIN asset.call_number cn ON (cp.call_number = cn.id)';
1263                     } else {
1264                         $class = undef;
1265                     }
1266
1267                     if ($class) {
1268                         my ($u,$e) = $apputils->checksesperm($token) if ($token);
1269                         $perm_join = ' OR c.owner = ' . $u->id if ($u && !$e);
1270
1271                         my $filter_alias = "$filter";
1272                         $filter_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1273                         $filter_alias =~ s/\|/_/go;
1274
1275                         $with .= ",\n     " if $with;
1276                         $with .= "container_${filter_alias} AS (\n";
1277                         $with .= "       SELECT $rec_field AS record FROM container.${class}_bucket_item ci\n"
1278                                . "             JOIN container.${class}_bucket c ON (c.id = ci.bucket) $rec_join\n"
1279                                . "       WHERE c.btype = " . $self->QueryParser->quote_value($ctype) . "\n"
1280                                . "             AND c.id = " . $self->QueryParser->quote_value($cid) . "\n"
1281                                . "             AND (c.pub IS TRUE$perm_join)\n";
1282                         if ($class eq 'copy') {
1283                             $with .= "       UNION\n"
1284                                    . "       SELECT pr.peer_record AS record FROM container.copy_bucket_item ci\n"
1285                                    . "             JOIN container.copy_bucket c ON (c.id = ci.bucket)\n"
1286                                    . "             JOIN biblio.peer_bib_copy_map pr ON ci.target_copy = pr.target_copy\n"
1287                                    . "       WHERE c.btype = " . $self->QueryParser->quote_value($ctype) . "\n"
1288                                    . "             AND c.id = " . $self->QueryParser->quote_value($cid) . "\n"
1289                                    . "             AND (c.pub IS TRUE$perm_join)\n";
1290                         }
1291                         $with .= "     )";
1292
1293                         my $optimize_join = 1 if $self->top_plan and !$NOT;
1294                         $from .= "\n" . ${spc} x 3 . ( $optimize_join ? 'INNER' : 'LEFT') . " JOIN container_${filter_alias} ON container_${filter_alias}.record = m.source";
1295
1296                         if (!$optimize_join) {
1297                             $where .= $joiner if $where ne '';
1298                             $where .= "(container_${filter_alias} IS " . ( $NOT ? 'NULL)' : 'NOT NULL)');
1299                         }
1300                     }
1301                 }
1302             } elsif ($filter->name eq 'record_list') {
1303                 if (@{$filter->args} > 0) {
1304                     my $key = 'm.source';
1305                     $key = 'm.metarecord' if (grep {$_->name eq 'metarecord' or $_->name eq 'metabib'} @{$self->QueryParser->parse_tree->modifiers});
1306                     $where .= $joiner if $where ne '';
1307                     $where .= "$key ${NOT}IN (" . join(',', map { $self->QueryParser->quote_value($_) } @{$filter->args}) . ')';
1308                 }
1309
1310             } elsif ($filter->name eq 'has_browse_entry') {
1311                 if (@{$filter->args} >= 2) {
1312                     my $entry = int(shift @{$filter->args});
1313                     my $fields = join(",", map(int, @{$filter->args}));
1314                     $from .= "\n" . $spc x 3 . sprintf("INNER JOIN metabib.browse_entry_def_map mbedm ON (mbedm.source = m.source AND mbedm.entry = %d AND mbedm.def IN (%s))", $entry, $fields);
1315                 }
1316             } elsif ($filter->name eq 'edit_date' or $filter->name eq 'create_date') {
1317                 # bre.create_date and bre.edit_date filtering
1318                 my $datefilter = $filter->name;
1319
1320                 $uses_bre = 1;
1321
1322                 if ($filter && $filter->args && scalar(@{$filter->args}) > 0 && scalar(@{$filter->args}) < 3) {
1323                     my ($cstart, $cend) = @{$filter->args};
1324         
1325                     if (!$cstart and !$cend) {
1326                         # useless use of filter
1327                     } elsif (!$cstart or $cstart eq '-infinity') { # no start supplied
1328                         if ($cend eq 'infinity') {
1329                             # useless use of filter
1330                         } else {
1331                             # "before $cend"
1332                             $cend = cleanse_ISO8601($cend);
1333                             $where .= $joiner if $where ne '';
1334                             $where .= "bre.$datefilter <= \$_$$\$$cend\$_$$\$";
1335                         }
1336             
1337                     } elsif (!$cend or $cend eq 'infinity') { # no end supplied
1338                         if ($cstart eq '-infinity') {
1339                             # useless use of filter
1340                         } else { # "after $cstart"
1341                             $cstart = cleanse_ISO8601($cstart);
1342                             $where .= $joiner if $where ne '';
1343                             $where .= "bre.$datefilter >= \$_$$\$$cstart\$_$$\$";
1344                         }
1345                     } else { # both supplied
1346                         # "between $cstart and $cend"
1347                         $cstart = cleanse_ISO8601($cstart);
1348                         $cend = cleanse_ISO8601($cend);
1349                         $where .= $joiner if $where ne '';
1350                         $where .= "bre.$datefilter BETWEEN \$_$$\$$cstart\$_$$\$ AND \$_$$\$$cend\$_$$\$";
1351                     }
1352                 }
1353             } elsif ($filter->name eq 'bib_source') {
1354                 $uses_bre = 1;
1355
1356                 if (@{$filter->args} > 0) {
1357                     $where .= $joiner if $where ne '';
1358                     $where .= "${NOT}COALESCE(bre.source IN ("
1359                            . join(',', map { $self->QueryParser->quote_value($_) } @{ $filter->args })
1360                            . "), false)";
1361                 }
1362             }
1363         }
1364     }
1365
1366     if (@dlist) {
1367
1368         $where .= $joiner if $where ne '';
1369         if ($common) { # Use a function wrapper to inform PG of the non-rareness of one or more filter elements
1370             $where .= sprintf(
1371                 'evergreen.query_int_wrapper(mrv.vlist, \'%s\')',
1372                 join('', @dlist)
1373             );
1374         } else {
1375             $where .= sprintf(
1376                 'mrv.vlist @@ \'%s\'',
1377                 join('', @dlist)
1378             );
1379         }
1380     }
1381
1382     warn "flatten(): full filter where => $where\n" if $self->QueryParser->debug;
1383
1384     return {
1385         rank_list => \@rank_list,
1386         from => $from,
1387         where => $where,
1388         with => $with,
1389         uses_bre => $uses_bre,
1390         uses_mrv => $uses_mrv,
1391         uses_mrd => $uses_mrd
1392     };
1393 }
1394
1395
1396 #-------------------------------
1397 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::filter;
1398 use base 'QueryParser::query_plan::filter';
1399
1400 #-------------------------------
1401 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::facet;
1402 use base 'QueryParser::query_plan::facet';
1403
1404 sub classname {
1405     my $self = shift;
1406     my ($classname) = split '\|', $self->name;
1407     return $classname;
1408 }
1409
1410 sub fields {
1411     my $self = shift;
1412     my ($classname,@fields) = split '\|', $self->name;
1413     return \@fields;
1414 }
1415
1416 sub table_alias {
1417     my $self = shift;
1418
1419     my $table_alias = "$self";
1420     $table_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1421     $table_alias .= '_' . $self->name;
1422     $table_alias =~ s/\|/_/go;
1423
1424     return $table_alias;
1425 }
1426
1427
1428 #-------------------------------
1429 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::modifier;
1430 use base 'QueryParser::query_plan::modifier';
1431
1432 #-------------------------------
1433 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::node::atom;
1434 use base 'QueryParser::query_plan::node::atom';
1435
1436 sub sql {
1437     my $self = shift;
1438     my $sql = shift;
1439
1440     $self->{sql} = $sql if ($sql);
1441
1442     return $self->{sql} if ($self->{sql});
1443     return $self->buildSQL;
1444 }
1445
1446 sub buildSQL {
1447     my $self = shift;
1448
1449     my $classname = $self->node->classname;
1450
1451     return $self->sql("to_tsquery('$classname','')") if $self->{dummy};
1452
1453     my $normalizers = $self->node->plan->QueryParser->query_normalizers( $classname );
1454     my $fields = $self->node->fields;
1455
1456     my $lang;
1457     my $filter = $self->node->plan->find_filter('preferred_language');
1458     $lang ||= $filter->args->[0] if ($filter && $filter->args);
1459     $lang ||= $self->node->plan->QueryParser->default_preferred_language;
1460     my $ts_configs = [];
1461
1462     if (@{$self->node->phrases}) {
1463         # We assume we want 'simple' for phrases. Gives us less to match against later.
1464         $ts_configs = ['simple'];
1465     } else {
1466         if (!@$fields) {
1467             $ts_configs = $self->node->plan->QueryParser->class_ts_config($classname, $lang);
1468         } else {
1469             for my $field (@$fields) {
1470                 push @$ts_configs, @{$self->node->plan->QueryParser->field_ts_config($classname, $field, $lang)};
1471             }
1472         }
1473         $ts_configs = [keys %{{map { $_ => 1 } @$ts_configs}}];
1474     }
1475
1476     # Assume we want exact if none otherwise provided.
1477     # Because we can reasonably expect this to exist
1478     $ts_configs = ['simple'] unless (scalar @$ts_configs);
1479
1480     $fields = $self->node->plan->QueryParser->search_fields->{$classname} if (!@$fields);
1481
1482     my %norms;
1483     my $pos = 0;
1484     for my $field (@$fields) {
1485         for my $nfield (keys %$normalizers) {
1486             for my $nizer ( @{$$normalizers{$nfield}} ) {
1487                 if ($field eq $nfield) {
1488                     my $param_string = OpenSRF::Utils::JSON->perl2JSON($nizer->{params});
1489                     if (!exists($norms{$nizer->{function}.$param_string})) {
1490                         $norms{$nizer->{function}.$param_string} = {p=>$pos++,n=>$nizer};
1491                     }
1492                 }
1493             }
1494         }
1495     }
1496
1497     my $sql = $self->node->plan->QueryParser->quote_value($self->content);
1498
1499     for my $n ( map { $$_{n} } sort { $$a{p} <=> $$b{p} } values %norms ) {
1500         $sql = join(', ', $sql, map { $self->node->plan->QueryParser->quote_value($_) } @{ $n->{params} });
1501         $sql = $n->{function}."($sql)";
1502     }
1503
1504     my $prefix = $self->prefix || '';
1505     my $suffix = $self->suffix || '';
1506     my $joiner = ' || ';
1507     $joiner = ' && ' if $self->prefix eq '!'; # Negative atoms should be "none of the variants" instead of "any of the variants"
1508
1509     $prefix = "'$prefix' ||" if $prefix;
1510     my $suffix_op = '';
1511     my $suffix_after = '';
1512
1513     $suffix_op = ":$suffix" if $suffix;
1514     $suffix_after = "|| '$suffix_op'" if $suffix;
1515
1516     my @sql_set = ();
1517     for my $ts_config (@$ts_configs) {
1518         push @sql_set, "to_tsquery('$ts_config', COALESCE(NULLIF($prefix '(' || btrim(regexp_replace($sql,E'(?:\\\\s+|:)','$suffix_op&','g'),'&|') $suffix_after || ')', '()'), ''))";
1519     }
1520
1521     $sql = join($joiner, @sql_set);
1522     $sql = '(' . $sql . ')' if (scalar(@$ts_configs) > 1);
1523
1524     return $self->sql($sql);
1525 }
1526
1527 #-------------------------------
1528 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::node;
1529 use base 'QueryParser::query_plan::node';
1530
1531 sub only_atoms {
1532     my $self = shift;
1533
1534     $self->{dummy_count} = 0;
1535
1536     my $atoms = $self->query_atoms;
1537     my @only_atoms;
1538     for my $a (@$atoms) {
1539         push(@only_atoms, $a) if (ref($a) && $a->isa('QueryParser::query_plan::node::atom'));
1540         $self->{dummy_count}++ if (ref($a) && $a->{dummy});
1541     }
1542
1543     return \@only_atoms;
1544 }
1545
1546 sub only_real_atoms {
1547     my $self = shift;
1548
1549     my $atoms = $self->query_atoms;
1550     my @only_real_atoms;
1551     for my $a (@$atoms) {
1552         push(@only_real_atoms, $a) if (ref($a) && $a->isa('QueryParser::query_plan::node::atom') && !($a->{dummy}));
1553     }
1554
1555     return \@only_real_atoms;
1556 }
1557
1558 sub only_positive_atoms {
1559     my $self = shift;
1560
1561     my $atoms = $self->query_atoms;
1562     my @only_positive_atoms;
1563     for my $a (@$atoms) {
1564         push(@only_positive_atoms, $a) if (ref($a) && $a->isa('QueryParser::query_plan::node::atom') && !($a->{dummy}) && ($a->{prefix} ne '!'));
1565     }
1566
1567     return \@only_positive_atoms;
1568 }
1569
1570 sub dummy_count {
1571     my $self = shift;
1572     return $self->{dummy_count};
1573 }
1574
1575 sub table {
1576     my $self = shift;
1577     my $table = shift;
1578     $self->{table} = $table if ($table);
1579     return $self->{table} if $self->{table};
1580     return $self->table( 'metabib.' . $self->classname . '_field_entry' );
1581 }
1582
1583 sub combined_table {
1584     my $self = shift;
1585     my $ctable = shift;
1586     $self->{ctable} = $ctable if ($ctable);
1587     return $self->{ctable} if $self->{ctable};
1588     return $self->combined_table( 'metabib.combined_' . $self->classname . '_field_entry' );
1589 }
1590
1591 sub combined_search {
1592     my $self = shift;
1593     return $self->plan->QueryParser->search_class_combined($self->classname);
1594 }
1595
1596 sub table_alias {
1597     my $self = shift;
1598     my $table_alias = shift;
1599     $self->{table_alias} = $table_alias if ($table_alias);
1600     return $self->{table_alias} if ($self->{table_alias});
1601
1602     $table_alias = "$self";
1603     $table_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1604     $table_alias .= '_' . $self->requested_class;
1605     $table_alias =~ s/\|/_/go;
1606
1607     return $self->table_alias( $table_alias );
1608 }
1609
1610 sub tsquery {
1611     my $self = shift;
1612     return $self->{tsquery} if ($self->{tsquery});
1613
1614     for my $atom (@{$self->query_atoms}) {
1615         if (ref($atom)) {
1616             $self->{tsquery} .= "\n" . ${spc} x 3 . $atom->sql;
1617         } else {
1618             $self->{tsquery} .= $atom x 2;
1619         }
1620     }
1621
1622     return $self->{tsquery};
1623 }
1624
1625 sub tsquery_rank {
1626     my $self = shift;
1627     return $self->{tsquery_rank} if ($self->{tsquery_rank});
1628     my @atomlines;
1629
1630     for my $atom (@{$self->only_positive_atoms}) {
1631         push @atomlines, "\n" . ${spc} x 3 . $atom->sql;
1632     }
1633     $self->{tsquery_rank} = join(' ||', @atomlines);
1634     $self->{tsquery_rank} = 'NULL::tsquery' unless $self->{tsquery_rank};
1635     return $self->{tsquery_rank};
1636 }
1637
1638 sub rank {
1639     my $self = shift;
1640     return $self->{rank} if ($self->{rank});
1641
1642     my $rank_norm_map = $self->plan->QueryParser->custom_data->{rank_cd_weight_map};
1643
1644     my $cover_density = 0;
1645     for my $norm ( keys %$rank_norm_map) {
1646         $cover_density += $$rank_norm_map{$norm} if ($self->plan->QueryParser->parse_tree->find_modifier($norm));
1647     }
1648
1649     my $weights = join(', ', @{$self->plan->QueryParser->search_class_weights($self->classname)});
1650
1651     return $self->{rank} = "ts_rank_cd('{" . $weights . "}', " . $self->table_alias . '.index_vector, ' . $self->table_alias . ".tsq_rank, $cover_density)";
1652 }
1653
1654
1655 1;
1656