]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Storage/Driver/Pg/QueryParser.pm
9774fd0608a7dd124b85eccf117b3fa44104f150
[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                             # UNION in the others ... group by class?
1277                             for my $real_field (@$real_fields) {
1278                                 $node->add_vfield($real_field);
1279                                 $logger->debug("Looking up virtual field for real field $real_field");
1280                                 my $vtable = $node->table(
1281                                     $self->QueryParser
1282                                         ->search_field_class_by_id($real_field)
1283                                         ->{classname}
1284                                 );
1285
1286                                 # NOTE: only real fields that match the (component) tsquery will
1287                                 #       get to contribute to and increased rank for the record.
1288                                 $from .= "\n" . ${spc} x 8 . "UNION ALL\n"
1289                                       . ${spc} x 5 . "SELECT fe.id, fe.source, fe.field, fe.value, fe.index_vector, "
1290                                       . "fe_weight.weight, ${talias}_xq.tsq, ${talias}_xq.tsq_rank /* virtual field addition */\n"
1291                                       . ${spc} x 6 . "FROM  $vtable AS fe\n"
1292                                       . ${spc} x 7 . "JOIN config.metabib_field_virtual_map AS fe_weight ON ("
1293                                             ."fe_weight.virtual = $possible_vfield AND "
1294                                             ."fe_weight.real = $real_field AND "
1295                                             ."fe_weight.real = fe.field)\n"
1296                                       . ${spc} x 7 . "JOIN ${talias}_xq ON (fe.index_vector @@ ${talias}_xq.tsq)"
1297                                 ;
1298                             }
1299                         }
1300                     }
1301                 }
1302
1303                 $from .= "\n" . ${spc} x 4 . ") AS $talias ON (m.source = ${talias}.source)";
1304
1305                 my %used_bumps;
1306                 my @bumps;
1307                 my @bumpmults;
1308                 for my $field ( @bump_fields ) {
1309                     my $bumps = $self->QueryParser->find_relevance_bumps( $node->classname => $field );
1310                     for my $b (keys %$bumps) {
1311                         next if (!$$bumps{$b}{active});
1312                         next if ($used_bumps{$b});
1313                         $used_bumps{$b} = 1;
1314
1315                         next if ($$bumps{$b}{multiplier} == 1); # optimization to remove unneeded bumps
1316                         push @bumps, $b;
1317                         push @bumpmults, $$bumps{$b}{multiplier};
1318                     }
1319                 }
1320
1321                 if(scalar @bumps > 0 && scalar @{$node->only_positive_atoms} > 0) {
1322                     # Note: Previous rank function used search_normalize outright. Duplicating that here.
1323                     $node_rank .= "\n" . ${spc} x 5 . "* COALESCE(evergreen.rel_bump(('{' || quote_literal(search_normalize(";
1324                     $node_rank .= join(")) || ',' || quote_literal(search_normalize(",map { $self->QueryParser->quote_phrase_value($_->content) } @{$node->only_positive_atoms});
1325                     $node_rank .= ")) || '}')::TEXT[], " . $node->table_alias . ".value, '{" . join(",",@bumps) . "}'::TEXT[], '{" . join(",",@bumpmults) . "}'::NUMERIC[]),1.0)";
1326                 }
1327
1328                 my $NOT = '';
1329                 $NOT = 'NOT ' if $node->negate;
1330
1331                 $where .= "$NOT(" . $talias . ".id IS NOT NULL";
1332                 if (@{$node->phrases}) {
1333                     $where .= ' AND ' . join(' AND ', map {
1334                         "${talias}.value ~* ".$self->QueryParser->quote_phrase_value($_, 1)
1335                     } @{$node->phrases});
1336                 } else {
1337                     for my $atom (@{$node->only_real_atoms}) {
1338                         next unless $atom->{content} && $atom->{content} =~ /(^\^|\$$)/;
1339                         $where .= " AND ${talias}.value ~* ".$self->QueryParser->quote_phrase_value($atom->{content});
1340                     }
1341                 }
1342                 $where .= ')';
1343
1344                 push @rank_list, $node_rank;
1345
1346             } elsif ($node->isa( 'QueryParser::query_plan::facet' )) {
1347
1348                 my $talias = $node->table_alias;
1349
1350                 my @field_ids;
1351                 if (@{$node->fields} > 0) {
1352                     push(@field_ids, $self->QueryParser->facet_field_ids_by_class( $node->classname, $_ )->[0]) for (@{$node->fields});
1353                 } else {
1354                     @field_ids = @{ $self->QueryParser->facet_field_ids_by_class( $node->classname ) };
1355                 }
1356
1357                 my $join_type = ($node->negate or !$self->top_plan) ? 'LEFT' : 'INNER';
1358                 $from .= "\n${spc}$join_type JOIN /* facet */ metabib.facet_entry $talias ON (\n"
1359                       . ${spc} x 2 . "m.source = ${talias}.source\n"
1360                       . ${spc} x 2 . "AND SUBSTRING(${talias}.value,1,1024) IN ("
1361                       . join(",", map { $self->QueryParser->quote_value($_) } @{$node->values}) . ")\n"
1362                       . ${spc} x 2 ."AND ${talias}.field IN (". join(',', @field_ids) . ")\n"
1363                       . "${spc})";
1364
1365                 if ($join_type ne 'INNER') {
1366                     my $NOT = $node->negate ? '' : ' NOT';
1367                     $where .= "${talias}.id IS$NOT NULL";
1368                 } elsif ($where ne '') {
1369                     # Strip extra joiner
1370                     $where =~ s/(\s|\n)+(AND|OR)\s$//;
1371                 }
1372
1373             } else {
1374                 my $subnode = $node->flatten;
1375
1376                 # strip the trailing bool from the previous loop if there is 
1377                 # nothing to add to the where within this loop.
1378                 if ($$subnode{where} eq '') {
1379                     $where =~ s/(\s|\n)+(AND|OR)\s$//;
1380                 }
1381
1382                 push(@rank_list, @{$$subnode{rank_list}});
1383                 $from .= $$subnode{from};
1384
1385                 my $NOT = '';
1386                 $NOT = 'NOT ' if $node->negate;
1387
1388                 if ($$subnode{where} ne '') {
1389                     $where .= "$NOT(\n"
1390                            . ${spc} x ($self->plan_level + 6) . $$subnode{where} . "\n"
1391                            . ${spc} x ($self->plan_level + 5) . ')';
1392                 }
1393
1394                 if ($$subnode{with}) {
1395                     $with .= ",\n     " if $with;
1396                     $with .= $$subnode{with};
1397                 }
1398
1399                 $uses_bre = $$subnode{uses_bre};
1400                 $uses_mrd = $$subnode{uses_mrd};
1401                 $uses_mrv = $$subnode{uses_mrv};
1402             }
1403         } else {
1404
1405             warn "flatten(): appending WHERE bool to: $where\n" if $self->QueryParser->debug;
1406
1407             if ($where ne '') {
1408                 $where .= "\n" . ${spc} x ( $self->plan_level + 5 ) . 'AND ' if ($node eq '&');
1409                 $where .= "\n" . ${spc} x ( $self->plan_level + 5 ) . 'OR ' if ($node eq '|');
1410             }
1411         }
1412     }
1413
1414     my $joiner = "\n" . ${spc} x ( $self->plan_level + 5 ) . ($self->joiner eq '&' ? 'AND ' : 'OR ');
1415
1416     my ($depth_filter) = grep { $_->name eq 'depth' } @{$self->filters};
1417     if ($depth_filter and @{$depth_filter->args} == 1) {
1418         $depth_filter = $depth_filter->args->[0];
1419     }
1420
1421     my $ot = $U->get_org_tree;
1422     my $site_org = $ot;
1423     my $negate = 'FALSE';
1424
1425     my ($site_filter) = grep { $_->name eq 'site' } @{$self->filters};
1426     if ($site_filter and @{$site_filter->args} == 1) {
1427        $negate = $site_filter->negate ? 'TRUE' : 'FALSE';
1428
1429        my $sitename = $site_filter->args->[0];
1430        $site_org = $U->find_org_by_shortname($ot, $sitename) || $ot;
1431     }
1432
1433     my $dorgs = $U->get_org_descendants($site_org->id, $depth_filter);
1434     my $aorgs = $U->get_org_ancestors($site_org->id);
1435
1436     if (!$self->find_modifier('staff')) {
1437         my $non_inherited_vis_gf = $U->get_global_flag('opac.org_unit.non_inherited_visibility');
1438         $dorgs = [ grep { is_org_visible($U->find_org($ot,$_), $non_inherited_vis_gf) } @$dorgs ];
1439         $aorgs = [ grep { is_org_visible($U->find_org($ot,$_), $non_inherited_vis_gf) } @$aorgs ];
1440     }
1441
1442     push @{$vis_filter{'c_attr'}},
1443         "search.calculate_visibility_attribute_test('circ_lib','{".join(',', @$dorgs)."}',$negate)";
1444
1445     my $lorgs = [@$aorgs];
1446     my $luri_as_copy_gf = $U->get_global_flag('opac.located_uri.act_as_copy');
1447     push @$lorgs, @$dorgs if ($luri_as_copy_gf and $U->is_true($luri_as_copy_gf->enabled));
1448
1449     $uses_bre = 1;
1450     push @{$vis_filter{'b_attr'}},
1451         "search.calculate_visibility_attribute_test('luri_org','{".join(',', @$lorgs)."}',$negate)";
1452
1453     my @dlist = ();
1454     my $common = 0;
1455     # for each dynamic filter, build more of the WHERE clause
1456     for my $filter (@{$self->filters}) {
1457         my $NOT = $filter->negate ? 'NOT ' : '';
1458         if (grep { $_ eq $filter->name } @{ $self->QueryParser->dynamic_filters }) {
1459
1460             my $fname = $filter->name;
1461             $fname = 'item_lang' if $fname eq 'language'; #XXX filter aliases 
1462
1463             warn "flatten(): processing dynamic filter ". $filter->name ."\n"
1464                 if $self->QueryParser->debug;
1465
1466             my $vlist_query;
1467             ($vlist_query, $common) = $self->dynamic_filter_compile( $fname, $filter->args, $filter->negate );
1468
1469             # bool joiner for intra-plan nodes/filters
1470             push(@dlist, $self->joiner) if @dlist;
1471             push(@dlist, $vlist_query);
1472             $uses_mrv = 1;
1473         } else {
1474             if ($filter->name eq 'before') {
1475                 if (@{$filter->args} == 1) {
1476                     $where .= $joiner if $where ne '';
1477                     $where .= "${NOT}COALESCE(pubdate_t.value <= "
1478                            . $self->QueryParser->quote_value($filter->args->[0])
1479                            . ", false)";
1480                 }
1481             } elsif ($filter->name eq 'after') {
1482                 if (@{$filter->args} == 1) {
1483                     $where .= $joiner if $where ne '';
1484                     $where .= "${NOT}COALESCE(pubdate_t.value >= "
1485                            . $self->QueryParser->quote_value($filter->args->[0])
1486                            . ", false)";
1487                 }
1488             } elsif ($filter->name eq 'during') {
1489                 if (@{$filter->args} == 1) {
1490                     $where .= $joiner if $where ne '';
1491                     $where .= "${NOT}COALESCE("
1492                            . $self->QueryParser->quote_value($filter->args->[0])
1493                            . " BETWEEN pubdate_t.value AND (mrd.attrs->'date2'), false)";
1494                     $uses_mrd = 1;
1495                 }
1496             } elsif ($filter->name eq 'between') {
1497                 if (@{$filter->args} == 2) {
1498                     $where .= $joiner if $where ne '';
1499                     $where .= "${NOT}COALESCE(pubdate_t.value BETWEEN "
1500                            . $self->QueryParser->quote_value($filter->args->[0])
1501                            . " AND "
1502                            . $self->QueryParser->quote_value($filter->args->[1])
1503                            . ", false)";
1504                 }
1505             } elsif ($filter->name eq 'container') {
1506                 if (@{$filter->args} >= 3) {
1507                     my ($class, $ctype, $cid, $token) = @{$filter->args};
1508                     my $perm_join = '';
1509                     my $rec_join = '';
1510                     my $rec_field = 'ci.target_biblio_record_entry';
1511                     if ($class eq 'bre') {
1512                         $class = 'biblio_record_entry';
1513                     } elsif ($class eq 'acn') {
1514                         $class = 'call_number';
1515                         $rec_field = 'cn.record';
1516                         $rec_join = 'JOIN asset.call_number cn ON (ci.target_call_number = cn.id)';
1517                     } elsif ($class eq 'acp') {
1518                         $class = 'copy';
1519                         $rec_field = 'cn.record';
1520                         $rec_join = 'JOIN asset.copy cp ON (ci.target_copy = cp.id) JOIN asset.call_number cn ON (cp.call_number = cn.id)';
1521                     } else {
1522                         $class = undef;
1523                     }
1524
1525                     if ($class) {
1526                         my ($u,$e) = $apputils->checksesperm($token) if ($token);
1527                         $perm_join = ' OR c.owner = ' . $u->id if ($u && !$e);
1528
1529                         my $filter_alias = "$filter";
1530                         $filter_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1531                         $filter_alias =~ s/\|/_/go;
1532
1533                         $with .= ",\n     " if $with;
1534                         $with .= "container_${filter_alias} AS (\n";
1535                         $with .= "       SELECT $rec_field AS record FROM container.${class}_bucket_item ci\n"
1536                                . "             JOIN container.${class}_bucket c ON (c.id = ci.bucket) $rec_join\n"
1537                                . "       WHERE c.btype = " . $self->QueryParser->quote_value($ctype) . "\n"
1538                                . "             AND c.id = " . $self->QueryParser->quote_value($cid) . "\n"
1539                                . "             AND (c.pub IS TRUE$perm_join)\n";
1540                         if ($class eq 'copy') {
1541                             $with .= "       UNION\n"
1542                                    . "       SELECT pr.peer_record AS record FROM container.copy_bucket_item ci\n"
1543                                    . "             JOIN container.copy_bucket c ON (c.id = ci.bucket)\n"
1544                                    . "             JOIN biblio.peer_bib_copy_map pr ON ci.target_copy = pr.target_copy\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                         }
1549                         $with .= "     )";
1550
1551                         my $optimize_join = 1 if $self->top_plan and !$NOT;
1552                         $from .= "\n" . ${spc} x 3 . ( $optimize_join ? 'INNER' : 'LEFT') . " JOIN container_${filter_alias} ON container_${filter_alias}.record = m.source";
1553
1554                         if (!$optimize_join) {
1555                             $where .= $joiner if $where ne '';
1556                             $where .= "(container_${filter_alias} IS " . ( $NOT ? 'NULL)' : 'NOT NULL)');
1557                         }
1558                     }
1559                 }
1560             } elsif ($filter->name eq 'copy_tag') {
1561                 my $valid_copy_tag_search = 0;
1562                 my $copy_tag_type;
1563                 my $tag_value;
1564                 if (@{$filter->args} >= 2) { # must have at least two parts, tag (or *) and terms
1565                     my @fargs = @{$filter->args};
1566                     $copy_tag_type = shift(@fargs);
1567                     $tag_value = join(' ', @fargs);
1568                     $valid_copy_tag_search = 1;
1569                 }
1570                 if ($valid_copy_tag_search) {
1571                     my $norm_value = search_normalize($tag_value);
1572                     my @tokens = split /\s+/, $norm_value;
1573                     
1574                     my $filter_alias = "$filter";
1575                     $filter_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1576                     $filter_alias =~ s/\|/_/go;
1577
1578                     $with .= ",\n     " if $with;
1579                     $with .= "copy_tag_${filter_alias} AS (\n";
1580                     $with .= "       SELECT cn.record AS record FROM config.copy_tag_type cctt\n";
1581                     $with .= "             JOIN asset.copy_tag acpt ON (cctt.code = acpt.tag_type)\n";
1582                     $with .= "             JOIN asset.copy_tag_copy_map acptcm ON (acpt.id = acptcm.tag)\n";
1583                     $with .= "             JOIN asset.copy cp ON (acptcm.copy = cp.id)\n";
1584                     $with .= "             JOIN asset.call_number cn ON (cp.call_number = cn.id)\n";
1585                     $with .= "       WHERE 1 = 1 \n";
1586                     if ($copy_tag_type ne '*') {
1587                         $with .= "             AND cctt.code = " . $self->QueryParser->quote_value($copy_tag_type) . "\n";
1588                     }
1589                     if (@tokens) {
1590                         $with .= '             AND acpt.value @@ to_tsquery(' . $self->QueryParser->quote_value(join(' & ', @tokens)) . ")\n";
1591                     }
1592                     if (!$self->find_modifier('staff')) {
1593                         $with .= "             AND acpt.pub IS TRUE\n";
1594                     }
1595                     $with .= "     )";
1596
1597                     my $optimize_join = 1 if $self->top_plan and !$NOT;
1598                     $from .= "\n" . ${spc} x 3 . ( $optimize_join ? 'INNER' : 'LEFT') . " JOIN copy_tag_${filter_alias} ON copy_tag_${filter_alias}.record = m.source";
1599
1600                     if (!$optimize_join) {
1601                         $where .= $joiner if $where ne '';
1602                         $where .= "(copy_tag_${filter_alias} IS " . ( $NOT ? 'NULL)' : 'NOT NULL)');
1603                     }
1604                 }
1605             } elsif ($filter->name eq 'record_list') {
1606                 if (@{$filter->args} > 0) {
1607                     my $key = 'm.source';
1608                     $key = 'm.metarecord' if (grep {$_->name eq 'metarecord' or $_->name eq 'metabib'} @{$self->QueryParser->parse_tree->modifiers});
1609                     $where .= $joiner if $where ne '';
1610                     $where .= "$key ${NOT}IN (" . join(',', map { $self->QueryParser->quote_value($_) } @{$filter->args}) . ')';
1611                 }
1612
1613             } elsif ($filter->name eq 'locations') {
1614                 if (@{$filter->args} > 0) {
1615                     my $negate = $filter->negate ? 'TRUE' : 'FALSE';
1616                     my $filter_args = join(",", map(int, @{$filter->args}));
1617                     push @{$vis_filter{'c_attr'}},
1618                         "search.calculate_visibility_attribute_test('location','{$filter_args}',$negate)";
1619                 }
1620
1621             } elsif ($filter->name eq 'location_groups') {
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',(SELECT ARRAY_AGG(location) FROM asset.copy_location_group_map WHERE lgroup IN ($filter_args)),$negate)";
1627                 }
1628
1629             } elsif ($filter->name eq 'statuses') {
1630                 if (@{$filter->args} > 0) {
1631                     my $negate = $filter->negate ? 'TRUE' : 'FALSE';
1632                     push @{$vis_filter{'c_attr'}},
1633                         "search.calculate_visibility_attribute_test('status','{".join(',', @{$filter->args})."}',$negate)";
1634                 }
1635
1636             } elsif ($filter->name eq 'has_browse_entry') {
1637                 if (@{$filter->args} >= 2) {
1638                     my $entry = int(shift @{$filter->args});
1639                     my $fields = join(",", map(int, @{$filter->args}));
1640                     $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);
1641                 }
1642             } elsif ($filter->name eq 'edit_date' or $filter->name eq 'create_date') {
1643                 # bre.create_date and bre.edit_date filtering
1644                 my $datefilter = $filter->name;
1645
1646                 $uses_bre = 1;
1647
1648                 if ($filter && $filter->args && scalar(@{$filter->args}) > 0 && scalar(@{$filter->args}) < 3) {
1649                     my ($cstart, $cend) = @{$filter->args};
1650         
1651                     if (!$cstart and !$cend) {
1652                         # useless use of filter
1653                     } elsif (!$cstart or $cstart eq '-infinity') { # no start supplied
1654                         if ($cend eq 'infinity') {
1655                             # useless use of filter
1656                         } else {
1657                             # "before $cend"
1658                             $cend = cleanse_ISO8601($cend);
1659                             $where .= $joiner if $where ne '';
1660                             $where .= "bre.$datefilter <= \$_$$\$$cend\$_$$\$";
1661                         }
1662             
1663                     } elsif (!$cend or $cend eq 'infinity') { # no end supplied
1664                         if ($cstart eq '-infinity') {
1665                             # useless use of filter
1666                         } else { # "after $cstart"
1667                             $cstart = cleanse_ISO8601($cstart);
1668                             $where .= $joiner if $where ne '';
1669                             $where .= "bre.$datefilter >= \$_$$\$$cstart\$_$$\$";
1670                         }
1671                     } else { # both supplied
1672                         # "between $cstart and $cend"
1673                         $cstart = cleanse_ISO8601($cstart);
1674                         $cend = cleanse_ISO8601($cend);
1675                         $where .= $joiner if $where ne '';
1676                         $where .= "bre.$datefilter BETWEEN \$_$$\$$cstart\$_$$\$ AND \$_$$\$$cend\$_$$\$";
1677                     }
1678                 }
1679             } elsif ($filter->name eq 'bib_source') {
1680                 if (@{$filter->args} > 0) {
1681                     $uses_bre = 1;
1682                     my $negate = $filter->negate ? 'TRUE' : 'FALSE';
1683                     push @{$vis_filter{'b_attr'}},
1684                         "search.calculate_visibility_attribute_test('source','{".join(',', @{$filter->args})."}',$negate)";
1685                 }
1686             } elsif ($filter->name eq 'from_metarecord') {
1687                 if (@{$filter->args} > 0) {
1688                     my $key = 'm.metarecord';
1689                     $where .= $joiner if $where ne '';
1690                     $where .= "$key ${NOT}IN (" . join(',', map { $self->QueryParser->quote_value($_) } @{$filter->args}) . ')';
1691                 }
1692             }
1693         }
1694     }
1695
1696     if (@dlist) {
1697
1698         $where .= $joiner if $where ne '';
1699         if ($common) { # Use a function wrapper to inform PG of the non-rareness of one or more filter elements
1700             $where .= sprintf(
1701                 'evergreen.query_int_wrapper(mrv.vlist, \'%s\')',
1702                 join('', @dlist)
1703             );
1704         } else {
1705             $where .= sprintf(
1706                 'mrv.vlist @@ \'%s\'',
1707                 join('', @dlist)
1708             );
1709         }
1710     }
1711
1712     warn "flatten(): full filter where => $where\n" if $self->QueryParser->debug;
1713
1714     return {
1715         rank_list => \@rank_list,
1716         from => $from,
1717         where => $where,
1718         with => $with,
1719         vis_filter => \%vis_filter,
1720         uses_bre => $uses_bre,
1721         uses_mrv => $uses_mrv,
1722         uses_mrd => $uses_mrd
1723     };
1724 }
1725
1726
1727 #-------------------------------
1728 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::filter;
1729 use base 'QueryParser::query_plan::filter';
1730
1731 #-------------------------------
1732 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::facet;
1733 use base 'QueryParser::query_plan::facet';
1734
1735 sub classname {
1736     my $self = shift;
1737     my ($classname) = split '\|', $self->name;
1738     return $classname;
1739 }
1740
1741 sub fields {
1742     my $self = shift;
1743     my ($classname,@fields) = split '\|', $self->name;
1744     return \@fields;
1745 }
1746
1747 sub table_alias {
1748     my $self = shift;
1749     my $suffix = shift;
1750
1751     my $table_alias = "$self";
1752     $table_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1753     $table_alias .= '_' . $self->name;
1754     $table_alias =~ s/\|/_/go;
1755     $table_alias .= "_$suffix" if ($suffix);
1756
1757     return $table_alias;
1758 }
1759
1760
1761 #-------------------------------
1762 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::modifier;
1763 use base 'QueryParser::query_plan::modifier';
1764
1765 #-------------------------------
1766 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::node::atom;
1767 use base 'QueryParser::query_plan::node::atom';
1768
1769 sub sql {
1770     my $self = shift;
1771     my $sql = shift;
1772
1773     $self->{sql} = $sql if ($sql);
1774
1775     return $self->{sql} if ($self->{sql});
1776     return $self->buildSQL;
1777 }
1778
1779 sub buildSQL {
1780     my $self = shift;
1781
1782     my $classname = $self->node->classname;
1783
1784     return $self->sql("to_tsquery('$classname','')") if $self->{dummy};
1785
1786     my $normalizers = $self->node->plan->QueryParser->query_normalizers( $classname );
1787     my $fields = $self->node->fields;
1788
1789     my $lang;
1790     my $filter = $self->node->plan->find_filter('preferred_language');
1791     $lang ||= $filter->args->[0] if ($filter && $filter->args);
1792     $lang ||= $self->node->plan->QueryParser->default_preferred_language;
1793     my $ts_configs = [];
1794
1795     if (@{$self->node->phrases}) {
1796         # We assume we want 'simple' for phrases. Gives us less to match against later.
1797         $ts_configs = ['simple'];
1798     } else {
1799         if (!@$fields) {
1800             $ts_configs = $self->node->plan->QueryParser->class_ts_config($classname, $lang);
1801         } else {
1802             for my $field (@$fields) {
1803                 push @$ts_configs, @{$self->node->plan->QueryParser->field_ts_config($classname, $field, $lang)};
1804             }
1805         }
1806         $ts_configs = [keys %{{map { $_ => 1 } @$ts_configs}}];
1807     }
1808
1809     # Assume we want exact if none otherwise provided.
1810     # Because we can reasonably expect this to exist
1811     $ts_configs = ['simple'] unless (scalar @$ts_configs);
1812
1813     $fields = $self->node->plan->QueryParser->search_fields->{$classname} if (!@$fields);
1814
1815     my %norms;
1816     my $pos = 0;
1817     for my $field (@$fields) {
1818         for my $nfield (keys %$normalizers) {
1819             for my $nizer ( @{$$normalizers{$nfield}} ) {
1820                 if ($field eq $nfield) {
1821                     my $param_string = OpenSRF::Utils::JSON->perl2JSON($nizer->{params});
1822                     if (!exists($norms{$nizer->{function}.$param_string})) {
1823                         $norms{$nizer->{function}.$param_string} = {p=>$pos++,n=>$nizer};
1824                     }
1825                 }
1826             }
1827         }
1828     }
1829
1830     my $sql = $self->node->plan->QueryParser->quote_value($self->content);
1831
1832     for my $n ( map { $$_{n} } sort { $$a{p} <=> $$b{p} } values %norms ) {
1833         $sql = join(', ', $sql, map { $self->node->plan->QueryParser->quote_value($_) } @{ $n->{params} });
1834         $sql = $n->{function}."($sql)";
1835     }
1836
1837     my $prefix = $self->prefix || '';
1838     my $suffix = $self->suffix || '';
1839     my $joiner = ' || ';
1840     $joiner = ' && ' if $self->prefix eq '!'; # Negative atoms should be "none of the variants" instead of "any of the variants"
1841
1842     $prefix = "'$prefix' ||" if $prefix;
1843     my $suffix_op = '';
1844     my $suffix_after = '';
1845
1846     $suffix_op = ":$suffix" if $suffix;
1847     $suffix_after = "|| '$suffix_op'" if $suffix;
1848
1849     my @sql_set = ();
1850     for my $ts_config (@$ts_configs) {
1851         push @sql_set, "to_tsquery('$ts_config', COALESCE(NULLIF($prefix '(' || btrim(regexp_replace($sql,E'(?:\\\\s+|:)','$suffix_op&','g'),'&|') $suffix_after || ')', '()'), ''))";
1852     }
1853
1854     $sql = join($joiner, @sql_set);
1855     $sql = '(' . $sql . ')' if (scalar(@$ts_configs) > 1);
1856
1857     return $self->sql($sql);
1858 }
1859
1860 #-------------------------------
1861 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::node;
1862 use base 'QueryParser::query_plan::node';
1863 use List::MoreUtils qw/uniq/;
1864 use Data::Dumper;
1865
1866 sub abstract_node_additions {
1867     my $self = shift;
1868     my $aq = shift;
1869
1870     my $hm = $self->plan
1871                 ->QueryParser
1872                 ->parse_tree
1873                 ->get_abstract_data('highlight_map') || {};
1874
1875     my $field_set = $self->fields;
1876     $field_set = $self->plan->QueryParser->search_fields->{$self->classname}
1877         if (!@$field_set);
1878
1879     my @field_ids = grep defined, (
1880         map {
1881             $self->plan->QueryParser->search_field_ids_by_class(
1882                 $self->classname, $_
1883             )->[0]
1884         } @$field_set
1885     );
1886
1887     push @field_ids, @{$self->{vfields}} if $self->{vfields};
1888
1889     my $ts_query = $self->tsquery_rank;
1890
1891     # We need to rework the hash so fields are only ever pointed at once.
1892     # That means if a field is already being looked at elsewhere then we'll
1893     # need to separate it out and combine its preexisting tsqueries.  This
1894     # will be fairly brute-force, and could be improved later, likely, with
1895     # a clever algorithm.
1896
1897     my %inverted_hm;
1898     for my $t (keys %$hm) {
1899         for my $f (@{$$hm{$t}}) {
1900             $inverted_hm{$f} = $t;
1901         }
1902     }
1903
1904     # Then, loop over new fields and put them in the inverted hash.
1905     my @existing_fields = keys %inverted_hm;
1906
1907     for my $f (@field_ids) {
1908         if (grep { $f == $_ } @existing_fields) { # We've seen the field, should we combine?
1909             my $t = $inverted_hm{$f};
1910             if ($t ne $ts_query) { # Different tsquery, do it!
1911                 $t .= ' || '. $ts_query;
1912                 $inverted_hm{$f} = $t;
1913             }
1914         } else { # New field
1915             $inverted_hm{$f} = $ts_query;
1916         }
1917     }
1918
1919     # Now, flip it back over.
1920     $hm = {};
1921     for my $f (keys %inverted_hm) {
1922         my $t = $inverted_hm{$f};
1923         if ($$hm{$t}) {
1924             push @{$$hm{$t}}, $f;
1925         } else {
1926             $$hm{$t} = [$f];
1927         }
1928     }
1929
1930     $self->plan
1931         ->QueryParser
1932         ->parse_tree
1933         ->set_abstract_data('highlight_map', $hm);
1934 }
1935
1936 sub add_vfield {
1937     my $self = shift;
1938     my $vfield = shift;
1939
1940     $self->{vfields} ||= [];
1941     push @{$self->{vfields}}, $vfield;
1942 }
1943
1944 sub only_atoms {
1945     my $self = shift;
1946
1947     $self->{dummy_count} = 0;
1948
1949     my $atoms = $self->query_atoms;
1950     my @only_atoms;
1951     for my $a (@$atoms) {
1952         push(@only_atoms, $a) if (ref($a) && $a->isa('QueryParser::query_plan::node::atom'));
1953         $self->{dummy_count}++ if (ref($a) && $a->{dummy});
1954     }
1955
1956     return \@only_atoms;
1957 }
1958
1959 sub only_real_atoms {
1960     my $self = shift;
1961
1962     my $atoms = $self->query_atoms;
1963     my @only_real_atoms;
1964     for my $a (@$atoms) {
1965         push(@only_real_atoms, $a) if (ref($a) && $a->isa('QueryParser::query_plan::node::atom') && !($a->{dummy}));
1966     }
1967
1968     return \@only_real_atoms;
1969 }
1970
1971 sub only_positive_atoms {
1972     my $self = shift;
1973
1974     my $atoms = $self->query_atoms;
1975     my @only_positive_atoms;
1976     for my $a (@$atoms) {
1977         push(@only_positive_atoms, $a) if (ref($a) && $a->isa('QueryParser::query_plan::node::atom') && !($a->{dummy}) && ($a->{prefix} ne '!'));
1978     }
1979
1980     return \@only_positive_atoms;
1981 }
1982
1983 sub dummy_count {
1984     my $self = shift;
1985     return $self->{dummy_count};
1986 }
1987
1988 sub table {
1989     my $self = shift;
1990     my $classname = shift || $self->classname;
1991     return 'metabib.' . $classname . '_field_entry';
1992 }
1993
1994 sub combined_table {
1995     my $self = shift;
1996     my $classname = shift || $self->classname;
1997     return 'metabib.combined_' . $classname . '_field_entry';
1998 }
1999
2000 sub combined_search {
2001     my $self = shift;
2002     return $self->plan->QueryParser->search_class_combined($self->classname);
2003 }
2004
2005 sub table_alias {
2006     my $self = shift;
2007     my $suffix = shift;
2008
2009     my $table_alias = "$self";
2010     $table_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
2011     $table_alias .= '_' . $self->requested_class;
2012     $table_alias =~ s/\|/_/go;
2013     $table_alias .= "_$suffix" if ($suffix);
2014
2015     return $table_alias;
2016 }
2017
2018 sub tsquery {
2019     my $self = shift;
2020     return $self->{tsquery} if ($self->{tsquery});
2021
2022     for my $atom (@{$self->query_atoms}) {
2023         if (ref($atom)) {
2024             $self->{tsquery} .= "\n" . ${spc} x 3 . $atom->sql;
2025         } else {
2026             $self->{tsquery} .= $atom x 2;
2027         }
2028     }
2029
2030     return $self->{tsquery};
2031 }
2032
2033 sub tsquery_rank {
2034     my $self = shift;
2035     return $self->{tsquery_rank} if ($self->{tsquery_rank});
2036     my @atomlines;
2037
2038     for my $atom (@{$self->only_positive_atoms}) {
2039         push @atomlines, "\n" . ${spc} x 3 . $atom->sql;
2040     }
2041     $self->{tsquery_rank} = join(' ||', @atomlines);
2042     $self->{tsquery_rank} = "''::tsquery" unless $self->{tsquery_rank};
2043     return $self->{tsquery_rank};
2044 }
2045
2046 sub rank {
2047     my $self = shift;
2048     return $self->{rank} if ($self->{rank});
2049
2050     my $rank_norm_map = $self->plan->QueryParser->custom_data->{rank_cd_weight_map};
2051
2052     my $cover_density = 0;
2053     for my $norm ( keys %$rank_norm_map) {
2054         $cover_density += $$rank_norm_map{$norm} if ($self->plan->QueryParser->parse_tree->find_modifier($norm));
2055     }
2056
2057     my $weights = join(', ', @{$self->plan->QueryParser->search_class_weights($self->classname)});
2058
2059     return $self->{rank} = "ts_rank_cd('{" . $weights . "}', " . $self->table_alias . '.index_vector, ' . $self->table_alias . ".tsq_rank, $cover_density)";
2060 }
2061
2062
2063 1;
2064