]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Storage/Driver/Pg/QueryParser.pm
LP#1743650: Bib vis testing needs different handling
[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_filter( 'from_metarecord' );
678 __PACKAGE__->add_search_modifier( 'available' );
679 __PACKAGE__->add_search_modifier( 'staff' );
680 __PACKAGE__->add_search_modifier( 'deleted' );
681 __PACKAGE__->add_search_modifier( 'lucky' );
682
683 # Start from container data (bre, acn, acp): container(bre,bookbag,123,deadb33fdeadb33fdeadb33fdeadb33f)
684 __PACKAGE__->add_search_filter( 'container' );
685
686 # Start from a list of record ids, either bre or metarecords, depending on the #metabib modifier
687 __PACKAGE__->add_search_filter( 'record_list' );
688
689 __PACKAGE__->add_search_filter( 'has_browse_entry' );
690
691 # copy_tag(copy_tag_code,copy_tag_search)
692 __PACKAGE__->add_search_filter( 'copy_tag' );
693
694 # used internally, but generally not user-settable
695 __PACKAGE__->add_search_filter( 'preferred_language' );
696 __PACKAGE__->add_search_filter( 'preferred_language_weight' );
697 __PACKAGE__->add_search_filter( 'preferred_language_multiplier' );
698 __PACKAGE__->add_search_filter( 'core_limit' );
699
700 # XXX Valid values to be supplied by SVF
701 __PACKAGE__->add_search_filter( 'sort' );
702
703 # modifies core query, not configurable
704 __PACKAGE__->add_search_modifier( 'descending' );
705 __PACKAGE__->add_search_modifier( 'ascending' );
706 __PACKAGE__->add_search_modifier( 'nullsfirst' );
707 __PACKAGE__->add_search_modifier( 'nullslast' );
708 __PACKAGE__->add_search_modifier( 'metarecord' );
709 __PACKAGE__->add_search_modifier( 'metabib' );
710
711
712 #-------------------------------
713 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan;
714 use base 'QueryParser::query_plan';
715 use OpenSRF::Utils::Logger qw($logger);
716 use OpenSRF::Utils qw/:datetime/;
717 use Data::Dumper;
718 use OpenILS::Application::AppUtils;
719 use OpenILS::Utils::Normalize qw/search_normalize/;
720 my $apputils = "OpenILS::Application::AppUtils";
721
722 our %_dfilter_controlled_cache = ();
723 our %_dfilter_stats_cache = ();
724 our $_pg_version = 0;
725
726 sub dynamic_filter_compile {
727     my ($self, $filter, $params, $negate) = @_;
728     my $e = OpenILS::Utils::CStoreEditor->new;
729
730     $negate = $negate ? '!' : '';
731
732     if (!$_pg_version) {
733         ($_pg_version = $e->json_query({from => ['version']})->[0]->{version}) =~ s/^.+?(\d\.\d).+$/$1/;
734     }
735
736     my $common = 0;
737     if ($_pg_version >= 9.2) {
738         if (!scalar keys %_dfilter_stats_cache) {
739             my $data = $e->json_query({from => ['evergreen.pg_statistics', 'record_attr_vector_list', 'vlist']});
740             %_dfilter_stats_cache = map {
741                 ( $_->{element}, $_->{frequency} )
742             } grep { $_->{frequency} > 5 } @$data; # Pin floor to 5% of the table
743         }
744     } else {
745         $common = 1; # Assume it's expensive
746     }
747
748     if (!exists($_dfilter_controlled_cache{$filter})) {
749         my $crad = $e->retrieve_config_record_attr_definition($filter);
750         my $ccvm_list = $e->search_config_coded_value_map({ctype =>$filter});
751
752         $_dfilter_controlled_cache{$filter} = $crad->to_bare_hash;
753         $_dfilter_controlled_cache{$filter}{controlled} = scalar @$ccvm_list;
754     }
755
756     my $method = $_dfilter_controlled_cache{$filter}{controlled} ?
757         'search_config_coded_value_map' : 'search_metabib_uncontrolled_record_attr_value';
758     my $attr_field = $_dfilter_controlled_cache{$filter}{controlled} ?
759         'ctype' : 'attr';
760     my $value_field = $_dfilter_controlled_cache{$filter}{controlled} ?
761         'code' : 'value';
762
763     my $attr_objects = $e->$method({ $attr_field => $filter, $value_field => $params });
764     $common = scalar(grep { exists($_dfilter_stats_cache{$_->id}) } @$attr_objects) unless $common;
765     
766     return (sprintf('%s(%s)', $negate,
767         join(
768             '|', 
769             map { $_->id } @$attr_objects
770         )
771     ), $common);
772 }
773
774 sub toSQL {
775     my $self = shift;
776
777     my %filters;
778
779     for my $f ( qw/preferred_language preferred_language_multiplier preferred_language_weight core_limit check_limit skip_check superpage superpage_size/ ) {
780         my $col = $f;
781         $col = 'preferred_language_multiplier' if ($f eq 'preferred_language_weight');
782         my ($filter) = $self->find_filter($f);
783         if ($filter and @{$filter->args}) {
784             $filters{$col} = $filter->args->[0];
785         }
786     }
787
788     $self->QueryParser->superpage($filters{superpage}) if ($filters{superpage});
789     $self->QueryParser->superpage_size($filters{superpage_size}) if ($filters{superpage_size});
790     $self->QueryParser->core_limit($filters{core_limit}) if ($filters{core_limit});
791
792     $logger->debug("Query plan:\n".Dumper($self));
793
794     my $flat_plan = $self->flatten;
795
796     # generate the relevance ranking
797     my $rel = '1'; # Default to something simple in case rank_list is empty.
798     if (@{$$flat_plan{rank_list}}) {
799         $rel = "AVG(\n"
800              . ${spc} x 5 ."("
801              . join(")\n" . ${spc} x 5 . "+ (", @{$$flat_plan{rank_list}})
802              . ")\n"
803              . ${spc} x 4 . ")+1";
804     }
805
806     # find any supplied sort option
807     my ($sort_filter) = $self->find_filter('sort');
808     if ($sort_filter) {
809         $sort_filter = $sort_filter->args->[0];
810     } else {
811         $sort_filter = 'rel';
812     }
813
814     my $lang_join = '';
815     if (($filters{preferred_language} || $self->QueryParser->default_preferred_language) && ($filters{preferred_language_multiplier} || $self->QueryParser->default_preferred_language_multiplier)) {
816     
817         my $pl = $self->QueryParser->quote_value( $filters{preferred_language} ? $filters{preferred_language} : $self->QueryParser->default_preferred_language );
818         $$flat_plan{with} .= ',' if $$flat_plan{with};
819         $$flat_plan{with} .= "lang_with AS (SELECT id FROM config.coded_value_map WHERE ctype = 'item_lang' AND code = $pl)";
820         $lang_join = ",lang_with";
821
822         my $plw = $filters{preferred_language_multiplier} ? $filters{preferred_language_multiplier} : $self->QueryParser->default_preferred_language_multiplier;
823         $rel = "($rel * COALESCE( NULLIF( FIRST(mrv.vlist \@> ARRAY[lang_with.id]), FALSE )::INT * $plw, 1))";
824         $$flat_plan{uses_mrv} = 1;
825     }
826
827     my $mrv_join = '';
828     if ($$flat_plan{uses_mrv}) {
829         $mrv_join = 'INNER JOIN metabib.record_attr_vector_list mrv ON m.source = mrv.source';
830     }
831
832     my $mra_join = '';
833     if ($$flat_plan{uses_mrd}) {
834         $mra_join = 'INNER JOIN metabib.record_attr mrd ON m.source = mrd.id';
835     }
836
837     my $pubdate_join = "LEFT JOIN metabib.record_sorter pubdate_t ON m.source = pubdate_t.source AND attr = 'pubdate'";
838
839     my $bre_join = '';
840     if ($self->find_modifier('deleted')) {
841         $bre_join = 'INNER JOIN biblio.record_entry bre ON m.source = bre.id AND bre.deleted';
842         # The above suffices for filters too when the #deleted modifier
843         # is in use.
844     } elsif ($$flat_plan{uses_bre} or !$self->find_modifier('staff')) {
845         $bre_join = 'INNER JOIN biblio.record_entry bre ON m.source = bre.id';
846     }
847
848     my $desc = 'ASC';
849     $desc = 'DESC' if ($self->find_modifier('descending'));
850
851     my $nullpos = 'NULLS LAST';
852     $nullpos = 'NULLS FIRST' if ($self->find_modifier('nullsfirst'));
853
854     # Do we have a badges() filter?
855     my $badges = '';
856     my ($badge_filter) = $self->find_filter('badges');
857     if ($badge_filter && @{$badge_filter->args}) {
858         $badges = join (',', grep /^\d+$/, @{$badge_filter->args});
859     }
860
861     # Do we have a badge_orgs() filter? (used for calculating popularity)
862     my $borgs = '';
863     my ($bo_filter) = $self->find_filter('badge_orgs');
864     if ($bo_filter && @{$bo_filter->args}) {
865         $borgs = join (',', grep /^\d+$/, @{$bo_filter->args});
866     }
867
868     # Build the badge-ish WITH query
869     my $pop_with = <<'    WITH';
870         pop_with AS (
871             SELECT  record,
872                     ARRAY_AGG(badge) AS badges,
873                     SUM(s.score::NUMERIC*b.weight::NUMERIC)/SUM(b.weight::NUMERIC) AS total_score
874               FROM  rating.record_badge_score s
875                     JOIN rating.badge b ON (
876                         b.id = s.badge
877     WITH
878
879     $pop_with .= " AND b.id = ANY ('{$badges}')" if ($badges);
880     $pop_with .= " AND b.scope = ANY ('{$borgs}')" if ($borgs);
881     $pop_with .= ') GROUP BY 1)'; 
882
883     my $pop_join = $badges ? # inner join if we are restricting via badges()
884         'INNER JOIN pop_with ON ( m.source = pop_with.record )' : 
885         'LEFT JOIN pop_with ON ( m.source = pop_with.record )';
886
887     $$flat_plan{with} .= ',' if $$flat_plan{with};
888     $$flat_plan{with} .= $pop_with;
889
890
891     my $rank;
892     my $pop_extra_sort = '';
893     if (grep {$_ eq $sort_filter} @{$self->QueryParser->dynamic_sorters}) {
894         $rank = "FIRST((SELECT value FROM metabib.record_sorter rbr WHERE rbr.source = m.source and attr = '$sort_filter'))"
895     } elsif ($sort_filter eq 'create_date') {
896         $rank = "FIRST((SELECT create_date FROM biblio.record_entry rbr WHERE rbr.id = m.source))";
897     } elsif ($sort_filter eq 'edit_date') {
898         $rank = "FIRST((SELECT edit_date FROM biblio.record_entry rbr WHERE rbr.id = m.source))";
899     } elsif ($sort_filter eq 'poprel') {
900         my $max_mult = $self->QueryParser->max_popularity_importance_multiplier() // 2.0;
901         $max_mult = 0.1 if $max_mult < 0.1; # keep it within reasonable bounds,
902                                             # and avoid the division-by-zero error
903                                             # you'd get if you allowed it to be
904                                             # zero
905
906         if ( $max_mult == 1.0 ) { # no adjustment requested by the configuration
907             $rank = "1.0/($rel)::NUMERIC";
908         } else { # calculate adjustment
909
910             # Scale the 0-5 effect of popularity badges by providing a multiplier
911             # for the badge average based on the overall maximum
912             # multiplier.  Two examples, comparing the effect to the default
913             # $max_mult value of 2.0, which causes a $adjusted_scale value
914             # of 0.2:
915             #
916             #  * Given the default $max_mult of 2.0, the value of
917             #    $adjusted_scale will be 0.2 [($max_mult - 1.0) / 5.0].
918             #    For a record whose average badge score is the maximum
919             #    of 5.0, that would make the relevance multiplier be
920             #    2.0:
921             #       1.0 + (5.0 [average score] * 0.2 [ $adjusted_scale ],
922             #    This would have the effect of doubling the effective
923             #    relevance of highly popular items.
924             #
925             #  * Given a $max_mult of 1.1, the value of $adjusted_scale
926             #    will be 0.02, meaning that the average badge value will be
927             #    multiplied by 0.02 rather than 0.2, then added to 1.0 and
928             #    used as a multiplier against the base relevance.  Thus a
929             #    change of at most 10% to the base relevance for a record
930             #    with a 5.0 average badge score. This will allow records
931             #    that are naturally very relevant to avoid being pushed
932             #    below badge-heavy records.
933             #
934             #  * Given a $max_mult of 3.0, the value of $adjusted_scale
935             #    will be 0.4, meaning that the average badge value will be
936             #    multiplied by 0.4 rather than 0.2, then added to 1.0 and
937             #    used as a multiplier against the base relevance. Thus a
938             #    change of as much as 200% to (or three times the size of)
939             #    the base relevance for a record with a 5.0 average badge
940             #    score.  This in turn will cause badges to outweigh
941             #    relevance to a very large degree.
942             #
943             # The maximum badge multiplier can be set to a value less than
944             # 1.0; this would have the effect of making less popular items
945             # show up higher in the results.  While this is not a likely
946             # option for production use, it could be useful for identifying
947             # interesting long-tail hits, particularly in a database
948             # where enough badges are configured so that very few records
949             # have an overage badge score of zero.
950
951             my $adjusted_scale = ( $max_mult - 1.0 ) / 5.0;
952             $rank = "1.0/(( $rel ) * (1.0 + (AVG(COALESCE(pop_with.total_score::NUMERIC,0.0::NUMERIC)) * ${adjusted_scale}::NUMERIC)))::NUMERIC";
953         }
954     } elsif ($sort_filter =~ /^pop/) {
955         $rank = '1.0/(AVG(COALESCE(pop_with.total_score::NUMERIC,0.0::NUMERIC)) + 5.0::NUMERIC)::NUMERIC';
956         my $pop_desc = $desc eq 'ASC' ? 'DESC' : 'ASC';
957         $pop_extra_sort = "3 $pop_desc $nullpos,";
958     } else {
959         # default to rel ranking
960         $rank = "1.0/($rel)::NUMERIC";
961     }
962
963     my $key = 'm.source';
964     $key = 'm.metarecord' if (grep {$_->name eq 'metarecord' or $_->name eq 'metabib'} @{$self->modifiers});
965
966     my $core_limit = $self->QueryParser->core_limit || 'NULL';
967     if ($self->find_modifier('lucky')) {
968         $filters{check_limit} = 1;
969         $filters{skip_check} = 0;
970         $core_limit = 1;
971     }
972
973
974     my $flat_where = $$flat_plan{where};
975     if ($flat_where ne '') {
976         $flat_where = "AND (\n" . ${spc} x 5 . $flat_where . "\n" . ${spc} x 4 . ")";
977     }
978
979     my $final_c_attr_test;
980     my $c_attr_join = '';
981     my $c_vis_test = '';
982     my $pc_vis_test = '';
983
984     # copy visibility testing
985     if (!$self->find_modifier('staff')) {
986         $pc_vis_test = "c_attrs";
987         $c_attr_join = ",c_attr"
988     }
989
990     if ($self->find_modifier('available')) {
991         push @{$$flat_plan{vis_filter}{'c_attr'}},
992             "search.calculate_visibility_attribute_test('status','{0,7,12}')";
993     }
994
995     if (@{$$flat_plan{vis_filter}{c_attr}}) {
996         $c_vis_test = join(",",@{$$flat_plan{vis_filter}{c_attr}});
997         $c_attr_join = ',c_attr';
998     }
999
1000     if ($c_vis_test or $pc_vis_test) {
1001         my $vis_test = '';
1002
1003         if ($c_vis_test and $pc_vis_test) {
1004             $vis_test = $pc_vis_test . ",". $c_vis_test;
1005         } elsif ($pc_vis_test) {
1006             $vis_test = $pc_vis_test;
1007         } else {
1008             $vis_test = $c_vis_test;
1009         }
1010
1011         # WITH-clause just generates vis test
1012         $$flat_plan{with} .= "\n," if $$flat_plan{with};
1013         $$flat_plan{with} .= "c_attr AS (SELECT (ARRAY_TO_STRING(ARRAY[$vis_test],'&'))::query_int AS vis_test FROM asset.patron_default_visibility_mask() x)";
1014
1015         $final_c_attr_test = 'EXISTS (SELECT 1 FROM asset.copy_vis_attr_cache WHERE record = m.source AND vis_attr_vector @@ c_attr.vis_test)';
1016     }
1017  
1018     if ($self->find_modifier('staff')) { # staff search
1019         $final_c_attr_test ||= 'FALSE';
1020         $final_c_attr_test = '(' . $final_c_attr_test . " OR (" .
1021                 "NOT EXISTS (SELECT 1 FROM asset.copy_vis_attr_cache WHERE record = m.source) " .
1022                 "AND (bre.vis_attr_vector IS NULL OR NOT ( int4range(0,268435455,'[]') @> ANY(bre.vis_attr_vector) ))".
1023             "))";
1024         # We need bre here, regardless
1025         $bre_join ||= 'INNER JOIN biblio.record_entry bre ON m.source = bre.id';
1026     }
1027
1028     my $final_b_attr_test;
1029     my $b_attr_join = '';
1030     my $b_vis_test = '';
1031     my $pb_vis_test = '';
1032
1033     # bib visibility testing
1034     if (!$self->find_modifier('staff')) {
1035         $pb_vis_test = "b_attrs";
1036         $b_attr_join = ",b_attr"
1037     }
1038
1039     if (@{$$flat_plan{vis_filter}{b_attr}}) {
1040         $b_attr_join = ',b_attr ';
1041         $b_vis_test = join("||'&'||",@{$$flat_plan{vis_filter}{b_attr}});
1042     }
1043
1044     # bib vis tests are handled a little bit differently, as they're simpler but need special handling
1045     if ($b_vis_test or $pb_vis_test) {
1046         my $vis_test = '';
1047
1048         if ($b_vis_test and $pb_vis_test) { # $pb_vis_test supplies a query_int operator at its end
1049             $vis_test = $pb_vis_test . '||'. $b_vis_test;
1050         } elsif ($pb_vis_test) { # here we want to remove it
1051             $vis_test = "RTRIM($pb_vis_test,'|&')";
1052         } else {
1053             $vis_test = $b_vis_test;
1054         }
1055
1056         # WITH-clause just generates vis test
1057         $$flat_plan{with} .= "\n," if $$flat_plan{with};
1058         $$flat_plan{with} .= "b_attr AS (SELECT ($vis_test)::query_int AS vis_test FROM asset.patron_default_visibility_mask() x)";
1059
1060         # These are magic numbers... see: search.calculate_visibility_attribute() UDF
1061         $final_b_attr_test = '(b_attr.vis_test IS NULL OR bre.vis_attr_vector @@ b_attr.vis_test)';
1062     }
1063
1064     if ($final_c_attr_test or $final_b_attr_test) { # something...
1065         if ($final_c_attr_test and $final_b_attr_test) { # both!
1066             my $plan = "($final_c_attr_test) OR ($final_b_attr_test)";
1067             $flat_where .= "\n" . ${spc} x 4 . "AND (\n" . ${spc} x 5 .  $plan .  "\n" . ${spc} x 4 . ")";
1068         } elsif ($final_c_attr_test) { # just copies...
1069             $flat_where .= "\n" . ${spc} x 4 . "AND (\n" . ${spc} x 5 .  $final_c_attr_test .  "\n" . ${spc} x 4 . ")";
1070         } else { # just bibs...
1071             $flat_where .= "\n" . ${spc} x 4 . "AND (\n" . ${spc} x 5 .  $final_b_attr_test .  "\n" . ${spc} x 4 . ")";
1072         }
1073     }
1074
1075     my $with = $$flat_plan{with};
1076     $with= "\nWITH $with" if $with;
1077
1078     # Need an array for query parser db function; this gives a better plan
1079     # than the ARRAY_AGG(DISTINCT m.source) option as of PostgreSQL 9.1
1080     my $agg_records = 'ARRAY[m.source] AS records';
1081     if ($key =~ /metarecord/) {
1082         # metarecord searches still require the ARRAY_AGG approach
1083         $agg_records = 'ARRAY_AGG(DISTINCT m.source) AS records';
1084     }
1085
1086     my $sql = <<SQL;
1087 WITH w AS (
1088
1089 $with
1090 SELECT  id,
1091         rel,
1092         CASE WHEN cardinality(records) = 1 THEN records[1] ELSE NULL END AS record,
1093         NULL::INT AS total,
1094         NULL::INT AS checked,
1095         NULL::INT AS visible,
1096         NULL::INT AS deleted,
1097         NULL::INT AS excluded,
1098         badges,
1099         popularity
1100   FROM  (SELECT $key AS id,
1101                 $agg_records,
1102                 ${rel}::NUMERIC AS rel,
1103                 $rank AS rank, 
1104                 FIRST(pubdate_t.value) AS tie_break,
1105                 STRING_AGG(ARRAY_TO_STRING(pop_with.badges,','),',') AS badges,
1106                 AVG(COALESCE(pop_with.total_score::NUMERIC,0.0::NUMERIC))::NUMERIC(2,1) AS popularity
1107           FROM  metabib.metarecord_source_map m
1108                 $$flat_plan{from}
1109                 $mra_join
1110                 $mrv_join
1111                 $bre_join
1112                 $pop_join
1113                 $pubdate_join
1114                 $lang_join
1115                 $c_attr_join
1116                 $b_attr_join
1117           WHERE 1=1
1118                 $flat_where
1119           GROUP BY 1
1120           ORDER BY 4 $desc $nullpos, $pop_extra_sort 5 DESC $nullpos, 3 DESC
1121           LIMIT $core_limit
1122         ) AS core_query
1123 ) (SELECT * FROM w LIMIT $filters{check_limit} OFFSET $filters{skip_check})
1124         UNION ALL
1125   SELECT NULL,NULL,NULL,COUNT(*),COUNT(*),COUNT(*),0,0,NULL,NULL FROM w;
1126 SQL
1127
1128     warn $sql if $self->QueryParser->debug;
1129     return $sql;
1130
1131 }
1132
1133 sub is_org_visible {
1134     my $org = shift;
1135     return 0 if (!$U->is_true($org->opac_visible));
1136
1137     my $non_inherited_vis_gf = shift || $U->get_global_flag('opac.org_unit.non_inherited_visibility');
1138     return 1 if ($U->is_true($non_inherited_vis_gf->enabled));
1139
1140     my $ot = $U->get_org_tree;
1141     while ($org = $U->find_org($ot,$org->parent_ou)) {
1142         return 0 if (!$U->is_true($org->opac_visible));
1143     }
1144     return 1;
1145 }
1146
1147 sub flatten {
1148     my $self = shift;
1149
1150     die 'ERROR: nesting too deep or boolean list too long' if ($self->plan_level > 40);
1151
1152     my $from = shift || '';
1153     my $where = shift || '';
1154     my $with = '';
1155     my %vis_filter = ( c_attr => [], b_attr => [] );
1156     my $uses_bre = 0;
1157     my $uses_mrd = 0;
1158     my $uses_mrv = 0;
1159
1160     my @rank_list;
1161     for my $node ( @{$self->query_nodes} ) {
1162
1163         if (ref($node)) {
1164             if ($node->isa( 'QueryParser::query_plan::node' )) {
1165
1166                 unless (@{$node->only_atoms}) {
1167                     push @rank_list, '1';
1168                     $where .= 'TRUE';
1169                     next;
1170                 }
1171
1172                 my $table = $node->table;
1173                 my $ctable = $node->combined_table;
1174                 my $talias = $node->table_alias;
1175
1176                 my $node_rank = 'COALESCE(' . $node->rank . " * ${talias}.weight, 0.0)";
1177
1178                 $from .= "\n" . ${spc} x 4 ."LEFT JOIN (\n"
1179                       . ${spc} x 5 . "SELECT fe.*, fe_weight.weight, ${talias}_xq.tsq, ${talias}_xq.tsq_rank /* search */\n"
1180                       . ${spc} x 6 . "FROM  $table AS fe";
1181                 $from .= "\n" . ${spc} x 7 . "JOIN config.metabib_field AS fe_weight ON (fe_weight.id = fe.field)";
1182
1183                 my @bump_fields;
1184                 my @field_ids;
1185                 if (@{$node->fields} > 0) {
1186                     @bump_fields = @{$node->fields};
1187
1188                     @field_ids = grep defined, (
1189                         map {
1190                             $self->QueryParser->search_field_ids_by_class(
1191                                 $node->classname, $_
1192                             )->[0]
1193                         } @bump_fields
1194                     );
1195                 } else {
1196                     @bump_fields = @{$self->QueryParser->search_fields->{$node->classname}};
1197                 }
1198
1199                 if ($node->dummy_count < @{$node->only_atoms} ) {
1200                     $with .= ",\n     " if $with;
1201                     $with .= "${talias}_xq AS (SELECT ". $node->tsquery ." AS tsq,". $node->tsquery_rank ." AS tsq_rank )";
1202                     if ($node->combined_search) {
1203                         $from .= "\n" . ${spc} x 6 . "JOIN $ctable AS com ON (com.record = fe.source";
1204                         if (@field_ids) {
1205                             $from .= " AND com.metabib_field IN (" . join(',',@field_ids) . "))";
1206                         } else {
1207                             $from .= " AND com.metabib_field IS NULL)";
1208                         }
1209                         $from .= "\n" . ${spc} x 6 . "JOIN ${talias}_xq ON (com.index_vector @@ ${talias}_xq.tsq)";
1210                     } else {
1211                         $from .= "\n" . ${spc} x 6 . "JOIN ${talias}_xq ON (fe.index_vector @@ ${talias}_xq.tsq)";
1212                     }
1213                 } else {
1214                     $from .= "\n" . ${spc} x 6 . ", (SELECT NULL::tsquery AS tsq, NULL:tsquery AS tsq_rank ) AS ${talias}_xq";
1215                 }
1216
1217                 if (@field_ids) {
1218                     $from .= "\n" . ${spc} x 6 . "WHERE fe_weight.id IN  (" .
1219                         join(',', @field_ids) . ")";
1220                 }
1221
1222                 $from .= "\n" . ${spc} x 4 . ") AS $talias ON (m.source = ${talias}.source)";
1223
1224                 my %used_bumps;
1225                 my @bumps;
1226                 my @bumpmults;
1227                 for my $field ( @bump_fields ) {
1228                     my $bumps = $self->QueryParser->find_relevance_bumps( $node->classname => $field );
1229                     for my $b (keys %$bumps) {
1230                         next if (!$$bumps{$b}{active});
1231                         next if ($used_bumps{$b});
1232                         $used_bumps{$b} = 1;
1233
1234                         next if ($$bumps{$b}{multiplier} == 1); # optimization to remove unneeded bumps
1235                         push @bumps, $b;
1236                         push @bumpmults, $$bumps{$b}{multiplier};
1237                     }
1238                 }
1239
1240                 if(scalar @bumps > 0 && scalar @{$node->only_positive_atoms} > 0) {
1241                     # Note: Previous rank function used search_normalize outright. Duplicating that here.
1242                     $node_rank .= "\n" . ${spc} x 5 . "* evergreen.rel_bump(('{' || quote_literal(search_normalize(";
1243                     $node_rank .= join(")) || ',' || quote_literal(search_normalize(",map { $self->QueryParser->quote_phrase_value($_->content) } @{$node->only_positive_atoms});
1244                     $node_rank .= ")) || '}')::TEXT[], " . $node->table_alias . ".value, '{" . join(",",@bumps) . "}'::TEXT[], '{" . join(",",@bumpmults) . "}'::NUMERIC[])";
1245                 }
1246
1247                 my $NOT = '';
1248                 $NOT = 'NOT ' if $node->negate;
1249
1250                 $where .= "$NOT(" . $talias . ".id IS NOT NULL";
1251                 if (@{$node->phrases}) {
1252                     $where .= ' AND ' . join(' AND ', map {
1253                         "${talias}.value ~* ".$self->QueryParser->quote_phrase_value($_, 1)
1254                     } @{$node->phrases});
1255                 } else {
1256                     for my $atom (@{$node->only_real_atoms}) {
1257                         next unless $atom->{content} && $atom->{content} =~ /(^\^|\$$)/;
1258                         $where .= " AND ${talias}.value ~* ".$self->QueryParser->quote_phrase_value($atom->{content});
1259                     }
1260                 }
1261                 $where .= ')';
1262
1263                 push @rank_list, $node_rank;
1264
1265             } elsif ($node->isa( 'QueryParser::query_plan::facet' )) {
1266
1267                 my $talias = $node->table_alias;
1268
1269                 my @field_ids;
1270                 if (@{$node->fields} > 0) {
1271                     push(@field_ids, $self->QueryParser->facet_field_ids_by_class( $node->classname, $_ )->[0]) for (@{$node->fields});
1272                 } else {
1273                     @field_ids = @{ $self->QueryParser->facet_field_ids_by_class( $node->classname ) };
1274                 }
1275
1276                 my $join_type = ($node->negate or !$self->top_plan) ? 'LEFT' : 'INNER';
1277                 $from .= "\n${spc}$join_type JOIN /* facet */ metabib.facet_entry $talias ON (\n"
1278                       . ${spc} x 2 . "m.source = ${talias}.source\n"
1279                       . ${spc} x 2 . "AND SUBSTRING(${talias}.value,1,1024) IN ("
1280                       . join(",", map { $self->QueryParser->quote_value($_) } @{$node->values}) . ")\n"
1281                       . ${spc} x 2 ."AND ${talias}.field IN (". join(',', @field_ids) . ")\n"
1282                       . "${spc})";
1283
1284                 if ($join_type ne 'INNER') {
1285                     my $NOT = $node->negate ? '' : ' NOT';
1286                     $where .= "${talias}.id IS$NOT NULL";
1287                 } elsif ($where ne '') {
1288                     # Strip extra joiner
1289                     $where =~ s/(\s|\n)+(AND|OR)\s$//;
1290                 }
1291
1292             } else {
1293                 my $subnode = $node->flatten;
1294
1295                 # strip the trailing bool from the previous loop if there is 
1296                 # nothing to add to the where within this loop.
1297                 if ($$subnode{where} eq '') {
1298                     $where =~ s/(\s|\n)+(AND|OR)\s$//;
1299                 }
1300
1301                 push(@rank_list, @{$$subnode{rank_list}});
1302                 $from .= $$subnode{from};
1303
1304                 my $NOT = '';
1305                 $NOT = 'NOT ' if $node->negate;
1306
1307                 if ($$subnode{where} ne '') {
1308                     $where .= "$NOT(\n"
1309                            . ${spc} x ($self->plan_level + 6) . $$subnode{where} . "\n"
1310                            . ${spc} x ($self->plan_level + 5) . ')';
1311                 }
1312
1313                 if ($$subnode{with}) {
1314                     $with .= ",\n     " if $with;
1315                     $with .= $$subnode{with};
1316                 }
1317
1318                 $uses_bre = $$subnode{uses_bre};
1319                 $uses_mrd = $$subnode{uses_mrd};
1320                 $uses_mrv = $$subnode{uses_mrv};
1321             }
1322         } else {
1323
1324             warn "flatten(): appending WHERE bool to: $where\n" if $self->QueryParser->debug;
1325
1326             if ($where ne '') {
1327                 $where .= "\n" . ${spc} x ( $self->plan_level + 5 ) . 'AND ' if ($node eq '&');
1328                 $where .= "\n" . ${spc} x ( $self->plan_level + 5 ) . 'OR ' if ($node eq '|');
1329             }
1330         }
1331     }
1332
1333     my $joiner = "\n" . ${spc} x ( $self->plan_level + 5 ) . ($self->joiner eq '&' ? 'AND ' : 'OR ');
1334
1335     my ($depth_filter) = grep { $_->name eq 'depth' } @{$self->filters};
1336     if ($depth_filter and @{$depth_filter->args} == 1) {
1337         $depth_filter = $depth_filter->args->[0];
1338     }
1339
1340     my $ot = $U->get_org_tree;
1341     my $site_org = $ot;
1342     my $negate = 'FALSE';
1343
1344     my ($site_filter) = grep { $_->name eq 'site' } @{$self->filters};
1345     if ($site_filter and @{$site_filter->args} == 1) {
1346        $negate = $site_filter->negate ? 'TRUE' : 'FALSE';
1347
1348        my $sitename = $site_filter->args->[0];
1349        $site_org = $U->find_org_by_shortname($ot, $sitename) || $ot;
1350     }
1351
1352     my $dorgs = $U->get_org_descendants($site_org->id, $depth_filter);
1353     my $aorgs = $U->get_org_ancestors($site_org->id);
1354
1355     if (!$self->find_modifier('staff')) {
1356         my $non_inherited_vis_gf = $U->get_global_flag('opac.org_unit.non_inherited_visibility');
1357         $dorgs = [ grep { is_org_visible($U->find_org($ot,$_), $non_inherited_vis_gf) } @$dorgs ];
1358         $aorgs = [ grep { is_org_visible($U->find_org($ot,$_), $non_inherited_vis_gf) } @$aorgs ];
1359     }
1360
1361     push @{$vis_filter{'c_attr'}},
1362         "search.calculate_visibility_attribute_test('circ_lib','{".join(',', @$dorgs)."}',$negate)";
1363
1364     my $lorgs = [@$aorgs];
1365     my $luri_as_copy_gf = $U->get_global_flag('opac.located_uri.act_as_copy');
1366     push @$lorgs, @$dorgs if ($luri_as_copy_gf and $U->is_true($luri_as_copy_gf->enabled));
1367
1368     $uses_bre = 1;
1369     push @{$vis_filter{'b_attr'}},
1370         "search.calculate_visibility_attribute_test('luri_org','{".join(',', @$lorgs)."}',$negate)";
1371
1372     my @dlist = ();
1373     my $common = 0;
1374     # for each dynamic filter, build more of the WHERE clause
1375     for my $filter (@{$self->filters}) {
1376         my $NOT = $filter->negate ? 'NOT ' : '';
1377         if (grep { $_ eq $filter->name } @{ $self->QueryParser->dynamic_filters }) {
1378
1379             my $fname = $filter->name;
1380             $fname = 'item_lang' if $fname eq 'language'; #XXX filter aliases 
1381
1382             warn "flatten(): processing dynamic filter ". $filter->name ."\n"
1383                 if $self->QueryParser->debug;
1384
1385             my $vlist_query;
1386             ($vlist_query, $common) = $self->dynamic_filter_compile( $fname, $filter->args, $filter->negate );
1387
1388             # bool joiner for intra-plan nodes/filters
1389             push(@dlist, $self->joiner) if @dlist;
1390             push(@dlist, $vlist_query);
1391             $uses_mrv = 1;
1392         } else {
1393             if ($filter->name eq 'before') {
1394                 if (@{$filter->args} == 1) {
1395                     $where .= $joiner if $where ne '';
1396                     $where .= "${NOT}COALESCE(pubdate_t.value <= "
1397                            . $self->QueryParser->quote_value($filter->args->[0])
1398                            . ", false)";
1399                 }
1400             } elsif ($filter->name eq 'after') {
1401                 if (@{$filter->args} == 1) {
1402                     $where .= $joiner if $where ne '';
1403                     $where .= "${NOT}COALESCE(pubdate_t.value >= "
1404                            . $self->QueryParser->quote_value($filter->args->[0])
1405                            . ", false)";
1406                 }
1407             } elsif ($filter->name eq 'during') {
1408                 if (@{$filter->args} == 1) {
1409                     $where .= $joiner if $where ne '';
1410                     $where .= "${NOT}COALESCE("
1411                            . $self->QueryParser->quote_value($filter->args->[0])
1412                            . " BETWEEN pubdate_t.value AND (mrd.attrs->'date2'), false)";
1413                     $uses_mrd = 1;
1414                 }
1415             } elsif ($filter->name eq 'between') {
1416                 if (@{$filter->args} == 2) {
1417                     $where .= $joiner if $where ne '';
1418                     $where .= "${NOT}COALESCE(pubdate_t.value BETWEEN "
1419                            . $self->QueryParser->quote_value($filter->args->[0])
1420                            . " AND "
1421                            . $self->QueryParser->quote_value($filter->args->[1])
1422                            . ", false)";
1423                 }
1424             } elsif ($filter->name eq 'container') {
1425                 if (@{$filter->args} >= 3) {
1426                     my ($class, $ctype, $cid, $token) = @{$filter->args};
1427                     my $perm_join = '';
1428                     my $rec_join = '';
1429                     my $rec_field = 'ci.target_biblio_record_entry';
1430                     if ($class eq 'bre') {
1431                         $class = 'biblio_record_entry';
1432                     } elsif ($class eq 'acn') {
1433                         $class = 'call_number';
1434                         $rec_field = 'cn.record';
1435                         $rec_join = 'JOIN asset.call_number cn ON (ci.target_call_number = cn.id)';
1436                     } elsif ($class eq 'acp') {
1437                         $class = 'copy';
1438                         $rec_field = 'cn.record';
1439                         $rec_join = 'JOIN asset.copy cp ON (ci.target_copy = cp.id) JOIN asset.call_number cn ON (cp.call_number = cn.id)';
1440                     } else {
1441                         $class = undef;
1442                     }
1443
1444                     if ($class) {
1445                         my ($u,$e) = $apputils->checksesperm($token) if ($token);
1446                         $perm_join = ' OR c.owner = ' . $u->id if ($u && !$e);
1447
1448                         my $filter_alias = "$filter";
1449                         $filter_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1450                         $filter_alias =~ s/\|/_/go;
1451
1452                         $with .= ",\n     " if $with;
1453                         $with .= "container_${filter_alias} AS (\n";
1454                         $with .= "       SELECT $rec_field AS record FROM container.${class}_bucket_item ci\n"
1455                                . "             JOIN container.${class}_bucket c ON (c.id = ci.bucket) $rec_join\n"
1456                                . "       WHERE c.btype = " . $self->QueryParser->quote_value($ctype) . "\n"
1457                                . "             AND c.id = " . $self->QueryParser->quote_value($cid) . "\n"
1458                                . "             AND (c.pub IS TRUE$perm_join)\n";
1459                         if ($class eq 'copy') {
1460                             $with .= "       UNION\n"
1461                                    . "       SELECT pr.peer_record AS record FROM container.copy_bucket_item ci\n"
1462                                    . "             JOIN container.copy_bucket c ON (c.id = ci.bucket)\n"
1463                                    . "             JOIN biblio.peer_bib_copy_map pr ON ci.target_copy = pr.target_copy\n"
1464                                    . "       WHERE c.btype = " . $self->QueryParser->quote_value($ctype) . "\n"
1465                                    . "             AND c.id = " . $self->QueryParser->quote_value($cid) . "\n"
1466                                    . "             AND (c.pub IS TRUE$perm_join)\n";
1467                         }
1468                         $with .= "     )";
1469
1470                         my $optimize_join = 1 if $self->top_plan and !$NOT;
1471                         $from .= "\n" . ${spc} x 3 . ( $optimize_join ? 'INNER' : 'LEFT') . " JOIN container_${filter_alias} ON container_${filter_alias}.record = m.source";
1472
1473                         if (!$optimize_join) {
1474                             $where .= $joiner if $where ne '';
1475                             $where .= "(container_${filter_alias} IS " . ( $NOT ? 'NULL)' : 'NOT NULL)');
1476                         }
1477                     }
1478                 }
1479             } elsif ($filter->name eq 'copy_tag') {
1480                 my $valid_copy_tag_search = 0;
1481                 my $copy_tag_type;
1482                 my $tag_value;
1483                 if (@{$filter->args} >= 2) { # must have at least two parts, tag (or *) and terms
1484                     my @fargs = @{$filter->args};
1485                     $copy_tag_type = shift(@fargs);
1486                     $tag_value = join(' ', @fargs);
1487                     $valid_copy_tag_search = 1;
1488                 }
1489                 if ($valid_copy_tag_search) {
1490                     my $norm_value = search_normalize($tag_value);
1491                     my @tokens = split /\s+/, $norm_value;
1492                     
1493                     my $filter_alias = "$filter";
1494                     $filter_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1495                     $filter_alias =~ s/\|/_/go;
1496
1497                     $with .= ",\n     " if $with;
1498                     $with .= "copy_tag_${filter_alias} AS (\n";
1499                     $with .= "       SELECT cn.record AS record FROM config.copy_tag_type cctt\n";
1500                     $with .= "             JOIN asset.copy_tag acpt ON (cctt.code = acpt.tag_type)\n";
1501                     $with .= "             JOIN asset.copy_tag_copy_map acptcm ON (acpt.id = acptcm.tag)\n";
1502                     $with .= "             JOIN asset.copy cp ON (acptcm.copy = cp.id)\n";
1503                     $with .= "             JOIN asset.call_number cn ON (cp.call_number = cn.id)\n";
1504                     $with .= "       WHERE 1 = 1 \n";
1505                     if ($copy_tag_type ne '*') {
1506                         $with .= "             AND cctt.code = " . $self->QueryParser->quote_value($copy_tag_type) . "\n";
1507                     }
1508                     if (@tokens) {
1509                         $with .= '             AND acpt.value @@ to_tsquery(' . $self->QueryParser->quote_value(join(' & ', @tokens)) . ")\n";
1510                     }
1511                     if (!$self->find_modifier('staff')) {
1512                         $with .= "             AND acpt.pub IS TRUE\n";
1513                     }
1514                     $with .= "     )";
1515
1516                     my $optimize_join = 1 if $self->top_plan and !$NOT;
1517                     $from .= "\n" . ${spc} x 3 . ( $optimize_join ? 'INNER' : 'LEFT') . " JOIN copy_tag_${filter_alias} ON copy_tag_${filter_alias}.record = m.source";
1518
1519                     if (!$optimize_join) {
1520                         $where .= $joiner if $where ne '';
1521                         $where .= "(copy_tag_${filter_alias} IS " . ( $NOT ? 'NULL)' : 'NOT NULL)');
1522                     }
1523                 }
1524             } elsif ($filter->name eq 'record_list') {
1525                 if (@{$filter->args} > 0) {
1526                     my $key = 'm.source';
1527                     $key = 'm.metarecord' if (grep {$_->name eq 'metarecord' or $_->name eq 'metabib'} @{$self->QueryParser->parse_tree->modifiers});
1528                     $where .= $joiner if $where ne '';
1529                     $where .= "$key ${NOT}IN (" . join(',', map { $self->QueryParser->quote_value($_) } @{$filter->args}) . ')';
1530                 }
1531
1532             } elsif ($filter->name eq 'locations') {
1533                 if (@{$filter->args} > 0) {
1534                     my $negate = $filter->negate ? 'TRUE' : 'FALSE';
1535                     my $filter_args = join(",", map(int, @{$filter->args}));
1536                     push @{$vis_filter{'c_attr'}},
1537                         "search.calculate_visibility_attribute_test('location',$filter_args,$negate)";
1538                 }
1539
1540             } elsif ($filter->name eq 'location_groups') {
1541                 if (@{$filter->args} > 0) {
1542                     my $negate = $filter->negate ? 'TRUE' : 'FALSE';
1543                     my $filter_args = join(",", map(int, @{$filter->args}));
1544                     push @{$vis_filter{'c_attr'}},
1545                         "search.calculate_visibility_attribute_test('location',(SELECT ARRAY_AGG(location) FROM asset.copy_location_group_map WHERE lgroup IN ($filter_args)),$negate)";
1546                 }
1547
1548             } elsif ($filter->name eq 'statuses') {
1549                 if (@{$filter->args} > 0) {
1550                     my $negate = $filter->negate ? 'TRUE' : 'FALSE';
1551                     push @{$vis_filter{'c_attr'}},
1552                         "search.calculate_visibility_attribute_test('status','{".join(',', @{$filter->args})."}',$negate)";
1553                 }
1554
1555             } elsif ($filter->name eq 'has_browse_entry') {
1556                 if (@{$filter->args} >= 2) {
1557                     my $entry = int(shift @{$filter->args});
1558                     my $fields = join(",", map(int, @{$filter->args}));
1559                     $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);
1560                 }
1561             } elsif ($filter->name eq 'edit_date' or $filter->name eq 'create_date') {
1562                 # bre.create_date and bre.edit_date filtering
1563                 my $datefilter = $filter->name;
1564
1565                 $uses_bre = 1;
1566
1567                 if ($filter && $filter->args && scalar(@{$filter->args}) > 0 && scalar(@{$filter->args}) < 3) {
1568                     my ($cstart, $cend) = @{$filter->args};
1569         
1570                     if (!$cstart and !$cend) {
1571                         # useless use of filter
1572                     } elsif (!$cstart or $cstart eq '-infinity') { # no start supplied
1573                         if ($cend eq 'infinity') {
1574                             # useless use of filter
1575                         } else {
1576                             # "before $cend"
1577                             $cend = cleanse_ISO8601($cend);
1578                             $where .= $joiner if $where ne '';
1579                             $where .= "bre.$datefilter <= \$_$$\$$cend\$_$$\$";
1580                         }
1581             
1582                     } elsif (!$cend or $cend eq 'infinity') { # no end supplied
1583                         if ($cstart eq '-infinity') {
1584                             # useless use of filter
1585                         } else { # "after $cstart"
1586                             $cstart = cleanse_ISO8601($cstart);
1587                             $where .= $joiner if $where ne '';
1588                             $where .= "bre.$datefilter >= \$_$$\$$cstart\$_$$\$";
1589                         }
1590                     } else { # both supplied
1591                         # "between $cstart and $cend"
1592                         $cstart = cleanse_ISO8601($cstart);
1593                         $cend = cleanse_ISO8601($cend);
1594                         $where .= $joiner if $where ne '';
1595                         $where .= "bre.$datefilter BETWEEN \$_$$\$$cstart\$_$$\$ AND \$_$$\$$cend\$_$$\$";
1596                     }
1597                 }
1598             } elsif ($filter->name eq 'bib_source') {
1599                 if (@{$filter->args} > 0) {
1600                     $uses_bre = 1;
1601                     my $negate = $filter->negate ? 'TRUE' : 'FALSE';
1602                     push @{$vis_filter{'b_attr'}},
1603                         "search.calculate_visibility_attribute_test('source','{".join(',', @{$filter->args})."}',$negate)";
1604                 }
1605             } elsif ($filter->name eq 'from_metarecord') {
1606                 if (@{$filter->args} > 0) {
1607                     my $key = 'm.metarecord';
1608                     $where .= $joiner if $where ne '';
1609                     $where .= "$key ${NOT}IN (" . join(',', map { $self->QueryParser->quote_value($_) } @{$filter->args}) . ')';
1610                 }
1611             }
1612         }
1613     }
1614
1615     if (@dlist) {
1616
1617         $where .= $joiner if $where ne '';
1618         if ($common) { # Use a function wrapper to inform PG of the non-rareness of one or more filter elements
1619             $where .= sprintf(
1620                 'evergreen.query_int_wrapper(mrv.vlist, \'%s\')',
1621                 join('', @dlist)
1622             );
1623         } else {
1624             $where .= sprintf(
1625                 'mrv.vlist @@ \'%s\'',
1626                 join('', @dlist)
1627             );
1628         }
1629     }
1630
1631     warn "flatten(): full filter where => $where\n" if $self->QueryParser->debug;
1632
1633     return {
1634         rank_list => \@rank_list,
1635         from => $from,
1636         where => $where,
1637         with => $with,
1638         vis_filter => \%vis_filter,
1639         uses_bre => $uses_bre,
1640         uses_mrv => $uses_mrv,
1641         uses_mrd => $uses_mrd
1642     };
1643 }
1644
1645
1646 #-------------------------------
1647 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::filter;
1648 use base 'QueryParser::query_plan::filter';
1649
1650 #-------------------------------
1651 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::facet;
1652 use base 'QueryParser::query_plan::facet';
1653
1654 sub classname {
1655     my $self = shift;
1656     my ($classname) = split '\|', $self->name;
1657     return $classname;
1658 }
1659
1660 sub fields {
1661     my $self = shift;
1662     my ($classname,@fields) = split '\|', $self->name;
1663     return \@fields;
1664 }
1665
1666 sub table_alias {
1667     my $self = shift;
1668
1669     my $table_alias = "$self";
1670     $table_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1671     $table_alias .= '_' . $self->name;
1672     $table_alias =~ s/\|/_/go;
1673
1674     return $table_alias;
1675 }
1676
1677
1678 #-------------------------------
1679 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::modifier;
1680 use base 'QueryParser::query_plan::modifier';
1681
1682 #-------------------------------
1683 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::node::atom;
1684 use base 'QueryParser::query_plan::node::atom';
1685
1686 sub sql {
1687     my $self = shift;
1688     my $sql = shift;
1689
1690     $self->{sql} = $sql if ($sql);
1691
1692     return $self->{sql} if ($self->{sql});
1693     return $self->buildSQL;
1694 }
1695
1696 sub buildSQL {
1697     my $self = shift;
1698
1699     my $classname = $self->node->classname;
1700
1701     return $self->sql("to_tsquery('$classname','')") if $self->{dummy};
1702
1703     my $normalizers = $self->node->plan->QueryParser->query_normalizers( $classname );
1704     my $fields = $self->node->fields;
1705
1706     my $lang;
1707     my $filter = $self->node->plan->find_filter('preferred_language');
1708     $lang ||= $filter->args->[0] if ($filter && $filter->args);
1709     $lang ||= $self->node->plan->QueryParser->default_preferred_language;
1710     my $ts_configs = [];
1711
1712     if (@{$self->node->phrases}) {
1713         # We assume we want 'simple' for phrases. Gives us less to match against later.
1714         $ts_configs = ['simple'];
1715     } else {
1716         if (!@$fields) {
1717             $ts_configs = $self->node->plan->QueryParser->class_ts_config($classname, $lang);
1718         } else {
1719             for my $field (@$fields) {
1720                 push @$ts_configs, @{$self->node->plan->QueryParser->field_ts_config($classname, $field, $lang)};
1721             }
1722         }
1723         $ts_configs = [keys %{{map { $_ => 1 } @$ts_configs}}];
1724     }
1725
1726     # Assume we want exact if none otherwise provided.
1727     # Because we can reasonably expect this to exist
1728     $ts_configs = ['simple'] unless (scalar @$ts_configs);
1729
1730     $fields = $self->node->plan->QueryParser->search_fields->{$classname} if (!@$fields);
1731
1732     my %norms;
1733     my $pos = 0;
1734     for my $field (@$fields) {
1735         for my $nfield (keys %$normalizers) {
1736             for my $nizer ( @{$$normalizers{$nfield}} ) {
1737                 if ($field eq $nfield) {
1738                     my $param_string = OpenSRF::Utils::JSON->perl2JSON($nizer->{params});
1739                     if (!exists($norms{$nizer->{function}.$param_string})) {
1740                         $norms{$nizer->{function}.$param_string} = {p=>$pos++,n=>$nizer};
1741                     }
1742                 }
1743             }
1744         }
1745     }
1746
1747     my $sql = $self->node->plan->QueryParser->quote_value($self->content);
1748
1749     for my $n ( map { $$_{n} } sort { $$a{p} <=> $$b{p} } values %norms ) {
1750         $sql = join(', ', $sql, map { $self->node->plan->QueryParser->quote_value($_) } @{ $n->{params} });
1751         $sql = $n->{function}."($sql)";
1752     }
1753
1754     my $prefix = $self->prefix || '';
1755     my $suffix = $self->suffix || '';
1756     my $joiner = ' || ';
1757     $joiner = ' && ' if $self->prefix eq '!'; # Negative atoms should be "none of the variants" instead of "any of the variants"
1758
1759     $prefix = "'$prefix' ||" if $prefix;
1760     my $suffix_op = '';
1761     my $suffix_after = '';
1762
1763     $suffix_op = ":$suffix" if $suffix;
1764     $suffix_after = "|| '$suffix_op'" if $suffix;
1765
1766     my @sql_set = ();
1767     for my $ts_config (@$ts_configs) {
1768         push @sql_set, "to_tsquery('$ts_config', COALESCE(NULLIF($prefix '(' || btrim(regexp_replace($sql,E'(?:\\\\s+|:)','$suffix_op&','g'),'&|') $suffix_after || ')', '()'), ''))";
1769     }
1770
1771     $sql = join($joiner, @sql_set);
1772     $sql = '(' . $sql . ')' if (scalar(@$ts_configs) > 1);
1773
1774     return $self->sql($sql);
1775 }
1776
1777 #-------------------------------
1778 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::node;
1779 use base 'QueryParser::query_plan::node';
1780
1781 sub only_atoms {
1782     my $self = shift;
1783
1784     $self->{dummy_count} = 0;
1785
1786     my $atoms = $self->query_atoms;
1787     my @only_atoms;
1788     for my $a (@$atoms) {
1789         push(@only_atoms, $a) if (ref($a) && $a->isa('QueryParser::query_plan::node::atom'));
1790         $self->{dummy_count}++ if (ref($a) && $a->{dummy});
1791     }
1792
1793     return \@only_atoms;
1794 }
1795
1796 sub only_real_atoms {
1797     my $self = shift;
1798
1799     my $atoms = $self->query_atoms;
1800     my @only_real_atoms;
1801     for my $a (@$atoms) {
1802         push(@only_real_atoms, $a) if (ref($a) && $a->isa('QueryParser::query_plan::node::atom') && !($a->{dummy}));
1803     }
1804
1805     return \@only_real_atoms;
1806 }
1807
1808 sub only_positive_atoms {
1809     my $self = shift;
1810
1811     my $atoms = $self->query_atoms;
1812     my @only_positive_atoms;
1813     for my $a (@$atoms) {
1814         push(@only_positive_atoms, $a) if (ref($a) && $a->isa('QueryParser::query_plan::node::atom') && !($a->{dummy}) && ($a->{prefix} ne '!'));
1815     }
1816
1817     return \@only_positive_atoms;
1818 }
1819
1820 sub dummy_count {
1821     my $self = shift;
1822     return $self->{dummy_count};
1823 }
1824
1825 sub table {
1826     my $self = shift;
1827     my $table = shift;
1828     $self->{table} = $table if ($table);
1829     return $self->{table} if $self->{table};
1830     return $self->table( 'metabib.' . $self->classname . '_field_entry' );
1831 }
1832
1833 sub combined_table {
1834     my $self = shift;
1835     my $ctable = shift;
1836     $self->{ctable} = $ctable if ($ctable);
1837     return $self->{ctable} if $self->{ctable};
1838     return $self->combined_table( 'metabib.combined_' . $self->classname . '_field_entry' );
1839 }
1840
1841 sub combined_search {
1842     my $self = shift;
1843     return $self->plan->QueryParser->search_class_combined($self->classname);
1844 }
1845
1846 sub table_alias {
1847     my $self = shift;
1848     my $table_alias = shift;
1849     $self->{table_alias} = $table_alias if ($table_alias);
1850     return $self->{table_alias} if ($self->{table_alias});
1851
1852     $table_alias = "$self";
1853     $table_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1854     $table_alias .= '_' . $self->requested_class;
1855     $table_alias =~ s/\|/_/go;
1856
1857     return $self->table_alias( $table_alias );
1858 }
1859
1860 sub tsquery {
1861     my $self = shift;
1862     return $self->{tsquery} if ($self->{tsquery});
1863
1864     for my $atom (@{$self->query_atoms}) {
1865         if (ref($atom)) {
1866             $self->{tsquery} .= "\n" . ${spc} x 3 . $atom->sql;
1867         } else {
1868             $self->{tsquery} .= $atom x 2;
1869         }
1870     }
1871
1872     return $self->{tsquery};
1873 }
1874
1875 sub tsquery_rank {
1876     my $self = shift;
1877     return $self->{tsquery_rank} if ($self->{tsquery_rank});
1878     my @atomlines;
1879
1880     for my $atom (@{$self->only_positive_atoms}) {
1881         push @atomlines, "\n" . ${spc} x 3 . $atom->sql;
1882     }
1883     $self->{tsquery_rank} = join(' ||', @atomlines);
1884     $self->{tsquery_rank} = 'NULL::tsquery' unless $self->{tsquery_rank};
1885     return $self->{tsquery_rank};
1886 }
1887
1888 sub rank {
1889     my $self = shift;
1890     return $self->{rank} if ($self->{rank});
1891
1892     my $rank_norm_map = $self->plan->QueryParser->custom_data->{rank_cd_weight_map};
1893
1894     my $cover_density = 0;
1895     for my $norm ( keys %$rank_norm_map) {
1896         $cover_density += $$rank_norm_map{$norm} if ($self->plan->QueryParser->parse_tree->find_modifier($norm));
1897     }
1898
1899     my $weights = join(', ', @{$self->plan->QueryParser->search_class_weights($self->classname)});
1900
1901     return $self->{rank} = "ts_rank_cd('{" . $weights . "}', " . $self->table_alias . '.index_vector, ' . $self->table_alias . ".tsq_rank, $cover_density)";
1902 }
1903
1904
1905 1;
1906