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