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