]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Storage/Driver/Pg/QueryParser.pm
LP#1698206: Eliminate Staged Search
[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_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         if (!$pc_vis_test) { # staff search
1017             $final_c_attr_test = '(' . $final_c_attr_test . ' OR NOT EXISTS (SELECT 1 FROM asset.copy_vis_attr_cache WHERE record = m.source))';
1018         }
1019     }
1020  
1021     my $final_b_attr_test;
1022     my $b_attr_join = '';
1023     my $b_vis_test = '';
1024     my $pb_vis_test = '';
1025
1026     # bib visibility testing
1027     if (!$self->find_modifier('staff')) {
1028         $pb_vis_test = "b_attrs";
1029         $b_attr_join = ",b_attr"
1030     }
1031
1032     if (@{$$flat_plan{vis_filter}{b_attr}}) {
1033         $b_attr_join = ',b_attr ';
1034         $b_vis_test = join("||'&'||",@{$$flat_plan{vis_filter}{b_attr}});
1035     }
1036
1037     if ($b_vis_test or $pb_vis_test) {
1038         my $vis_test = '';
1039
1040         if ($b_vis_test and $pb_vis_test) {
1041             $vis_test = $pb_vis_test . ",". $b_vis_test;
1042         } elsif ($pb_vis_test) {
1043             $vis_test = $pb_vis_test;
1044         } else {
1045             $vis_test = $b_vis_test;
1046         }
1047
1048         # WITH-clause just generates vis test
1049         $$flat_plan{with} .= "\n," if $$flat_plan{with};
1050         $$flat_plan{with} .= "b_attr AS (SELECT (ARRAY_TO_STRING(ARRAY[$vis_test],'&'))::query_int AS vis_test FROM asset.patron_default_visibility_mask() x)";
1051
1052         # These are magic numbers... see: search.calculate_visibility_attribute() UDF
1053         $final_b_attr_test = '(b_attr.vis_test IS NULL OR bre.vis_attr_vector @@ b_attr.vis_test)';
1054         if (!$pb_vis_test) { # staff search
1055             $final_b_attr_test .= " OR NOT ( int4range(0,268435455,'[]') @> ANY(bre.vis_attr_vector) )";
1056         }
1057     }
1058
1059     if ($final_c_attr_test or $final_b_attr_test) { # something...
1060         if ($final_c_attr_test and $final_b_attr_test) { # both!
1061             my $plan = "($final_c_attr_test) OR ($final_b_attr_test)";
1062             $flat_where .= "\n" . ${spc} x 4 . "AND (\n" . ${spc} x 5 .  $plan .  "\n" . ${spc} x 4 . ")";
1063         } elsif ($final_c_attr_test) { # just copies...
1064             $flat_where .= "\n" . ${spc} x 4 . "AND (\n" . ${spc} x 5 .  $final_c_attr_test .  "\n" . ${spc} x 4 . ")";
1065         } else { # just bibs...
1066             $flat_where .= "\n" . ${spc} x 4 . "AND (\n" . ${spc} x 5 .  $final_b_attr_test .  "\n" . ${spc} x 4 . ")";
1067         }
1068     }
1069
1070     my $with = $$flat_plan{with};
1071     $with= "\nWITH $with" if $with;
1072
1073     # Need an array for query parser db function; this gives a better plan
1074     # than the ARRAY_AGG(DISTINCT m.source) option as of PostgreSQL 9.1
1075     my $agg_records = 'ARRAY[m.source] AS records';
1076     if ($key =~ /metarecord/) {
1077         # metarecord searches still require the ARRAY_AGG approach
1078         $agg_records = 'ARRAY_AGG(DISTINCT m.source) AS records';
1079     }
1080
1081     my $sql = <<SQL;
1082 WITH w AS (
1083
1084 $with
1085 SELECT  id,
1086         rel,
1087         CASE WHEN cardinality(records) = 1 THEN records[1] ELSE NULL END AS record,
1088         NULL::INT AS total,
1089         NULL::INT AS checked,
1090         NULL::INT AS visible,
1091         NULL::INT AS deleted,
1092         NULL::INT AS excluded,
1093         badges,
1094         popularity
1095   FROM  (SELECT $key AS id,
1096                 $agg_records,
1097                 ${rel}::NUMERIC AS rel,
1098                 $rank AS rank, 
1099                 FIRST(pubdate_t.value) AS tie_break,
1100                 STRING_AGG(ARRAY_TO_STRING(pop_with.badges,','),',') AS badges,
1101                 AVG(COALESCE(pop_with.total_score::NUMERIC,0.0::NUMERIC))::NUMERIC(2,1) AS popularity
1102           FROM  metabib.metarecord_source_map m
1103                 $$flat_plan{from}
1104                 $mra_join
1105                 $mrv_join
1106                 $bre_join
1107                 $pop_join
1108                 $pubdate_join
1109                 $lang_join
1110                 $c_attr_join
1111                 $b_attr_join
1112           WHERE 1=1
1113                 $flat_where
1114           GROUP BY 1
1115           ORDER BY 4 $desc $nullpos, $pop_extra_sort 5 DESC $nullpos, 3 DESC
1116           LIMIT $core_limit
1117         ) AS core_query
1118 ) (SELECT * FROM w LIMIT $filters{check_limit} OFFSET $filters{skip_check})
1119         UNION ALL
1120   SELECT NULL,NULL,NULL,COUNT(*),COUNT(*),COUNT(*),0,0,NULL,NULL FROM w;
1121 SQL
1122
1123     warn $sql if $self->QueryParser->debug;
1124     return $sql;
1125
1126 }
1127
1128 sub flatten {
1129     my $self = shift;
1130
1131     die 'ERROR: nesting too deep or boolean list too long' if ($self->plan_level > 40);
1132
1133     my $from = shift || '';
1134     my $where = shift || '';
1135     my $with = '';
1136     my %vis_filter = ( c_attr => [], b_attr => [] );
1137     my $uses_bre = 0;
1138     my $uses_mrd = 0;
1139     my $uses_mrv = 0;
1140
1141     my @rank_list;
1142     for my $node ( @{$self->query_nodes} ) {
1143
1144         if (ref($node)) {
1145             if ($node->isa( 'QueryParser::query_plan::node' )) {
1146
1147                 unless (@{$node->only_atoms}) {
1148                     push @rank_list, '1';
1149                     $where .= 'TRUE';
1150                     next;
1151                 }
1152
1153                 my $table = $node->table;
1154                 my $ctable = $node->combined_table;
1155                 my $talias = $node->table_alias;
1156
1157                 my $node_rank = 'COALESCE(' . $node->rank . " * ${talias}.weight, 0.0)";
1158
1159                 $from .= "\n" . ${spc} x 4 ."LEFT JOIN (\n"
1160                       . ${spc} x 5 . "SELECT fe.*, fe_weight.weight, ${talias}_xq.tsq, ${talias}_xq.tsq_rank /* search */\n"
1161                       . ${spc} x 6 . "FROM  $table AS fe";
1162                 $from .= "\n" . ${spc} x 7 . "JOIN config.metabib_field AS fe_weight ON (fe_weight.id = fe.field)";
1163
1164                 my @bump_fields;
1165                 my @field_ids;
1166                 if (@{$node->fields} > 0) {
1167                     @bump_fields = @{$node->fields};
1168
1169                     @field_ids = grep defined, (
1170                         map {
1171                             $self->QueryParser->search_field_ids_by_class(
1172                                 $node->classname, $_
1173                             )->[0]
1174                         } @bump_fields
1175                     );
1176                 } else {
1177                     @bump_fields = @{$self->QueryParser->search_fields->{$node->classname}};
1178                 }
1179
1180                 if ($node->dummy_count < @{$node->only_atoms} ) {
1181                     $with .= ",\n     " if $with;
1182                     $with .= "${talias}_xq AS (SELECT ". $node->tsquery ." AS tsq,". $node->tsquery_rank ." AS tsq_rank )";
1183                     if ($node->combined_search) {
1184                         $from .= "\n" . ${spc} x 6 . "JOIN $ctable AS com ON (com.record = fe.source";
1185                         if (@field_ids) {
1186                             $from .= " AND com.metabib_field IN (" . join(',',@field_ids) . "))";
1187                         } else {
1188                             $from .= " AND com.metabib_field IS NULL)";
1189                         }
1190                         $from .= "\n" . ${spc} x 6 . "JOIN ${talias}_xq ON (com.index_vector @@ ${talias}_xq.tsq)";
1191                     } else {
1192                         $from .= "\n" . ${spc} x 6 . "JOIN ${talias}_xq ON (fe.index_vector @@ ${talias}_xq.tsq)";
1193                     }
1194                 } else {
1195                     $from .= "\n" . ${spc} x 6 . ", (SELECT NULL::tsquery AS tsq, NULL:tsquery AS tsq_rank ) AS ${talias}_xq";
1196                 }
1197
1198                 if (@field_ids) {
1199                     $from .= "\n" . ${spc} x 6 . "WHERE fe_weight.id IN  (" .
1200                         join(',', @field_ids) . ")";
1201                 }
1202
1203                 $from .= "\n" . ${spc} x 4 . ") AS $talias ON (m.source = ${talias}.source)";
1204
1205                 my %used_bumps;
1206                 my @bumps;
1207                 my @bumpmults;
1208                 for my $field ( @bump_fields ) {
1209                     my $bumps = $self->QueryParser->find_relevance_bumps( $node->classname => $field );
1210                     for my $b (keys %$bumps) {
1211                         next if (!$$bumps{$b}{active});
1212                         next if ($used_bumps{$b});
1213                         $used_bumps{$b} = 1;
1214
1215                         next if ($$bumps{$b}{multiplier} == 1); # optimization to remove unneeded bumps
1216                         push @bumps, $b;
1217                         push @bumpmults, $$bumps{$b}{multiplier};
1218                     }
1219                 }
1220
1221                 if(scalar @bumps > 0 && scalar @{$node->only_positive_atoms} > 0) {
1222                     # Note: Previous rank function used search_normalize outright. Duplicating that here.
1223                     $node_rank .= "\n" . ${spc} x 5 . "* evergreen.rel_bump(('{' || quote_literal(search_normalize(";
1224                     $node_rank .= join(")) || ',' || quote_literal(search_normalize(",map { $self->QueryParser->quote_phrase_value($_->content) } @{$node->only_positive_atoms});
1225                     $node_rank .= ")) || '}')::TEXT[], " . $node->table_alias . ".value, '{" . join(",",@bumps) . "}'::TEXT[], '{" . join(",",@bumpmults) . "}'::NUMERIC[])";
1226                 }
1227
1228                 my $NOT = '';
1229                 $NOT = 'NOT ' if $node->negate;
1230
1231                 $where .= "$NOT(" . $talias . ".id IS NOT NULL";
1232                 if (@{$node->phrases}) {
1233                     $where .= ' AND ' . join(' AND ', map {
1234                         "${talias}.value ~* ".$self->QueryParser->quote_phrase_value($_, 1)
1235                     } @{$node->phrases});
1236                 } else {
1237                     for my $atom (@{$node->only_real_atoms}) {
1238                         next unless $atom->{content} && $atom->{content} =~ /(^\^|\$$)/;
1239                         $where .= " AND ${talias}.value ~* ".$self->QueryParser->quote_phrase_value($atom->{content});
1240                     }
1241                 }
1242                 $where .= ')';
1243
1244                 push @rank_list, $node_rank;
1245
1246             } elsif ($node->isa( 'QueryParser::query_plan::facet' )) {
1247
1248                 my $talias = $node->table_alias;
1249
1250                 my @field_ids;
1251                 if (@{$node->fields} > 0) {
1252                     push(@field_ids, $self->QueryParser->facet_field_ids_by_class( $node->classname, $_ )->[0]) for (@{$node->fields});
1253                 } else {
1254                     @field_ids = @{ $self->QueryParser->facet_field_ids_by_class( $node->classname ) };
1255                 }
1256
1257                 my $join_type = ($node->negate or !$self->top_plan) ? 'LEFT' : 'INNER';
1258                 $from .= "\n${spc}$join_type JOIN /* facet */ metabib.facet_entry $talias ON (\n"
1259                       . ${spc} x 2 . "m.source = ${talias}.source\n"
1260                       . ${spc} x 2 . "AND SUBSTRING(${talias}.value,1,1024) IN ("
1261                       . join(",", map { $self->QueryParser->quote_value($_) } @{$node->values}) . ")\n"
1262                       . ${spc} x 2 ."AND ${talias}.field IN (". join(',', @field_ids) . ")\n"
1263                       . "${spc})";
1264
1265                 if ($join_type ne 'INNER') {
1266                     my $NOT = $node->negate ? '' : ' NOT';
1267                     $where .= "${talias}.id IS$NOT NULL";
1268                 } elsif ($where ne '') {
1269                     # Strip extra joiner
1270                     $where =~ s/(\s|\n)+(AND|OR)\s$//;
1271                 }
1272
1273             } else {
1274                 my $subnode = $node->flatten;
1275
1276                 # strip the trailing bool from the previous loop if there is 
1277                 # nothing to add to the where within this loop.
1278                 if ($$subnode{where} eq '') {
1279                     $where =~ s/(\s|\n)+(AND|OR)\s$//;
1280                 }
1281
1282                 push(@rank_list, @{$$subnode{rank_list}});
1283                 $from .= $$subnode{from};
1284
1285                 my $NOT = '';
1286                 $NOT = 'NOT ' if $node->negate;
1287
1288                 if ($$subnode{where} ne '') {
1289                     $where .= "$NOT(\n"
1290                            . ${spc} x ($self->plan_level + 6) . $$subnode{where} . "\n"
1291                            . ${spc} x ($self->plan_level + 5) . ')';
1292                 }
1293
1294                 if ($$subnode{with}) {
1295                     $with .= ",\n     " if $with;
1296                     $with .= $$subnode{with};
1297                 }
1298
1299                 $uses_bre = $$subnode{uses_bre};
1300                 $uses_mrd = $$subnode{uses_mrd};
1301                 $uses_mrv = $$subnode{uses_mrv};
1302             }
1303         } else {
1304
1305             warn "flatten(): appending WHERE bool to: $where\n" if $self->QueryParser->debug;
1306
1307             if ($where ne '') {
1308                 $where .= "\n" . ${spc} x ( $self->plan_level + 5 ) . 'AND ' if ($node eq '&');
1309                 $where .= "\n" . ${spc} x ( $self->plan_level + 5 ) . 'OR ' if ($node eq '|');
1310             }
1311         }
1312     }
1313
1314     my $joiner = "\n" . ${spc} x ( $self->plan_level + 5 ) . ($self->joiner eq '&' ? 'AND ' : 'OR ');
1315
1316     my ($depth_filter) = grep { $_->name eq 'depth' } @{$self->filters};
1317     if ($depth_filter and @{$depth_filter->args} == 1) {
1318         $depth_filter = $depth_filter->args->[0];
1319     }
1320
1321     my @dlist = ();
1322     my $common = 0;
1323     # for each dynamic filter, build more of the WHERE clause
1324     for my $filter (@{$self->filters}) {
1325         my $NOT = $filter->negate ? 'NOT ' : '';
1326         if (grep { $_ eq $filter->name } @{ $self->QueryParser->dynamic_filters }) {
1327
1328             my $fname = $filter->name;
1329             $fname = 'item_lang' if $fname eq 'language'; #XXX filter aliases 
1330
1331             warn "flatten(): processing dynamic filter ". $filter->name ."\n"
1332                 if $self->QueryParser->debug;
1333
1334             my $vlist_query;
1335             ($vlist_query, $common) = $self->dynamic_filter_compile( $fname, $filter->args, $filter->negate );
1336
1337             # bool joiner for intra-plan nodes/filters
1338             push(@dlist, $self->joiner) if @dlist;
1339             push(@dlist, $vlist_query);
1340             $uses_mrv = 1;
1341         } else {
1342             if ($filter->name eq 'before') {
1343                 if (@{$filter->args} == 1) {
1344                     $where .= $joiner if $where ne '';
1345                     $where .= "${NOT}COALESCE(pubdate_t.value <= "
1346                            . $self->QueryParser->quote_value($filter->args->[0])
1347                            . ", false)";
1348                 }
1349             } elsif ($filter->name eq 'after') {
1350                 if (@{$filter->args} == 1) {
1351                     $where .= $joiner if $where ne '';
1352                     $where .= "${NOT}COALESCE(pubdate_t.value >= "
1353                            . $self->QueryParser->quote_value($filter->args->[0])
1354                            . ", false)";
1355                 }
1356             } elsif ($filter->name eq 'during') {
1357                 if (@{$filter->args} == 1) {
1358                     $where .= $joiner if $where ne '';
1359                     $where .= "${NOT}COALESCE("
1360                            . $self->QueryParser->quote_value($filter->args->[0])
1361                            . " BETWEEN pubdate_t.value AND (mrd.attrs->'date2'), false)";
1362                     $uses_mrd = 1;
1363                 }
1364             } elsif ($filter->name eq 'between') {
1365                 if (@{$filter->args} == 2) {
1366                     $where .= $joiner if $where ne '';
1367                     $where .= "${NOT}COALESCE(pubdate_t.value BETWEEN "
1368                            . $self->QueryParser->quote_value($filter->args->[0])
1369                            . " AND "
1370                            . $self->QueryParser->quote_value($filter->args->[1])
1371                            . ", false)";
1372                 }
1373             } elsif ($filter->name eq 'container') {
1374                 if (@{$filter->args} >= 3) {
1375                     my ($class, $ctype, $cid, $token) = @{$filter->args};
1376                     my $perm_join = '';
1377                     my $rec_join = '';
1378                     my $rec_field = 'ci.target_biblio_record_entry';
1379                     if ($class eq 'bre') {
1380                         $class = 'biblio_record_entry';
1381                     } elsif ($class eq 'acn') {
1382                         $class = 'call_number';
1383                         $rec_field = 'cn.record';
1384                         $rec_join = 'JOIN asset.call_number cn ON (ci.target_call_number = cn.id)';
1385                     } elsif ($class eq 'acp') {
1386                         $class = 'copy';
1387                         $rec_field = 'cn.record';
1388                         $rec_join = 'JOIN asset.copy cp ON (ci.target_copy = cp.id) JOIN asset.call_number cn ON (cp.call_number = cn.id)';
1389                     } else {
1390                         $class = undef;
1391                     }
1392
1393                     if ($class) {
1394                         my ($u,$e) = $apputils->checksesperm($token) if ($token);
1395                         $perm_join = ' OR c.owner = ' . $u->id if ($u && !$e);
1396
1397                         my $filter_alias = "$filter";
1398                         $filter_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1399                         $filter_alias =~ s/\|/_/go;
1400
1401                         $with .= ",\n     " if $with;
1402                         $with .= "container_${filter_alias} AS (\n";
1403                         $with .= "       SELECT $rec_field AS record FROM container.${class}_bucket_item ci\n"
1404                                . "             JOIN container.${class}_bucket c ON (c.id = ci.bucket) $rec_join\n"
1405                                . "       WHERE c.btype = " . $self->QueryParser->quote_value($ctype) . "\n"
1406                                . "             AND c.id = " . $self->QueryParser->quote_value($cid) . "\n"
1407                                . "             AND (c.pub IS TRUE$perm_join)\n";
1408                         if ($class eq 'copy') {
1409                             $with .= "       UNION\n"
1410                                    . "       SELECT pr.peer_record AS record FROM container.copy_bucket_item ci\n"
1411                                    . "             JOIN container.copy_bucket c ON (c.id = ci.bucket)\n"
1412                                    . "             JOIN biblio.peer_bib_copy_map pr ON ci.target_copy = pr.target_copy\n"
1413                                    . "       WHERE c.btype = " . $self->QueryParser->quote_value($ctype) . "\n"
1414                                    . "             AND c.id = " . $self->QueryParser->quote_value($cid) . "\n"
1415                                    . "             AND (c.pub IS TRUE$perm_join)\n";
1416                         }
1417                         $with .= "     )";
1418
1419                         my $optimize_join = 1 if $self->top_plan and !$NOT;
1420                         $from .= "\n" . ${spc} x 3 . ( $optimize_join ? 'INNER' : 'LEFT') . " JOIN container_${filter_alias} ON container_${filter_alias}.record = m.source";
1421
1422                         if (!$optimize_join) {
1423                             $where .= $joiner if $where ne '';
1424                             $where .= "(container_${filter_alias} IS " . ( $NOT ? 'NULL)' : 'NOT NULL)');
1425                         }
1426                     }
1427                 }
1428             } elsif ($filter->name eq 'copy_tag') {
1429                 my $valid_copy_tag_search = 0;
1430                 my $copy_tag_type;
1431                 my $tag_value;
1432                 if (@{$filter->args} >= 2) { # must have at least two parts, tag (or *) and terms
1433                     my @fargs = @{$filter->args};
1434                     $copy_tag_type = shift(@fargs);
1435                     $tag_value = join(' ', @fargs);
1436                     $valid_copy_tag_search = 1;
1437                 }
1438                 if ($valid_copy_tag_search) {
1439                     my $norm_value = search_normalize($tag_value);
1440                     my @tokens = split /\s+/, $norm_value;
1441                     
1442                     my $filter_alias = "$filter";
1443                     $filter_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1444                     $filter_alias =~ s/\|/_/go;
1445
1446                     $with .= ",\n     " if $with;
1447                     $with .= "copy_tag_${filter_alias} AS (\n";
1448                     $with .= "       SELECT cn.record AS record FROM config.copy_tag_type cctt\n";
1449                     $with .= "             JOIN asset.copy_tag acpt ON (cctt.code = acpt.tag_type)\n";
1450                     $with .= "             JOIN asset.copy_tag_copy_map acptcm ON (acpt.id = acptcm.tag)\n";
1451                     $with .= "             JOIN asset.copy cp ON (acptcm.copy = cp.id)\n";
1452                     $with .= "             JOIN asset.call_number cn ON (cp.call_number = cn.id)\n";
1453                     $with .= "       WHERE 1 = 1 \n";
1454                     if ($copy_tag_type ne '*') {
1455                         $with .= "             AND cctt.code = " . $self->QueryParser->quote_value($copy_tag_type) . "\n";
1456                     }
1457                     if (@tokens) {
1458                         $with .= '             AND acpt.value @@ to_tsquery(' . $self->QueryParser->quote_value(join(' & ', @tokens)) . ")\n";
1459                     }
1460                     if (!$self->find_modifier('staff')) {
1461                         $with .= "             AND acpt.pub IS TRUE\n";
1462                     }
1463                     $with .= "     )";
1464
1465                     my $optimize_join = 1 if $self->top_plan and !$NOT;
1466                     $from .= "\n" . ${spc} x 3 . ( $optimize_join ? 'INNER' : 'LEFT') . " JOIN copy_tag_${filter_alias} ON copy_tag_${filter_alias}.record = m.source";
1467
1468                     if (!$optimize_join) {
1469                         $where .= $joiner if $where ne '';
1470                         $where .= "(copy_tag_${filter_alias} IS " . ( $NOT ? 'NULL)' : 'NOT NULL)');
1471                     }
1472                 }
1473             } elsif ($filter->name eq 'record_list') {
1474                 if (@{$filter->args} > 0) {
1475                     my $key = 'm.source';
1476                     $key = 'm.metarecord' if (grep {$_->name eq 'metarecord' or $_->name eq 'metabib'} @{$self->QueryParser->parse_tree->modifiers});
1477                     $where .= $joiner if $where ne '';
1478                     $where .= "$key ${NOT}IN (" . join(',', map { $self->QueryParser->quote_value($_) } @{$filter->args}) . ')';
1479                 }
1480
1481             } elsif ($filter->name eq 'site') {
1482                 if (@{$filter->args} == 1) {
1483                     if (!defined($depth_filter) or $depth_filter > 0) { # no point in filtering by "all"
1484                         my $sitename = $filter->args->[0];
1485
1486                         my $ot = $U->get_org_tree;
1487                         my $site_org = $U->find_org_by_shortname($ot, $sitename);
1488
1489                         if ($site_org and $site_org->id != $ot->id) { # no point in filtering by "all"
1490                             my $dorgs = $U->get_org_descendants($site_org->id, $depth_filter);
1491                             my $aorgs = $U->get_org_ancestors($site_org->id);
1492
1493                             my $negate = $filter->negate ? 'TRUE' : 'FALSE';
1494                             push @{$vis_filter{'c_attr'}},
1495                                 "search.calculate_visibility_attribute_test('circ_lib','{".join(',', @$dorgs)."}',$negate)";
1496
1497                             my $lorgs = [@$aorgs];
1498                             my $luri_as_copy_gf = $U->get_global_flag('opac.located_uri.act_as_copy');
1499                             push @$lorgs, @$dorgs if (
1500                                 $luri_as_copy_gf
1501                                 and $U->is_true($luri_as_copy_gf->enabled)
1502                                 and $U->is_true($luri_as_copy_gf->value)
1503                             );
1504
1505                             $uses_bre = 1;
1506                             push @{$vis_filter{'b_attr'}},
1507                                 "search.calculate_visibility_attribute_test('luri_org','{".join(',', @$lorgs)."}',$negate)";
1508                         }
1509                     }
1510                 }
1511
1512             } elsif ($filter->name eq 'locations') {
1513                 if (@{$filter->args} > 0) {
1514                     my $negate = $filter->negate ? 'TRUE' : 'FALSE';
1515                     push @{$vis_filter{'c_attr'}},
1516                         "search.calculate_visibility_attribute_test('location','{".join(',', @{$filter->args})."}',$negate)";
1517                 }
1518
1519             } elsif ($filter->name eq 'location_groups') {
1520                 if (@{$filter->args} > 0) {
1521                     my $negate = $filter->negate ? 'TRUE' : 'FALSE';
1522                     push @{$vis_filter{'c_attr'}},
1523                         "search.calculate_visibility_attribute_test('location_group','{".join(',', @{$filter->args})."}',$negate)";
1524                 }
1525
1526             } elsif ($filter->name eq 'statuses') {
1527                 if (@{$filter->args} > 0) {
1528                     my $negate = $filter->negate ? 'TRUE' : 'FALSE';
1529                     push @{$vis_filter{'c_attr'}},
1530                         "search.calculate_visibility_attribute_test('status','{".join(',', @{$filter->args})."}',$negate)";
1531                 }
1532
1533             } elsif ($filter->name eq 'has_browse_entry') {
1534                 if (@{$filter->args} >= 2) {
1535                     my $entry = int(shift @{$filter->args});
1536                     my $fields = join(",", map(int, @{$filter->args}));
1537                     $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);
1538                 }
1539             } elsif ($filter->name eq 'edit_date' or $filter->name eq 'create_date') {
1540                 # bre.create_date and bre.edit_date filtering
1541                 my $datefilter = $filter->name;
1542
1543                 $uses_bre = 1;
1544
1545                 if ($filter && $filter->args && scalar(@{$filter->args}) > 0 && scalar(@{$filter->args}) < 3) {
1546                     my ($cstart, $cend) = @{$filter->args};
1547         
1548                     if (!$cstart and !$cend) {
1549                         # useless use of filter
1550                     } elsif (!$cstart or $cstart eq '-infinity') { # no start supplied
1551                         if ($cend eq 'infinity') {
1552                             # useless use of filter
1553                         } else {
1554                             # "before $cend"
1555                             $cend = cleanse_ISO8601($cend);
1556                             $where .= $joiner if $where ne '';
1557                             $where .= "bre.$datefilter <= \$_$$\$$cend\$_$$\$";
1558                         }
1559             
1560                     } elsif (!$cend or $cend eq 'infinity') { # no end supplied
1561                         if ($cstart eq '-infinity') {
1562                             # useless use of filter
1563                         } else { # "after $cstart"
1564                             $cstart = cleanse_ISO8601($cstart);
1565                             $where .= $joiner if $where ne '';
1566                             $where .= "bre.$datefilter >= \$_$$\$$cstart\$_$$\$";
1567                         }
1568                     } else { # both supplied
1569                         # "between $cstart and $cend"
1570                         $cstart = cleanse_ISO8601($cstart);
1571                         $cend = cleanse_ISO8601($cend);
1572                         $where .= $joiner if $where ne '';
1573                         $where .= "bre.$datefilter BETWEEN \$_$$\$$cstart\$_$$\$ AND \$_$$\$$cend\$_$$\$";
1574                     }
1575                 }
1576             } elsif ($filter->name eq 'bib_source') {
1577                 if (@{$filter->args} > 0) {
1578                     $uses_bre = 1;
1579                     my $negate = $filter->negate ? 'TRUE' : 'FALSE';
1580                     push @{$vis_filter{'c_attr'}},
1581                         "search.calculate_visibility_attribute_test('source','{".join(',', @{$filter->args})."}',$negate)";
1582                 }
1583             } elsif ($filter->name eq 'from_metarecord') {
1584                 if (@{$filter->args} > 0) {
1585                     my $key = 'm.metarecord';
1586                     $where .= $joiner if $where ne '';
1587                     $where .= "$key ${NOT}IN (" . join(',', map { $self->QueryParser->quote_value($_) } @{$filter->args}) . ')';
1588                 }
1589             }
1590         }
1591     }
1592
1593     if (@dlist) {
1594
1595         $where .= $joiner if $where ne '';
1596         if ($common) { # Use a function wrapper to inform PG of the non-rareness of one or more filter elements
1597             $where .= sprintf(
1598                 'evergreen.query_int_wrapper(mrv.vlist, \'%s\')',
1599                 join('', @dlist)
1600             );
1601         } else {
1602             $where .= sprintf(
1603                 'mrv.vlist @@ \'%s\'',
1604                 join('', @dlist)
1605             );
1606         }
1607     }
1608
1609     warn "flatten(): full filter where => $where\n" if $self->QueryParser->debug;
1610
1611     return {
1612         rank_list => \@rank_list,
1613         from => $from,
1614         where => $where,
1615         with => $with,
1616         vis_filter => \%vis_filter,
1617         uses_bre => $uses_bre,
1618         uses_mrv => $uses_mrv,
1619         uses_mrd => $uses_mrd
1620     };
1621 }
1622
1623
1624 #-------------------------------
1625 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::filter;
1626 use base 'QueryParser::query_plan::filter';
1627
1628 #-------------------------------
1629 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::facet;
1630 use base 'QueryParser::query_plan::facet';
1631
1632 sub classname {
1633     my $self = shift;
1634     my ($classname) = split '\|', $self->name;
1635     return $classname;
1636 }
1637
1638 sub fields {
1639     my $self = shift;
1640     my ($classname,@fields) = split '\|', $self->name;
1641     return \@fields;
1642 }
1643
1644 sub table_alias {
1645     my $self = shift;
1646
1647     my $table_alias = "$self";
1648     $table_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1649     $table_alias .= '_' . $self->name;
1650     $table_alias =~ s/\|/_/go;
1651
1652     return $table_alias;
1653 }
1654
1655
1656 #-------------------------------
1657 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::modifier;
1658 use base 'QueryParser::query_plan::modifier';
1659
1660 #-------------------------------
1661 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::node::atom;
1662 use base 'QueryParser::query_plan::node::atom';
1663
1664 sub sql {
1665     my $self = shift;
1666     my $sql = shift;
1667
1668     $self->{sql} = $sql if ($sql);
1669
1670     return $self->{sql} if ($self->{sql});
1671     return $self->buildSQL;
1672 }
1673
1674 sub buildSQL {
1675     my $self = shift;
1676
1677     my $classname = $self->node->classname;
1678
1679     return $self->sql("to_tsquery('$classname','')") if $self->{dummy};
1680
1681     my $normalizers = $self->node->plan->QueryParser->query_normalizers( $classname );
1682     my $fields = $self->node->fields;
1683
1684     my $lang;
1685     my $filter = $self->node->plan->find_filter('preferred_language');
1686     $lang ||= $filter->args->[0] if ($filter && $filter->args);
1687     $lang ||= $self->node->plan->QueryParser->default_preferred_language;
1688     my $ts_configs = [];
1689
1690     if (@{$self->node->phrases}) {
1691         # We assume we want 'simple' for phrases. Gives us less to match against later.
1692         $ts_configs = ['simple'];
1693     } else {
1694         if (!@$fields) {
1695             $ts_configs = $self->node->plan->QueryParser->class_ts_config($classname, $lang);
1696         } else {
1697             for my $field (@$fields) {
1698                 push @$ts_configs, @{$self->node->plan->QueryParser->field_ts_config($classname, $field, $lang)};
1699             }
1700         }
1701         $ts_configs = [keys %{{map { $_ => 1 } @$ts_configs}}];
1702     }
1703
1704     # Assume we want exact if none otherwise provided.
1705     # Because we can reasonably expect this to exist
1706     $ts_configs = ['simple'] unless (scalar @$ts_configs);
1707
1708     $fields = $self->node->plan->QueryParser->search_fields->{$classname} if (!@$fields);
1709
1710     my %norms;
1711     my $pos = 0;
1712     for my $field (@$fields) {
1713         for my $nfield (keys %$normalizers) {
1714             for my $nizer ( @{$$normalizers{$nfield}} ) {
1715                 if ($field eq $nfield) {
1716                     my $param_string = OpenSRF::Utils::JSON->perl2JSON($nizer->{params});
1717                     if (!exists($norms{$nizer->{function}.$param_string})) {
1718                         $norms{$nizer->{function}.$param_string} = {p=>$pos++,n=>$nizer};
1719                     }
1720                 }
1721             }
1722         }
1723     }
1724
1725     my $sql = $self->node->plan->QueryParser->quote_value($self->content);
1726
1727     for my $n ( map { $$_{n} } sort { $$a{p} <=> $$b{p} } values %norms ) {
1728         $sql = join(', ', $sql, map { $self->node->plan->QueryParser->quote_value($_) } @{ $n->{params} });
1729         $sql = $n->{function}."($sql)";
1730     }
1731
1732     my $prefix = $self->prefix || '';
1733     my $suffix = $self->suffix || '';
1734     my $joiner = ' || ';
1735     $joiner = ' && ' if $self->prefix eq '!'; # Negative atoms should be "none of the variants" instead of "any of the variants"
1736
1737     $prefix = "'$prefix' ||" if $prefix;
1738     my $suffix_op = '';
1739     my $suffix_after = '';
1740
1741     $suffix_op = ":$suffix" if $suffix;
1742     $suffix_after = "|| '$suffix_op'" if $suffix;
1743
1744     my @sql_set = ();
1745     for my $ts_config (@$ts_configs) {
1746         push @sql_set, "to_tsquery('$ts_config', COALESCE(NULLIF($prefix '(' || btrim(regexp_replace($sql,E'(?:\\\\s+|:)','$suffix_op&','g'),'&|') $suffix_after || ')', '()'), ''))";
1747     }
1748
1749     $sql = join($joiner, @sql_set);
1750     $sql = '(' . $sql . ')' if (scalar(@$ts_configs) > 1);
1751
1752     return $self->sql($sql);
1753 }
1754
1755 #-------------------------------
1756 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::node;
1757 use base 'QueryParser::query_plan::node';
1758
1759 sub only_atoms {
1760     my $self = shift;
1761
1762     $self->{dummy_count} = 0;
1763
1764     my $atoms = $self->query_atoms;
1765     my @only_atoms;
1766     for my $a (@$atoms) {
1767         push(@only_atoms, $a) if (ref($a) && $a->isa('QueryParser::query_plan::node::atom'));
1768         $self->{dummy_count}++ if (ref($a) && $a->{dummy});
1769     }
1770
1771     return \@only_atoms;
1772 }
1773
1774 sub only_real_atoms {
1775     my $self = shift;
1776
1777     my $atoms = $self->query_atoms;
1778     my @only_real_atoms;
1779     for my $a (@$atoms) {
1780         push(@only_real_atoms, $a) if (ref($a) && $a->isa('QueryParser::query_plan::node::atom') && !($a->{dummy}));
1781     }
1782
1783     return \@only_real_atoms;
1784 }
1785
1786 sub only_positive_atoms {
1787     my $self = shift;
1788
1789     my $atoms = $self->query_atoms;
1790     my @only_positive_atoms;
1791     for my $a (@$atoms) {
1792         push(@only_positive_atoms, $a) if (ref($a) && $a->isa('QueryParser::query_plan::node::atom') && !($a->{dummy}) && ($a->{prefix} ne '!'));
1793     }
1794
1795     return \@only_positive_atoms;
1796 }
1797
1798 sub dummy_count {
1799     my $self = shift;
1800     return $self->{dummy_count};
1801 }
1802
1803 sub table {
1804     my $self = shift;
1805     my $table = shift;
1806     $self->{table} = $table if ($table);
1807     return $self->{table} if $self->{table};
1808     return $self->table( 'metabib.' . $self->classname . '_field_entry' );
1809 }
1810
1811 sub combined_table {
1812     my $self = shift;
1813     my $ctable = shift;
1814     $self->{ctable} = $ctable if ($ctable);
1815     return $self->{ctable} if $self->{ctable};
1816     return $self->combined_table( 'metabib.combined_' . $self->classname . '_field_entry' );
1817 }
1818
1819 sub combined_search {
1820     my $self = shift;
1821     return $self->plan->QueryParser->search_class_combined($self->classname);
1822 }
1823
1824 sub table_alias {
1825     my $self = shift;
1826     my $table_alias = shift;
1827     $self->{table_alias} = $table_alias if ($table_alias);
1828     return $self->{table_alias} if ($self->{table_alias});
1829
1830     $table_alias = "$self";
1831     $table_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1832     $table_alias .= '_' . $self->requested_class;
1833     $table_alias =~ s/\|/_/go;
1834
1835     return $self->table_alias( $table_alias );
1836 }
1837
1838 sub tsquery {
1839     my $self = shift;
1840     return $self->{tsquery} if ($self->{tsquery});
1841
1842     for my $atom (@{$self->query_atoms}) {
1843         if (ref($atom)) {
1844             $self->{tsquery} .= "\n" . ${spc} x 3 . $atom->sql;
1845         } else {
1846             $self->{tsquery} .= $atom x 2;
1847         }
1848     }
1849
1850     return $self->{tsquery};
1851 }
1852
1853 sub tsquery_rank {
1854     my $self = shift;
1855     return $self->{tsquery_rank} if ($self->{tsquery_rank});
1856     my @atomlines;
1857
1858     for my $atom (@{$self->only_positive_atoms}) {
1859         push @atomlines, "\n" . ${spc} x 3 . $atom->sql;
1860     }
1861     $self->{tsquery_rank} = join(' ||', @atomlines);
1862     $self->{tsquery_rank} = 'NULL::tsquery' unless $self->{tsquery_rank};
1863     return $self->{tsquery_rank};
1864 }
1865
1866 sub rank {
1867     my $self = shift;
1868     return $self->{rank} if ($self->{rank});
1869
1870     my $rank_norm_map = $self->plan->QueryParser->custom_data->{rank_cd_weight_map};
1871
1872     my $cover_density = 0;
1873     for my $norm ( keys %$rank_norm_map) {
1874         $cover_density += $$rank_norm_map{$norm} if ($self->plan->QueryParser->parse_tree->find_modifier($norm));
1875     }
1876
1877     my $weights = join(', ', @{$self->plan->QueryParser->search_class_weights($self->classname)});
1878
1879     return $self->{rank} = "ts_rank_cd('{" . $weights . "}', " . $self->table_alias . '.index_vector, ' . $self->table_alias . ".tsq_rank, $cover_density)";
1880 }
1881
1882
1883 1;
1884