4 package OpenILS::Application::Storage::Driver::Pg::QueryParser;
5 use OpenILS::Application::Storage::QueryParser;
6 use base 'QueryParser';
7 use OpenILS::Utils::DateTime qw/:datetime/;
8 use OpenSRF::Utils::JSON;
9 use OpenILS::Application::AppUtils;
10 use OpenILS::Utils::CStoreEditor;
11 use OpenSRF::Utils::Logger qw($logger);
13 my $U = 'OpenILS::Application::AppUtils';
16 sub subquery_callback {
17 my ($invocant, $self, $struct, $filter, $params, $negate) = @_;
19 return sprintf(' ((%s)) ',
25 OpenILS::Utils::CStoreEditor
27 ->search_actor_search_query({ id => $params })
33 sub filter_group_entry_callback {
34 my ($invocant, $self, $struct, $filter, $params, $negate) = @_;
36 return sprintf(' saved_query(%s)',
42 OpenILS::Utils::CStoreEditor
44 ->search_actor_search_filter_group_entry({ id => $params })
51 my ($invocant, $self, $struct, $filter, $params, $negate) = @_;
54 my $negate_flag = ($negate ? '-' : '');
56 for my $param (@$params) {
57 my ($t,$f) = split('-', $param);
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;
65 $return = join(' || ', @returns);
66 $return = '(' . $return . ')' if(@returns > 1);
67 $return = $negate_flag.$return if($return);
75 if ($value =~ /^\d/) { # may have to use non-$ quoting
77 $value =~ s/\\/\\\\/g;
80 return "\$_$$\$$value\$_$$\$";
83 sub quote_phrase_value {
88 my $left_anchored = '';
89 my $right_anchored = '';
93 $left_anchored = $1 if $value =~ m/^([*\^])/;
94 $right_anchored = $1 if $value =~ m/([*\$])$/;
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+$/;
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);
115 sub default_preferred_language {
119 $self->custom_data->{default_preferred_language} = $lang if ($lang);
120 return $self->custom_data->{default_preferred_language};
123 sub default_preferred_language_multiplier {
127 $self->custom_data->{default_preferred_language_multiplier} = $lang if ($lang);
128 return $self->custom_data->{default_preferred_language_multiplier};
131 sub max_popularity_importance_multiplier {
135 $self->custom_data->{max_popularity_importance_multiplier} = $max if defined($max);
136 return $self->custom_data->{max_popularity_importance_multiplier};
143 $self->custom_data->{dbh} = $dbh if defined($dbh);
144 return $self->custom_data->{dbh};
150 return 0 unless $self->parse_tree;
151 return 0 if @{$self->parse_tree->filters};
152 return 0 if @{$self->parse_tree->modifiers};
153 for my $node ( @{ $self->parse_tree->query_nodes } ) {
154 return 0 if (!ref($node) && $node eq '|');
155 next unless (ref($node));
156 return 0 if ($node->isa('QueryParser::query_plan'));
164 return $self->parse_tree->toSQL;
167 sub dynamic_filters {
171 $self->custom_data->{dynamic_filters} ||= [];
172 push(@{$self->custom_data->{dynamic_filters}}, $new) if ($new);
173 return $self->custom_data->{dynamic_filters};
176 sub dynamic_sorters {
180 $self->custom_data->{dynamic_sorters} ||= [];
181 push(@{$self->custom_data->{dynamic_sorters}}, $new) if ($new);
182 return $self->custom_data->{dynamic_sorters};
185 sub facet_field_id_map {
189 $self->custom_data->{facet_field_id_map} ||= {};
190 $self->custom_data->{facet_field_id_map} = $map if ($map);
191 return $self->custom_data->{facet_field_id_map};
194 sub add_facet_field_id_map {
201 $self->add_facet_field( $class => $field );
202 $self->facet_field_id_map->{by_id}{$id} = { classname => $class, field => $field, weight => $weight };
203 $self->facet_field_id_map->{by_class}{$class}{$field} = $id;
206 by_id => { $id => { classname => $class, field => $field, weight => $weight } },
207 by_class => { $class => { $field => $id } }
211 sub facet_field_class_by_id {
215 return $self->facet_field_id_map->{by_id}{$id};
218 sub facet_field_ids_by_class {
223 return undef unless ($class);
226 return [$self->facet_field_id_map->{by_class}{$class}{$field}];
229 return [values( %{ $self->facet_field_id_map->{by_class}{$class} } )];
232 sub search_field_id_map {
236 $self->custom_data->{search_field_id_map} ||= {};
237 $self->custom_data->{search_field_id_map} = $map if ($map);
238 return $self->custom_data->{search_field_id_map};
241 sub search_field_virtual_map {
245 $self->custom_data->{search_field_virtual_map} ||= {};
246 $self->custom_data->{search_field_virtual_map} = $map if ($map);
247 return $self->custom_data->{search_field_virtual_map};
250 sub add_search_field_id_map {
256 my $combined = shift;
258 $self->add_search_field( $class => $field );
259 $self->search_field_id_map->{by_id}{$id} = { classname => $class, field => $field, weight => $weight };
260 $self->search_field_id_map->{by_class}{$class}{$field} = $id;
263 by_id => { $id => { classname => $class, field => $field, weight => $weight } },
264 by_class => { $class => { $field => $id } }
268 sub add_search_field_virtual_map {
274 $self->search_field_virtual_map->{by_virt}{$virtid} ||= [];
275 push @{$self->search_field_virtual_map->{by_virt}{$virtid}}, { real => $realid, weight => $weight };
277 $self->search_field_virtual_map->{by_real}{$realid} ||= [];
278 push @{$self->search_field_virtual_map->{by_real}{$realid}}, { virt => $virtid, weight => $weight };
281 sub search_field_class_by_id {
285 return $self->search_field_id_map->{by_id}{$id};
288 sub search_field_ids_by_class {
293 return undef unless ($class);
296 return [$self->search_field_id_map->{by_class}{$class}{$field}];
299 return [values( %{ $self->search_field_id_map->{by_class}{$class} } )];
302 sub relevance_bumps {
306 $self->custom_data->{rel_bumps} ||= {};
307 $self->custom_data->{rel_bumps} = $bumps if ($bumps);
308 return $self->custom_data->{rel_bumps};
311 sub find_relevance_bumps {
316 return $self->relevance_bumps->{$class}{$field};
319 sub add_relevance_bump {
324 my $multiplier = shift;
327 if (defined($active) and $active eq 'f') {
333 $self->relevance_bumps->{$class}{$field}{$type} = { multiplier => $multiplier, active => $active };
335 return { $class => { $field => { $type => { multiplier => $multiplier, active => $active } } } };
338 sub search_class_weights {
341 my $a_weight = shift;
342 my $b_weight = shift;
343 my $c_weight = shift;
344 my $d_weight = shift;
346 $self->custom_data->{class_weights} ||= {};
347 # Note: This reverses the A-D order, putting D first, because that is how the call actually works in PG
348 $self->custom_data->{class_weights}->{$class} ||= [0.1, 0.2, 0.4, 1.0];
349 $self->custom_data->{class_weights}->{$class} = [$d_weight, $c_weight, $b_weight, $a_weight] if $a_weight;
350 return $self->custom_data->{class_weights}->{$class};
353 sub search_class_combined {
358 $self->custom_data->{class_combined} ||= {};
359 # Note: This reverses the A-D order, putting D first, because that is how the call actually works in PG
360 $self->custom_data->{class_combined}->{$class} ||= 0;
361 $self->custom_data->{class_combined}->{$class} = 1 if $c && $c =~ /^(?:t|y|1)/i;
362 return $self->custom_data->{class_combined}->{$class};
365 sub class_ts_config {
368 my $lang = shift || 'DEFAULT';
370 my $ts_config = shift;
372 $self->custom_data->{class_ts_config} ||= {};
373 $self->custom_data->{class_ts_config}->{$class} ||= {};
374 $self->custom_data->{class_ts_config}->{$class}->{$lang} ||= {};
375 $self->custom_data->{class_ts_config}->{$class}->{$lang}->{normal} ||= [];
376 $self->custom_data->{class_ts_config}->{$class}->{$lang}->{always} ||= [];
377 $self->custom_data->{class_ts_config}->{$class}->{'DEFAULT'} ||= {};
378 $self->custom_data->{class_ts_config}->{$class}->{'DEFAULT'}->{normal} ||= [];
379 $self->custom_data->{class_ts_config}->{$class}->{'DEFAULT'}->{always} ||= [];
382 push @{$self->custom_data->{class_ts_config}->{$class}->{$lang}->{normal}}, $ts_config unless $always;
383 push @{$self->custom_data->{class_ts_config}->{$class}->{$lang}->{always}}, $ts_config if $always;
387 push @$return, @{$self->custom_data->{class_ts_config}->{$class}->{$lang}->{always}};
388 push @$return, @{$self->custom_data->{class_ts_config}->{$class}->{$lang}->{normal}} unless $always;
389 if($lang ne 'DEFAULT') {
390 push @$return, @{$self->custom_data->{class_ts_config}->{$class}->{'DEFAULT'}->{always}};
391 push @$return, @{$self->custom_data->{class_ts_config}->{$class}->{'DEFAULT'}->{normal}} unless $always;
396 sub field_ts_config {
400 my $lang = shift || 'DEFAULT';
401 my $ts_config = shift;
403 $self->custom_data->{field_ts_config} ||= {};
404 $self->custom_data->{field_ts_config}->{$class} ||= {};
405 $self->custom_data->{field_ts_config}->{$class}->{$field} ||= {};
406 $self->custom_data->{field_ts_config}->{$class}->{$field}->{$lang} ||= [];
407 $self->custom_data->{field_ts_config}->{$class}->{$field}->{'DEFAULT'} ||= [];
410 push @{$self->custom_data->{field_ts_config}->{$class}->{$field}->{$lang}}, $ts_config;
414 push @$return, @{$self->custom_data->{field_ts_config}->{$class}->{$field}->{$lang}};
415 if($lang ne 'DEFAULT') {
416 push @$return, @{$self->custom_data->{field_ts_config}->{$class}->{$field}->{'DEFAULT'}};
418 # Make it easy on us: Grab any "always" for the class here. If we have none we grab them all.
419 push @$return, @{$self->class_ts_config($class, $lang, scalar(@$return))};
423 sub initialize_search_field_id_map {
425 my $cmf_list = shift;
427 for my $cmf (@$cmf_list) {
428 __PACKAGE__->add_search_field_id_map( $cmf->field_class, $cmf->name, $cmf->id, $cmf->weight ) if ($U->is_true($cmf->search_field));
429 __PACKAGE__->add_facet_field_id_map( $cmf->field_class, $cmf->name, $cmf->id, $cmf->weight ) if ($U->is_true($cmf->facet_field));
432 return $self->search_field_id_map;
435 sub initialize_search_field_virtual_map {
437 my $cmfvm_list = shift;
439 __PACKAGE__->add_search_field_virtual_map( $_->real, $_->virtual, $_->weight )
442 $logger->debug('Virtual field map: ' . Dumper($self->search_field_virtual_map));
443 return $self->search_field_virtual_map;
446 sub initialize_aliases {
448 my $cmsa_list = shift;
450 for my $cmsa (@$cmsa_list) {
452 __PACKAGE__->add_search_class_alias( $cmsa->field_class, $cmsa->alias );
454 my $c = $self->search_field_class_by_id( $cmsa->field );
455 __PACKAGE__->add_search_field_alias( $cmsa->field_class, $c->{field}, $cmsa->alias );
460 sub initialize_relevance_bumps {
462 my $sra_list = shift;
464 for my $sra (@$sra_list) {
465 my $c = $self->search_field_class_by_id( $sra->field );
466 __PACKAGE__->add_relevance_bump( $c->{classname}, $c->{field}, $sra->bump_type, $sra->multiplier, $sra->active );
469 return $self->relevance_bumps;
472 sub initialize_query_normalizers {
474 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" }] }
476 for my $cmfinm ( @$tree ) {
477 my $field_info = $self->search_field_class_by_id( $cmfinm->field );
478 next unless $field_info;
479 __PACKAGE__->add_query_normalizer( $field_info->{classname}, $field_info->{field}, $cmfinm->norm->func, OpenSRF::Utils::JSON->JSON2perl($cmfinm->params) );
483 sub initialize_dynamic_filters {
485 my $list = shift; # open-ils.cstore.direct.config.record_attr_definition.search.atomic { "id" : { "!=" : null } }
487 for my $crad ( @$list ) {
488 __PACKAGE__->dynamic_filters( __PACKAGE__->add_search_filter( $crad->name ) ) if ($U->is_true($crad->filter));
489 __PACKAGE__->dynamic_sorters( $crad->name ) if ($U->is_true($crad->sorter));
493 sub initialize_filter_normalizers {
495 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" }] }
497 for my $crainm ( @$tree ) {
498 __PACKAGE__->add_filter_normalizer( $crainm->attr, $crainm->norm->func, OpenSRF::Utils::JSON->JSON2perl($crainm->params) );
502 sub initialize_search_class_weights {
506 for my $search_class (@$classes) {
507 __PACKAGE__->search_class_weights( $search_class->name, $search_class->a_weight, $search_class->b_weight, $search_class->c_weight, $search_class->d_weight );
508 __PACKAGE__->search_class_combined( $search_class->name, $search_class->combined );
512 sub initialize_class_ts_config {
514 my $class_entries = shift;
516 for my $search_class_entry (@$class_entries) {
517 __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);
521 sub initialize_field_ts_config {
523 my $field_entries = shift;
524 my $field_objects = shift;
525 my %field_hash = map { $_->id => $_ } @$field_objects;
527 for my $search_field_entry (@$field_entries) {
528 my $field_object = $field_hash{$search_field_entry->metabib_field};
529 __PACKAGE__->field_ts_config($field_object->field_class,$field_object->name,$search_field_entry->search_lang,$search_field_entry->ts_config);
534 sub initialization_complete {
542 return $_complete if ($_complete);
544 # tsearch rank normalization adjustments. see http://www.postgresql.org/docs/9.0/interactive/textsearch-controls.html#TEXTSEARCH-RANKING for details
545 $self->custom_data->{rank_cd_weight_map} = {
546 CD_logDocumentLength => 1,
547 CD_documentLength => 2,
548 CD_meanHarmonic => 4,
550 CD_logUniqueWords => 16,
554 $self->add_search_modifier( $_ ) for (keys %{ $self->custom_data->{rank_cd_weight_map} });
556 $self->initialize_search_field_id_map( $args{config_metabib_field} )
557 if ($args{config_metabib_field});
559 $self->initialize_search_field_virtual_map( $args{config_metabib_field_virtual_map} )
560 if ($args{config_metabib_field_virtual_map});
562 $self->initialize_aliases( $args{config_metabib_search_alias} )
563 if ($args{config_metabib_search_alias});
565 $self->initialize_relevance_bumps( $args{search_relevance_adjustment} )
566 if ($args{search_relevance_adjustment});
568 $self->initialize_query_normalizers( $args{config_metabib_field_index_norm_map} )
569 if ($args{config_metabib_field_index_norm_map});
571 $self->initialize_dynamic_filters( $args{config_record_attr_definition} )
572 if ($args{config_record_attr_definition});
574 $self->initialize_filter_normalizers( $args{config_record_attr_index_norm_map} )
575 if ($args{config_record_attr_index_norm_map});
577 $self->initialize_search_class_weights( $args{config_metabib_class} )
578 if ($args{config_metabib_class});
580 $self->initialize_class_ts_config( $args{config_metabib_class_ts_map} )
581 if ($args{config_metabib_class_ts_map});
583 $self->initialize_field_ts_config( $args{config_metabib_field_ts_map}, $args{config_metabib_field} )
584 if ($args{config_metabib_field_ts_map} && $args{config_metabib_field});
587 $args{config_metabib_field_index_norm_map} &&
588 $args{search_relevance_adjustment} &&
589 $args{config_metabib_search_alias} &&
590 $args{config_metabib_field} &&
591 $args{config_record_attr_definition}
599 __PACKAGE__->allow_nested_modifiers(1);
601 __PACKAGE__->add_search_field_id_map( series => seriestitle => 1 => 1 );
603 __PACKAGE__->add_search_field_id_map( series => seriestitle => 1 => 1 );
604 __PACKAGE__->add_relevance_bump( series => seriestitle => first_word => 1.5 );
605 __PACKAGE__->add_relevance_bump( series => seriestitle => full_match => 20 );
607 __PACKAGE__->add_search_field_id_map( title => abbreviated => 2 => 1 );
608 __PACKAGE__->add_relevance_bump( title => abbreviated => first_word => 1.5 );
609 __PACKAGE__->add_relevance_bump( title => abbreviated => full_match => 20 );
611 __PACKAGE__->add_search_field_id_map( title => translated => 3 => 1 );
612 __PACKAGE__->add_relevance_bump( title => translated => first_word => 1.5 );
613 __PACKAGE__->add_relevance_bump( title => translated => full_match => 20 );
615 __PACKAGE__->add_search_field_id_map( title => proper => 6 => 1 );
616 __PACKAGE__->add_query_normalizer( title => proper => 'search_normalize' );
617 __PACKAGE__->add_relevance_bump( title => proper => first_word => 1.5 );
618 __PACKAGE__->add_relevance_bump( title => proper => full_match => 20 );
619 __PACKAGE__->add_relevance_bump( title => proper => word_order => 10 );
621 __PACKAGE__->add_search_field_id_map( author => corporate => 7 => 1 );
622 __PACKAGE__->add_relevance_bump( author => corporate => first_word => 1.5 );
623 __PACKAGE__->add_relevance_bump( author => corporate => full_match => 20 );
625 __PACKAGE__->add_facet_field_id_map( author => personal => 8 => 1 );
627 __PACKAGE__->add_search_field_id_map( author => personal => 8 => 1 );
628 __PACKAGE__->add_relevance_bump( author => personal => first_word => 1.5 );
629 __PACKAGE__->add_relevance_bump( author => personal => full_match => 20 );
630 __PACKAGE__->add_query_normalizer( author => personal => 'search_normalize' );
631 __PACKAGE__->add_query_normalizer( author => personal => 'split_date_range' );
633 __PACKAGE__->add_facet_field_id_map( subject => topic => 14 => 1 );
635 __PACKAGE__->add_search_field_id_map( subject => topic => 14 => 1 );
636 __PACKAGE__->add_relevance_bump( subject => topic => first_word => 1 );
637 __PACKAGE__->add_relevance_bump( subject => topic => full_match => 1 );
639 __PACKAGE__->add_search_field_id_map( subject => complete => 16 => 1 );
640 __PACKAGE__->add_relevance_bump( subject => complete => first_word => 1 );
641 __PACKAGE__->add_relevance_bump( subject => complete => full_match => 1 );
643 __PACKAGE__->add_search_field_id_map( keyword => keyword => 15 => 1 );
644 __PACKAGE__->add_relevance_bump( keyword => keyword => first_word => 1 );
645 __PACKAGE__->add_relevance_bump( keyword => keyword => full_match => 1 );
647 __PACKAGE__->add_search_field_virtual_map( 6 => 15 => 5 );
649 __PACKAGE__->class_ts_config( 'series', undef, 1, 'english_nostop' );
650 __PACKAGE__->class_ts_config( 'title', undef, 1, 'english_nostop' );
651 __PACKAGE__->class_ts_config( 'author', undef, 1, 'english_nostop' );
652 __PACKAGE__->class_ts_config( 'subject', undef, 1, 'english_nostop' );
653 __PACKAGE__->class_ts_config( 'keyword', undef, 1, 'english_nostop' );
654 __PACKAGE__->class_ts_config( 'series', undef, 1, 'simple' );
655 __PACKAGE__->class_ts_config( 'title', undef, 1, 'simple' );
656 __PACKAGE__->class_ts_config( 'author', undef, 1, 'simple' );
657 __PACKAGE__->class_ts_config( 'subject', undef, 1, 'simple' );
658 __PACKAGE__->class_ts_config( 'keyword', undef, 1, 'simple' );
660 # French! To test language limiters
661 __PACKAGE__->class_ts_config( 'series', 'fre', 1, 'french_nostop' );
662 __PACKAGE__->class_ts_config( 'title', 'fre', 1, 'french_nostop' );
663 __PACKAGE__->class_ts_config( 'author', 'fre', 1, 'french_nostop' );
664 __PACKAGE__->class_ts_config( 'subject', 'fre', 1, 'french_nostop' );
665 __PACKAGE__->class_ts_config( 'keyword', 'fre', 1, 'french_nostop' );
667 # Not a default config by any means, but good for some testing
668 __PACKAGE__->field_ts_config( 'author', 'personal', 'eng', 'english' );
669 __PACKAGE__->field_ts_config( 'author', 'personal', 'fre', 'french' );
671 __PACKAGE__->add_search_class_alias( keyword => 'kw' );
672 __PACKAGE__->add_search_class_alias( title => 'ti' );
673 __PACKAGE__->add_search_class_alias( author => 'au' );
674 __PACKAGE__->add_search_class_alias( author => 'name' );
675 __PACKAGE__->add_search_class_alias( author => 'dc.contributor' );
676 __PACKAGE__->add_search_class_alias( subject => 'su' );
677 __PACKAGE__->add_search_class_alias( subject => 'bib.subject(?:Title|Place|Occupation)' );
678 __PACKAGE__->add_search_class_alias( series => 'se' );
679 __PACKAGE__->add_search_class_alias( keyword => 'dc.identifier' );
681 __PACKAGE__->add_query_normalizer( author => corporate => 'search_normalize' );
682 __PACKAGE__->add_query_normalizer( keyword => keyword => 'search_normalize' );
684 __PACKAGE__->add_search_field_alias( subject => name => 'bib.subjectName' );
686 #__PACKAGE__->search_class_combined( keyword => 1 );
687 __PACKAGE__->search_class_combined( author => 1 );
690 __PACKAGE__->default_search_class( 'keyword' );
692 # implements EG-specific stored subqueries
693 __PACKAGE__->add_search_filter( 'saved_query', sub { return __PACKAGE__->subquery_callback(@_) } );
694 __PACKAGE__->add_search_filter( 'filter_group_entry', sub { return __PACKAGE__->filter_group_entry_callback(@_) } );
696 # will be retained simply for back-compat
697 __PACKAGE__->add_search_filter( 'format', sub { return __PACKAGE__->format_callback(@_) } );
699 # grumble grumble, special cases against date1 and date2
700 __PACKAGE__->add_search_filter( 'before' );
701 __PACKAGE__->add_search_filter( 'after' );
702 __PACKAGE__->add_search_filter( 'between' );
703 __PACKAGE__->add_search_filter( 'during' );
705 # various filters for limiting in various ways
706 __PACKAGE__->add_search_filter( 'edit_date' );
707 __PACKAGE__->add_search_filter( 'create_date' );
708 __PACKAGE__->add_search_filter( 'statuses' );
709 __PACKAGE__->add_search_filter( 'locations' );
710 __PACKAGE__->add_search_filter( 'location_groups' );
711 __PACKAGE__->add_search_filter( 'bib_source' );
712 __PACKAGE__->add_search_filter( 'badge_orgs' );
713 __PACKAGE__->add_search_filter( 'badges' );
714 __PACKAGE__->add_search_filter( 'site' );
715 __PACKAGE__->add_search_filter( 'pref_ou' );
716 __PACKAGE__->add_search_filter( 'lasso' );
717 __PACKAGE__->add_search_filter( 'my_lasso' );
718 __PACKAGE__->add_search_filter( 'depth' );
719 __PACKAGE__->add_search_filter( 'language' );
720 __PACKAGE__->add_search_filter( 'offset' );
721 __PACKAGE__->add_search_filter( 'limit' );
722 __PACKAGE__->add_search_filter( 'check_limit' );
723 __PACKAGE__->add_search_filter( 'skip_check' );
724 __PACKAGE__->add_search_filter( 'superpage' );
725 __PACKAGE__->add_search_filter( 'superpage_size' );
726 __PACKAGE__->add_search_filter( 'estimation_strategy' );
727 __PACKAGE__->add_search_filter( 'from_metarecord' );
728 __PACKAGE__->add_search_filter( 'on_reserve' );
729 __PACKAGE__->add_search_modifier( 'available' );
730 __PACKAGE__->add_search_modifier( 'staff' );
731 __PACKAGE__->add_search_modifier( 'deleted' );
732 __PACKAGE__->add_search_modifier( 'lucky' );
734 # Start from container data (bre, acn, acp): container(bre,bookbag,123,deadb33fdeadb33fdeadb33fdeadb33f)
735 __PACKAGE__->add_search_filter( 'container' );
737 # Start from a list of record ids, either bre or metarecords, depending on the #metabib modifier
738 __PACKAGE__->add_search_filter( 'record_list' );
740 __PACKAGE__->add_search_filter( 'has_browse_entry' );
742 # copy_tag(copy_tag_code,copy_tag_search)
743 __PACKAGE__->add_search_filter( 'copy_tag' );
745 # used internally, but generally not user-settable
746 __PACKAGE__->add_search_filter( 'preferred_language' );
747 __PACKAGE__->add_search_filter( 'preferred_language_weight' );
748 __PACKAGE__->add_search_filter( 'preferred_language_multiplier' );
749 __PACKAGE__->add_search_filter( 'core_limit' );
751 # XXX Valid values to be supplied by SVF
752 __PACKAGE__->add_search_filter( 'sort' );
754 # modifies core query, not configurable
755 __PACKAGE__->add_search_modifier( 'descending' );
756 __PACKAGE__->add_search_modifier( 'ascending' );
757 __PACKAGE__->add_search_modifier( 'nullsfirst' );
758 __PACKAGE__->add_search_modifier( 'nullslast' );
759 __PACKAGE__->add_search_modifier( 'metarecord' );
760 __PACKAGE__->add_search_modifier( 'metabib' );
763 #-------------------------------
764 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan;
765 use base 'QueryParser::query_plan';
766 use OpenSRF::Utils::Logger qw($logger);
767 use OpenILS::Utils::DateTime qw/:datetime/;
769 use OpenILS::Application::AppUtils;
770 use OpenILS::Utils::Normalize qw/search_normalize/;
771 my $apputils = "OpenILS::Application::AppUtils";
773 our %_dfilter_controlled_cache = ();
774 our %_dfilter_stats_cache = ();
775 our $_pg_version = 0;
777 sub dynamic_filter_compile {
778 my ($self, $filter, $params, $negate) = @_;
779 my $e = OpenILS::Utils::CStoreEditor->new;
781 $negate = $negate ? '!' : '';
784 ($_pg_version = $e->json_query({from => ['version']})->[0]->{version}) =~ s/^.+?(\d\.\d).+$/$1/;
788 if ($_pg_version >= 9.2) {
789 if (!scalar keys %_dfilter_stats_cache) {
790 my $data = $e->json_query({from => ['evergreen.pg_statistics', 'record_attr_vector_list', 'vlist']});
791 %_dfilter_stats_cache = map {
792 ( $_->{element}, $_->{frequency} )
793 } grep { $_->{frequency} > 5 } @$data; # Pin floor to 5% of the table
796 $common = 1; # Assume it's expensive
799 if (!exists($_dfilter_controlled_cache{$filter})) {
800 my $crad = $e->retrieve_config_record_attr_definition($filter);
801 my $ccvm_list = $e->search_config_coded_value_map({ctype =>$filter});
803 $_dfilter_controlled_cache{$filter} = $crad->to_bare_hash;
804 $_dfilter_controlled_cache{$filter}{controlled} = scalar @$ccvm_list;
807 my $method = $_dfilter_controlled_cache{$filter}{controlled} ?
808 'search_config_coded_value_map' : 'search_metabib_uncontrolled_record_attr_value';
809 my $attr_field = $_dfilter_controlled_cache{$filter}{controlled} ?
811 my $value_field = $_dfilter_controlled_cache{$filter}{controlled} ?
814 my $attr_objects = $e->$method({ $attr_field => $filter, $value_field => $params });
815 $common = scalar(grep { exists($_dfilter_stats_cache{$_->id}) } @$attr_objects) unless $common;
817 return (sprintf('%s(%s)', $negate,
820 map { $_->id } @$attr_objects
830 for my $f ( qw/preferred_language preferred_language_multiplier preferred_language_weight core_limit check_limit skip_check superpage superpage_size/ ) {
832 $col = 'preferred_language_multiplier' if ($f eq 'preferred_language_weight');
833 my ($filter) = $self->find_filter($f);
834 if ($filter and @{$filter->args}) {
835 $filters{$col} = $filter->args->[0];
839 $self->QueryParser->superpage($filters{superpage}) if ($filters{superpage});
840 $self->QueryParser->superpage_size($filters{superpage_size}) if ($filters{superpage_size});
841 $self->QueryParser->core_limit($filters{core_limit}) if ($filters{core_limit});
843 $logger->debug("Query plan:\n".Dumper($self));
845 my $flat_plan = $self->flatten;
847 # generate the relevance ranking
848 my $rel = '1'; # Default to something simple in case rank_list is empty.
849 if (@{$$flat_plan{rank_list}}) {
852 . join(")\n" . ${spc} x 5 . "+ (", @{$$flat_plan{rank_list}})
854 . ${spc} x 4 . ")+1";
857 # find any supplied sort option
858 my ($sort_filter) = $self->find_filter('sort');
860 $sort_filter = $sort_filter->args->[0];
862 $sort_filter = 'rel';
866 if (($filters{preferred_language} || $self->QueryParser->default_preferred_language) && ($filters{preferred_language_multiplier} || $self->QueryParser->default_preferred_language_multiplier)) {
868 my $pl = $self->QueryParser->quote_value( $filters{preferred_language} ? $filters{preferred_language} : $self->QueryParser->default_preferred_language );
869 $$flat_plan{with} .= ',' if $$flat_plan{with};
870 $$flat_plan{with} .= "lang_with AS (SELECT id FROM config.coded_value_map WHERE ctype = 'item_lang' AND code = $pl)";
871 $lang_join = ",lang_with";
873 my $plw = $filters{preferred_language_multiplier} ? $filters{preferred_language_multiplier} : $self->QueryParser->default_preferred_language_multiplier;
874 $rel = "($rel * COALESCE( NULLIF( FIRST(mrv.vlist \@> ARRAY[lang_with.id]), FALSE )::INT * $plw, 1))";
875 $$flat_plan{uses_mrv} = 1;
879 if ($$flat_plan{uses_mrv}) {
880 $mrv_join = 'INNER JOIN metabib.record_attr_vector_list mrv ON m.source = mrv.source';
884 if ($$flat_plan{uses_mrd}) {
885 $mra_join = 'INNER JOIN metabib.record_attr mrd ON m.source = mrd.id';
888 my $pubdate_join = "LEFT JOIN metabib.record_sorter pubdate_t ON m.source = pubdate_t.source AND attr = 'pubdate'";
891 if ($self->find_modifier('deleted')) {
892 $bre_join = 'INNER JOIN biblio.record_entry bre ON m.source = bre.id AND bre.deleted';
893 # The above suffices for filters too when the #deleted modifier
896 $bre_join = 'INNER JOIN biblio.record_entry bre ON m.source = bre.id AND NOT bre.deleted';
900 $desc = 'DESC' if ($self->find_modifier('descending'));
902 my $nullpos = 'NULLS LAST';
903 $nullpos = 'NULLS FIRST' if ($self->find_modifier('nullsfirst'));
905 my $course_join = q{};
906 my $course_where = q{};
907 my ($course_filter) = $self->find_filter('on_reserve');
908 if ($course_filter) {
909 my $course_org_filter = q{};
910 if (@{$course_filter->args}) {
911 my @course_orgs = grep /^\d+$/, @{$course_filter->args};
912 # Don't filter by course OU if we didn't find any good candidate IDs.
913 # This way, users can do searches like `biology on_reserve(all)` to
914 # find matches from all org units' courses
915 if (@course_orgs > 0) {
916 my $course_orgs_with_descendants = [];
917 foreach ( @course_orgs ) {
918 push @$course_orgs_with_descendants, @{$U->get_org_descendants($_)};
920 my $course_org_string = join q{,}, @$course_orgs_with_descendants;
921 $course_org_filter .= "AND acmc.owning_lib IN ($course_org_string) ";
924 if ($course_filter->negate) {
925 $course_join .= ' LEFT JOIN (SELECT record FROM asset.course_module_course_materials acmcm';
926 $course_join .= " INNER JOIN asset.course_module_course acmc ON acmcm.course=acmc.id $course_org_filter ) cm";
927 $course_join .= ' ON cm.record=m.source';
928 $course_where .= ' AND cm.record IS NULL';
930 $course_join .= ' INNER JOIN asset.course_module_course_materials acmcm ON m.source = acmcm.record';
931 $course_join .= " INNER JOIN asset.course_module_course acmc ON acmcm.course=acmc.id $course_org_filter";
935 # Do we have a badges() filter?
937 my ($badge_filter) = $self->find_filter('badges');
938 if ($badge_filter && @{$badge_filter->args}) {
939 $badges = join (',', grep /^\d+$/, @{$badge_filter->args});
942 # Do we have a badge_orgs() filter? (used for calculating popularity)
944 my ($bo_filter) = $self->find_filter('badge_orgs');
945 if ($bo_filter && @{$bo_filter->args}) {
946 $borgs = join (',', grep /^\d+$/, @{$bo_filter->args});
949 # Build the badge-ish WITH query
950 my $pop_with = <<' WITH';
953 ARRAY_AGG(badge) AS badges,
954 SUM(s.score::NUMERIC*b.weight::NUMERIC)/SUM(b.weight::NUMERIC) AS total_score
955 FROM rating.record_badge_score s
956 JOIN rating.badge b ON (
960 $pop_with .= " AND b.id = ANY ('{$badges}')" if ($badges);
961 $pop_with .= " AND b.scope = ANY ('{$borgs}')" if ($borgs);
962 $pop_with .= ') GROUP BY 1)';
964 my $pop_join = $badges ? # inner join if we are restricting via badges()
965 'INNER JOIN pop_with ON ( m.source = pop_with.record )' :
966 'LEFT JOIN pop_with ON ( m.source = pop_with.record )';
968 $$flat_plan{with} .= ',' if $$flat_plan{with};
969 $$flat_plan{with} .= $pop_with;
973 my $pop_extra_sort = '';
974 if (grep {$_ eq $sort_filter} @{$self->QueryParser->dynamic_sorters}) {
975 $rank = "FIRST((SELECT value FROM metabib.record_sorter rbr WHERE rbr.source = m.source and attr = '$sort_filter'))"
976 } elsif ($sort_filter eq 'create_date') {
977 $rank = "FIRST((SELECT create_date FROM biblio.record_entry rbr WHERE rbr.id = m.source))";
978 } elsif ($sort_filter eq 'edit_date') {
979 $rank = "FIRST((SELECT edit_date FROM biblio.record_entry rbr WHERE rbr.id = m.source))";
980 } elsif ($sort_filter eq 'poprel') {
981 my $max_mult = $self->QueryParser->max_popularity_importance_multiplier() // 2.0;
982 $max_mult = 0.1 if $max_mult < 0.1; # keep it within reasonable bounds,
983 # and avoid the division-by-zero error
984 # you'd get if you allowed it to be
987 if ( $max_mult == 1.0 ) { # no adjustment requested by the configuration
988 $rank = "1.0/($rel)::NUMERIC";
989 } else { # calculate adjustment
991 # Scale the 0-5 effect of popularity badges by providing a multiplier
992 # for the badge average based on the overall maximum
993 # multiplier. Two examples, comparing the effect to the default
994 # $max_mult value of 2.0, which causes a $adjusted_scale value
997 # * Given the default $max_mult of 2.0, the value of
998 # $adjusted_scale will be 0.2 [($max_mult - 1.0) / 5.0].
999 # For a record whose average badge score is the maximum
1000 # of 5.0, that would make the relevance multiplier be
1002 # 1.0 + (5.0 [average score] * 0.2 [ $adjusted_scale ],
1003 # This would have the effect of doubling the effective
1004 # relevance of highly popular items.
1006 # * Given a $max_mult of 1.1, the value of $adjusted_scale
1007 # will be 0.02, meaning that the average badge value will be
1008 # multiplied by 0.02 rather than 0.2, then added to 1.0 and
1009 # used as a multiplier against the base relevance. Thus a
1010 # change of at most 10% to the base relevance for a record
1011 # with a 5.0 average badge score. This will allow records
1012 # that are naturally very relevant to avoid being pushed
1013 # below badge-heavy records.
1015 # * Given a $max_mult of 3.0, the value of $adjusted_scale
1016 # will be 0.4, meaning that the average badge value will be
1017 # multiplied by 0.4 rather than 0.2, then added to 1.0 and
1018 # used as a multiplier against the base relevance. Thus a
1019 # change of as much as 200% to (or three times the size of)
1020 # the base relevance for a record with a 5.0 average badge
1021 # score. This in turn will cause badges to outweigh
1022 # relevance to a very large degree.
1024 # The maximum badge multiplier can be set to a value less than
1025 # 1.0; this would have the effect of making less popular items
1026 # show up higher in the results. While this is not a likely
1027 # option for production use, it could be useful for identifying
1028 # interesting long-tail hits, particularly in a database
1029 # where enough badges are configured so that very few records
1030 # have an overage badge score of zero.
1032 my $adjusted_scale = ( $max_mult - 1.0 ) / 5.0;
1033 $rank = "1.0/(( $rel ) * (1.0 + (AVG(COALESCE(pop_with.total_score::NUMERIC,0.0::NUMERIC)) * ${adjusted_scale}::NUMERIC)))::NUMERIC";
1035 } elsif ($sort_filter =~ /^pop/) {
1036 $rank = '1.0/(AVG(COALESCE(pop_with.total_score::NUMERIC,0.0::NUMERIC)) + 5.0::NUMERIC)::NUMERIC';
1037 my $pop_desc = $desc eq 'ASC' ? 'DESC' : 'ASC';
1038 $pop_extra_sort = "3 $pop_desc $nullpos,";
1040 # default to rel ranking
1041 $rank = "1.0/($rel)::NUMERIC";
1044 my $key = 'm.source';
1045 $key = 'm.metarecord' if (grep {$_->name eq 'metarecord' or $_->name eq 'metabib'} @{$self->modifiers});
1047 my $core_limit = $self->QueryParser->core_limit || 'NULL';
1048 if ($self->find_modifier('lucky')) {
1049 $filters{check_limit} = 1;
1050 $filters{skip_check} = 0;
1055 my $flat_where = $$flat_plan{where};
1056 if ($flat_where ne '') {
1057 $flat_where = "AND (\n" . ${spc} x 5 . $flat_where . "\n" . ${spc} x 4 . ")";
1060 my $final_c_attr_test;
1061 my $c_attr_join = '';
1062 my $c_vis_test = '';
1063 my $pc_vis_test = '';
1065 # copy visibility testing
1066 if (!$self->find_modifier('staff')) {
1067 $pc_vis_test = "c_attrs";
1068 $c_attr_join = ",c_attr"
1071 if ($self->find_modifier('available')) {
1072 push @{$$flat_plan{vis_filter}{'c_attr'}},
1073 "search.calculate_visibility_attribute_test('status','{0,7,12}')";
1076 if (@{$$flat_plan{vis_filter}{c_attr}}) {
1077 $c_vis_test = join(",",@{$$flat_plan{vis_filter}{c_attr}});
1078 $c_attr_join = ',c_attr';
1081 if ($c_vis_test or $pc_vis_test) {
1084 if ($c_vis_test and $pc_vis_test) {
1085 $vis_test = $pc_vis_test . ",". $c_vis_test;
1086 } elsif ($pc_vis_test) {
1087 $vis_test = $pc_vis_test;
1089 $vis_test = $c_vis_test;
1092 # WITH-clause just generates vis test
1093 $$flat_plan{with} .= "\n," if $$flat_plan{with};
1094 $$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 OFFSET 0)";
1096 $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)';
1099 if ($self->find_modifier('staff') && !$self->find_modifier('available') && !$self->find_filter('locations') && !$self->find_filter('location_groups')) {
1100 $final_c_attr_test ||= 'FALSE';
1101 $final_c_attr_test = '(' . $final_c_attr_test . " OR (" .
1102 "NOT EXISTS (SELECT 1 FROM asset.copy_vis_attr_cache WHERE record = m.source) " .
1103 "AND (bre.vis_attr_vector IS NULL OR NOT ( int4range(0,268435455,'[]') @> ANY(bre.vis_attr_vector) ))".
1105 # We need bre here, regardless
1106 $bre_join ||= 'INNER JOIN biblio.record_entry bre ON m.source = bre.id AND NOT bre.deleted';
1109 my $final_b_attr_test;
1110 my $b_attr_join = '';
1111 my $b_vis_test = '';
1112 my $pb_vis_test = '';
1114 # bib visibility testing
1115 if (!$self->find_modifier('staff')) {
1116 $pb_vis_test = "b_attrs";
1117 $b_attr_join = ",b_attr"
1120 if (@{$$flat_plan{vis_filter}{b_attr}}) {
1121 $b_attr_join = ',b_attr ';
1122 $b_vis_test = join("||'&'||",@{$$flat_plan{vis_filter}{b_attr}});
1125 # bib vis tests are handled a little bit differently, as they're simpler but need special handling
1126 if ($b_vis_test or $pb_vis_test) {
1129 if ($b_vis_test and $pb_vis_test) { # $pb_vis_test supplies a query_int operator at its end
1130 $vis_test = $pb_vis_test . '||'. $b_vis_test;
1131 } elsif ($pb_vis_test) { # here we want to remove it
1132 $vis_test = "RTRIM($pb_vis_test,'|&')";
1134 $vis_test = $b_vis_test;
1137 # WITH-clause just generates vis test
1138 $$flat_plan{with} .= "\n," if $$flat_plan{with};
1139 $$flat_plan{with} .= "b_attr AS (SELECT ($vis_test)::query_int AS vis_test FROM asset.patron_default_visibility_mask() x OFFSET 0)";
1141 # These are magic numbers... see: search.calculate_visibility_attribute() UDF
1142 $final_b_attr_test = '(b_attr.vis_test IS NULL OR bre.vis_attr_vector @@ b_attr.vis_test)';
1145 if ($final_c_attr_test or $final_b_attr_test) { # something...
1146 if ($final_c_attr_test and $final_b_attr_test) { # both!
1147 my $plan = "($final_c_attr_test) OR ($final_b_attr_test)";
1148 $flat_where .= "\n" . ${spc} x 4 . "AND (\n" . ${spc} x 5 . $plan . "\n" . ${spc} x 4 . ")";
1149 } elsif ($final_c_attr_test) { # just copies...
1150 $flat_where .= "\n" . ${spc} x 4 . "AND (\n" . ${spc} x 5 . $final_c_attr_test . "\n" . ${spc} x 4 . ")";
1151 } else { # just bibs...
1152 $flat_where .= "\n" . ${spc} x 4 . "AND (\n" . ${spc} x 5 . $final_b_attr_test . "\n" . ${spc} x 4 . ")";
1156 my $with = $$flat_plan{with};
1157 $with= "\nWITH $with" if $with;
1159 # Need an array for query parser db function; this gives a better plan
1160 # than the ARRAY_AGG(DISTINCT m.source) option as of PostgreSQL 9.1
1161 my $agg_records = 'ARRAY[m.source] AS records';
1162 if ($key =~ /metarecord/) {
1163 # metarecord searches still require the ARRAY_AGG approach
1164 $agg_records = 'ARRAY_AGG(DISTINCT m.source) AS records';
1173 CASE WHEN cardinality(records) = 1 THEN records[1] ELSE NULL END AS record,
1175 NULL::INT AS checked,
1176 NULL::INT AS visible,
1177 NULL::INT AS deleted,
1178 NULL::INT AS excluded,
1181 FROM (SELECT $key AS id,
1183 ${rel}::NUMERIC AS rel,
1185 FIRST(pubdate_t.value) AS tie_break,
1186 STRING_AGG(ARRAY_TO_STRING(pop_with.badges,','),',') AS badges,
1187 AVG(COALESCE(pop_with.total_score::NUMERIC,0.0::NUMERIC))::NUMERIC(2,1) AS popularity
1188 FROM metabib.metarecord_source_map m
1203 ORDER BY 4 $desc $nullpos, $pop_extra_sort 5 DESC $nullpos, 3 DESC
1206 ) (SELECT * FROM w LIMIT $filters{check_limit} OFFSET $filters{skip_check})
1208 SELECT NULL,NULL,NULL,COUNT(*),COUNT(*),COUNT(*),0,0,NULL,NULL FROM w;
1211 warn $sql if $self->QueryParser->debug;
1216 sub is_org_visible {
1218 return 0 if (!$U->is_true($org->opac_visible));
1220 my $non_inherited_vis_gf = shift || $U->get_global_flag('opac.org_unit.non_inherited_visibility');
1221 return 1 if ($U->is_true($non_inherited_vis_gf->enabled));
1223 while ($org = $org->parent_ou) {
1224 return 0 if (!$U->is_true($org->opac_visible));
1231 my $kids = $t->children;
1232 if ($kids && @$kids) {
1233 map {$_->parent_ou($t); flesh_parents($_)} @$kids;
1237 sub unflesh_parents {
1239 my $kids = $t->children;
1240 if ($kids && @$kids) {
1241 map {$_->parent_ou($t->id); unflesh_parents($_)} @$kids;
1248 die 'ERROR: nesting too deep or boolean list too long' if ($self->plan_level > 40);
1250 my $from = shift || '';
1251 my $where = shift || '';
1253 my %vis_filter = ( c_attr => [], b_attr => [] );
1259 for my $node ( @{$self->query_nodes} ) {
1262 if ($node->isa( 'QueryParser::query_plan::node' )) {
1264 unless (@{$node->only_atoms}) {
1265 push @rank_list, '1';
1272 if (@{$node->fields} > 0) {
1273 @bump_fields = @{$node->fields};
1275 @field_ids = grep defined, (
1277 $self->QueryParser->search_field_ids_by_class(
1278 $node->classname, $_
1283 @bump_fields = @{$self->QueryParser->search_fields->{$node->classname}};
1286 # use search_field_list to handle virtual index defs
1287 my $search_field_list = $self->QueryParser->search_field_ids_by_class($node->classname);
1288 $search_field_list = [@field_ids] if (@field_ids);
1290 my $table = $node->table;
1291 my $ctable = $node->combined_table;
1292 my $talias = $node->table_alias;
1294 my $node_rank = 'COALESCE(' . $node->rank . " * ${talias}.weight * 1000, 0.0)";
1296 my $search_cte = ",\n $talias AS (\n"
1297 . ${spc} x 5 . "SELECT fe.*, fe_weight.weight, ${talias}_xq.tsq, ${talias}_xq.tsq_rank /* search */\n"
1298 . ${spc} x 6 . "FROM $table AS fe\n"
1299 . ${spc} x 7 . "JOIN config.metabib_field AS fe_weight ON (fe_weight.id = fe.field)";
1301 if ($node->dummy_count < @{$node->only_atoms} or @{$node->phrases}) {
1302 $with .= ",\n " if $with;
1303 $with .= "${talias}_xq AS (SELECT ". $node->tsquery ." AS tsq,". $node->tsquery_rank ." AS tsq_rank )";
1304 if ($node->combined_search) {
1305 $search_cte .= "\n" . ${spc} x 7 . "JOIN $ctable AS com ON (com.record = fe.source";
1307 $search_cte .= " AND com.metabib_field IN (" . join(',',@field_ids) . "))";
1309 $search_cte .= " AND com.metabib_field IS NULL)";
1311 $search_cte .= "\n" . ${spc} x 7 . "JOIN ${talias}_xq ON (com.index_vector @@ ${talias}_xq.tsq)";
1313 $search_cte .= "\n" . ${spc} x 7 . "JOIN ${talias}_xq ON (fe.index_vector @@ ${talias}_xq.tsq)";
1316 $search_cte .= "\n" . ${spc} x 7 . ", (SELECT NULL::tsquery AS tsq, NULL::tsquery AS tsq_rank ) AS ${talias}_xq";
1320 $search_cte .= "\n" . ${spc} x 6 . "WHERE fe_weight.id IN (" .
1321 join(',', @field_ids) . ")";
1324 # Even though virtual fields have all the real field data in
1325 # their combined version, and thus a search against the real
1326 # fields is not necessary to match records, we still want to
1327 # UNION them in so we can get their virtual weight if they
1328 # would match a search directly against them.
1329 if ($node->dummy_count < @{$node->only_atoms} ) { # no point in searching real fields with no search terms
1330 for my $possible_vfield (@$search_field_list) {
1331 my $real_fields = $self->QueryParser->search_field_virtual_map->{by_virt}->{$possible_vfield};
1332 if ($real_fields and @$real_fields) { # this is a virt field
1333 my %vtable_field_map;
1335 # UNION in the others ... group by class
1336 for my $real_field (@$real_fields) {
1337 my $natural_field = $self->QueryParser->search_field_id_map->{by_id}{$$real_field{real}};
1339 $node->add_vfield($$real_field{real});
1340 $logger->debug("Looking up virtual field for real field $$real_field{real}");
1341 my $vtable = $node->table(
1343 ->search_field_class_by_id($$real_field{real})
1346 $vtable_field_map{$vtable} ||= [];
1347 push(@{$vtable_field_map{$vtable}}, $$real_field{real})
1348 if ($$real_field{weight} != $$natural_field{weight});
1351 for my $vtable (keys %vtable_field_map) {
1352 my $rfields = $vtable_field_map{$vtable};
1353 next unless (@$rfields);
1355 # NOTE: only real fields that match the (component) tsquery will
1356 # get to contribute to and increased rank for the record.
1357 $search_cte .= "\n" . ${spc} x 8 . "UNION ALL\n"
1358 . ${spc} x 5 . "SELECT fe.id, fe.source, fe.field, fe.value, fe.index_vector, "
1359 . "fe_weight.weight, ${talias}_xq.tsq, ${talias}_xq.tsq_rank /* virtual field addition */\n"
1360 . ${spc} x 6 . "FROM $vtable AS fe\n"
1361 . ${spc} x 7 . "JOIN config.metabib_field_virtual_map AS fe_weight ON ("
1362 ."fe_weight.virtual = $possible_vfield AND "
1363 ."fe_weight.real IN (".join(',',@$rfields).") AND "
1364 ."fe_weight.real = fe.field)\n"
1365 . ${spc} x 7 . "JOIN ${talias}_xq ON (fe.index_vector @@ ${talias}_xq.tsq)"
1372 $with .= $search_cte . ')';
1373 $from .= "\n" . ${spc} x 4 . "LEFT JOIN $talias ON (m.source = ${talias}.source)";
1378 for my $field ( @bump_fields ) {
1379 my $bumps = $self->QueryParser->find_relevance_bumps( $node->classname => $field );
1380 for my $b (keys %$bumps) {
1381 next if (!$$bumps{$b}{active});
1382 next if ($used_bumps{$b});
1383 $used_bumps{$b} = 1;
1385 next if ($$bumps{$b}{multiplier} == 1); # optimization to remove unneeded bumps
1387 push @bumpmults, $$bumps{$b}{multiplier};
1391 if(scalar @bumps > 0 && scalar @{$node->only_positive_atoms} > 0) {
1392 # Note: Previous rank function used search_normalize outright. Duplicating that here.
1393 $node_rank .= "\n" . ${spc} x 5 . "* COALESCE(evergreen.rel_bump(('{' || quote_literal(search_normalize(";
1394 $node_rank .= join(")) || ',' || quote_literal(search_normalize(",map { $self->QueryParser->quote_phrase_value($_->content) } @{$node->only_positive_atoms});
1395 $node_rank .= ")) || '}')::TEXT[], " . $node->table_alias . ".value, '{" . join(",",@bumps) . "}'::TEXT[], '{" . join(",",@bumpmults) . "}'::NUMERIC[]),1.0)";
1399 $NOT = 'NOT ' if $node->negate;
1401 $where .= "$NOT(" . $talias . ".id IS NOT NULL";
1402 for my $atom (@{$node->only_real_atoms}) { # left and right anchored substring match (prefix / suffix search)
1403 next unless $atom->{content} && $atom->{content} =~ /(^\^|\$$)/;
1404 $where .= " AND ${talias}.value ~* ".$self->QueryParser->quote_phrase_value($atom->{content});
1408 push @rank_list, $node_rank;
1410 } elsif ($node->isa( 'QueryParser::query_plan::facet' )) {
1412 my $talias = $node->table_alias;
1415 if (@{$node->fields} > 0) {
1416 push(@field_ids, $self->QueryParser->facet_field_ids_by_class( $node->classname, $_ )->[0]) for (@{$node->fields});
1418 @field_ids = @{ $self->QueryParser->facet_field_ids_by_class( $node->classname ) };
1421 my $join_type = ($node->negate or !$self->top_plan) ? 'LEFT' : 'INNER';
1422 $from .= "\n${spc}$join_type JOIN /* facet */ metabib.facet_entry $talias ON (\n"
1423 . ${spc} x 2 . "m.source = ${talias}.source\n"
1424 . ${spc} x 2 . "AND SUBSTRING(${talias}.value,1,1024) IN ("
1425 . join(",", map { $self->QueryParser->quote_value($_) } @{$node->values}) . ")\n"
1426 . ${spc} x 2 ."AND ${talias}.field IN (". join(',', @field_ids) . ")\n"
1429 if ($join_type ne 'INNER') {
1430 my $NOT = $node->negate ? '' : ' NOT';
1431 $where .= "${talias}.id IS$NOT NULL";
1432 } elsif ($where ne '') {
1433 # Strip extra joiner
1434 $where =~ s/(\s|\n)+(AND|OR)\s$//;
1438 my $subnode = $node->flatten;
1440 # strip the trailing bool from the previous loop if there is
1441 # nothing to add to the where within this loop.
1442 if ($$subnode{where} eq '') {
1443 $where =~ s/(\s|\n)+(AND|OR)\s$//;
1446 push(@rank_list, @{$$subnode{rank_list}});
1447 $from .= $$subnode{from};
1450 $NOT = 'NOT ' if $node->negate;
1452 if ($$subnode{where} ne '') {
1454 . ${spc} x ($self->plan_level + 6) . $$subnode{where} . "\n"
1455 . ${spc} x ($self->plan_level + 5) . ')';
1458 if ($$subnode{with}) {
1459 $with .= ",\n " if $with;
1460 $with .= $$subnode{with};
1463 $uses_bre = $$subnode{uses_bre};
1464 $uses_mrd = $$subnode{uses_mrd};
1465 $uses_mrv = $$subnode{uses_mrv};
1469 warn "flatten(): appending WHERE bool to: $where\n" if $self->QueryParser->debug;
1472 $where .= "\n" . ${spc} x ( $self->plan_level + 5 ) . 'AND ' if ($node eq '&');
1473 $where .= "\n" . ${spc} x ( $self->plan_level + 5 ) . 'OR ' if ($node eq '|');
1478 my $joiner = "\n" . ${spc} x ( $self->plan_level + 5 ) . ($self->joiner eq '&' ? 'AND ' : 'OR ');
1480 my ($depth_filter) = grep { $_->name eq 'depth' } @{$self->filters};
1481 if ($depth_filter and @{$depth_filter->args} == 1) {
1482 $depth_filter = $depth_filter->args->[0];
1485 my $ot = $U->get_org_tree;
1487 my $negate = 'FALSE';
1490 my ($lasso_filter) = grep { $_->name eq 'lasso' } @{$self->filters};
1491 if ($lasso_filter and @{$lasso_filter->args} == 1) {
1492 $negate = $lasso_filter->negate ? 'TRUE' : 'FALSE';
1494 my $lasso = $lasso_filter->args->[0];
1495 if ($lasso !~ /^\d+$/) {
1496 $lasso = $U->find_lasso_by_name($lasso);
1500 $lasso = $lasso->id if (ref $lasso);
1501 @lasso_list = map { $_->org_unit } @{ $U->fetch_lasso_org_maps($lasso) };
1507 my ($site_filter) = grep { $_->name eq 'site' } @{$self->filters};
1508 if ($site_filter and @{$site_filter->args} == 1) {
1509 $negate = $site_filter->negate ? 'TRUE' : 'FALSE';
1511 my $sitename = $site_filter->args->[0];
1512 $site_org = $U->find_org_by_shortname($ot, $sitename) || $ot;
1516 my $dorgs = scalar(@lasso_list) ? [@lasso_list] : $U->get_org_descendants($site_org->id, $depth_filter);
1517 my $aorgs = $U->get_org_ancestors($site_org->id);
1520 if (!$self->find_modifier('staff')) {
1521 my $non_inherited_vis_gf = $U->get_global_flag('opac.org_unit.non_inherited_visibility');
1522 $dorgs = [ grep { is_org_visible($U->find_org($ot,$_), $non_inherited_vis_gf) } @$dorgs ];
1523 $aorgs = [ grep { is_org_visible($U->find_org($ot,$_), $non_inherited_vis_gf) } @$aorgs ];
1525 unflesh_parents($ot);
1527 push @{$vis_filter{'c_attr'}},
1528 "search.calculate_visibility_attribute_test('circ_lib','{".join(',', @$dorgs)."}',$negate)";
1530 # NOTE: both lassos and shelving locations preclude Located URI search
1531 if (!$lasso_filter && !$self->find_filter('locations') && !$self->find_filter('location_groups')) {
1532 my $lorgs = [@$aorgs];
1533 my $luri_as_copy_gf = $U->get_global_flag('opac.located_uri.act_as_copy');
1534 push @$lorgs, @$dorgs if ($luri_as_copy_gf and $U->is_true($luri_as_copy_gf->enabled));
1537 push @{$vis_filter{'b_attr'}},
1538 "search.calculate_visibility_attribute_test('luri_org','{".join(',', @$lorgs)."}',$negate)";
1543 # for each dynamic filter, build more of the WHERE clause
1544 for my $filter (@{$self->filters}) {
1545 my $NOT = $filter->negate ? 'NOT ' : '';
1546 if (grep { $_ eq $filter->name } @{ $self->QueryParser->dynamic_filters }) {
1548 my $fname = $filter->name;
1549 $fname = 'item_lang' if $fname eq 'language'; #XXX filter aliases
1551 warn "flatten(): processing dynamic filter ". $filter->name ."\n"
1552 if $self->QueryParser->debug;
1555 ($vlist_query, $common) = $self->dynamic_filter_compile( $fname, $filter->args, $filter->negate );
1557 # bool joiner for intra-plan nodes/filters
1558 push(@dlist, $self->joiner) if @dlist;
1559 push(@dlist, $vlist_query);
1562 if ($filter->name eq 'before') {
1563 if (@{$filter->args} == 1) {
1564 $where .= $joiner if $where ne '';
1565 $where .= "${NOT}COALESCE(pubdate_t.value <= "
1566 . $self->QueryParser->quote_value($filter->args->[0])
1569 } elsif ($filter->name eq 'after') {
1570 if (@{$filter->args} == 1) {
1571 $where .= $joiner if $where ne '';
1572 $where .= "${NOT}COALESCE(pubdate_t.value >= "
1573 . $self->QueryParser->quote_value($filter->args->[0])
1576 } elsif ($filter->name eq 'during') {
1577 if (@{$filter->args} == 1) {
1578 $where .= $joiner if $where ne '';
1579 $where .= "${NOT}COALESCE("
1580 . $self->QueryParser->quote_value($filter->args->[0])
1581 . " BETWEEN pubdate_t.value AND (mrd.attrs->'date2'), false)";
1584 } elsif ($filter->name eq 'between') {
1585 if (@{$filter->args} == 2) {
1586 $where .= $joiner if $where ne '';
1587 $where .= "${NOT}COALESCE(pubdate_t.value BETWEEN "
1588 . $self->QueryParser->quote_value($filter->args->[0])
1590 . $self->QueryParser->quote_value($filter->args->[1])
1593 } elsif ($filter->name eq 'container') {
1594 if (@{$filter->args} >= 3) {
1595 my ($class, $ctype, $cid, $token) = @{$filter->args};
1598 my $rec_field = 'ci.target_biblio_record_entry';
1599 if ($class eq 'bre') {
1600 $class = 'biblio_record_entry';
1601 } elsif ($class eq 'acn') {
1602 $class = 'call_number';
1603 $rec_field = 'cn.record';
1604 $rec_join = 'JOIN asset.call_number cn ON (ci.target_call_number = cn.id)';
1605 } elsif ($class eq 'acp') {
1607 $rec_field = 'cn.record';
1608 $rec_join = 'JOIN asset.copy cp ON (ci.target_copy = cp.id) JOIN asset.call_number cn ON (cp.call_number = cn.id)';
1614 my ($u,$e) = $apputils->checksesperm($token) if ($token);
1615 $perm_join = ' OR c.owner = ' . $u->id if ($u && !$e);
1617 my $filter_alias = "$filter";
1618 $filter_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1619 $filter_alias =~ s/\|/_/go;
1621 $with .= ",\n " if $with;
1622 $with .= "container_${filter_alias} AS (\n";
1623 $with .= " SELECT $rec_field AS record FROM container.${class}_bucket_item ci\n"
1624 . " JOIN container.${class}_bucket c ON (c.id = ci.bucket) $rec_join\n"
1625 . " WHERE c.btype = " . $self->QueryParser->quote_value($ctype) . "\n"
1626 . " AND c.id = " . $self->QueryParser->quote_value($cid) . "\n"
1627 . " AND (c.pub IS TRUE$perm_join)\n";
1628 if ($class eq 'copy') {
1630 . " SELECT pr.peer_record AS record FROM container.copy_bucket_item ci\n"
1631 . " JOIN container.copy_bucket c ON (c.id = ci.bucket)\n"
1632 . " JOIN biblio.peer_bib_copy_map pr ON ci.target_copy = pr.target_copy\n"
1633 . " WHERE c.btype = " . $self->QueryParser->quote_value($ctype) . "\n"
1634 . " AND c.id = " . $self->QueryParser->quote_value($cid) . "\n"
1635 . " AND (c.pub IS TRUE$perm_join)\n";
1639 my $optimize_join = 1 if $self->top_plan and !$NOT;
1640 $from .= "\n" . ${spc} x 3 . ( $optimize_join ? 'INNER' : 'LEFT') . " JOIN container_${filter_alias} ON container_${filter_alias}.record = m.source";
1642 if (!$optimize_join) {
1643 $where .= $joiner if $where ne '';
1644 $where .= "(container_${filter_alias} IS " . ( $NOT ? 'NULL)' : 'NOT NULL)');
1648 } elsif ($filter->name eq 'copy_tag') {
1649 my $valid_copy_tag_search = 0;
1652 if (@{$filter->args} >= 2) { # must have at least two parts, tag (or *) and terms
1653 my @fargs = @{$filter->args};
1654 $copy_tag_type = shift(@fargs);
1655 $tag_value = join(' ', @fargs);
1656 $valid_copy_tag_search = 1;
1658 if ($valid_copy_tag_search) {
1659 my $norm_value = search_normalize($tag_value);
1660 my @tokens = split /\s+/, $norm_value;
1662 my $filter_alias = "$filter";
1663 $filter_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1664 $filter_alias =~ s/\|/_/go;
1666 $with .= ",\n " if $with;
1667 $with .= "copy_tag_${filter_alias} AS (\n";
1668 $with .= " SELECT cn.record AS record FROM config.copy_tag_type cctt\n";
1669 $with .= " JOIN asset.copy_tag acpt ON (cctt.code = acpt.tag_type)\n";
1670 $with .= " JOIN asset.copy_tag_copy_map acptcm ON (acpt.id = acptcm.tag)\n";
1671 $with .= " JOIN asset.copy cp ON (acptcm.copy = cp.id)\n";
1672 $with .= " JOIN asset.call_number cn ON (cp.call_number = cn.id)\n";
1673 $with .= " WHERE 1 = 1 \n";
1674 $with .= " AND cp.circ_lib IN (" . join(',', @$dorgs) . ")\n";
1675 if ($copy_tag_type ne '*') {
1676 $with .= " AND cctt.code = " . $self->QueryParser->quote_value($copy_tag_type) . "\n";
1679 $with .= ' AND acpt.value @@ to_tsquery(' . $self->QueryParser->quote_value(join(' & ', @tokens)) . ")\n";
1681 if (!$self->find_modifier('staff')) {
1682 $with .= " AND acpt.pub IS TRUE\n";
1686 my $optimize_join = 1 if $self->top_plan and !$NOT;
1687 $from .= "\n" . ${spc} x 3 . ( $optimize_join ? 'INNER' : 'LEFT') . " JOIN copy_tag_${filter_alias} ON copy_tag_${filter_alias}.record = m.source";
1689 if (!$optimize_join) {
1690 $where .= $joiner if $where ne '';
1691 $where .= "(copy_tag_${filter_alias} IS " . ( $NOT ? 'NULL)' : 'NOT NULL)');
1694 } elsif ($filter->name eq 'record_list') {
1695 if (@{$filter->args} > 0) {
1696 my $key = 'm.source';
1697 $key = 'm.metarecord' if (grep {$_->name eq 'metarecord' or $_->name eq 'metabib'} @{$self->QueryParser->parse_tree->modifiers});
1698 $where .= $joiner if $where ne '';
1699 $where .= "$key ${NOT}IN (" . join(',', map { $self->QueryParser->quote_value($_) } @{$filter->args}) . ')';
1702 } elsif ($filter->name eq 'locations') {
1703 if (@{$filter->args} > 0) {
1704 my $negate = $filter->negate ? 'TRUE' : 'FALSE';
1705 my $filter_args = join(",", map(int, @{$filter->args}));
1706 push @{$vis_filter{'c_attr'}},
1707 "search.calculate_visibility_attribute_test('location','{$filter_args}',$negate)";
1710 } elsif ($filter->name eq 'location_groups') {
1711 if (@{$filter->args} > 0) {
1712 my $negate = $filter->negate ? 'TRUE' : 'FALSE';
1713 my $filter_args = join(",", map(int, @{$filter->args}));
1714 push @{$vis_filter{'c_attr'}},
1715 "search.calculate_visibility_attribute_test('location',(SELECT ARRAY_AGG(location) FROM asset.copy_location_group_map WHERE lgroup IN ($filter_args)),$negate)";
1718 } elsif ($filter->name eq 'statuses') {
1719 if (@{$filter->args} > 0) {
1720 my $negate = $filter->negate ? 'TRUE' : 'FALSE';
1721 push @{$vis_filter{'c_attr'}},
1722 "search.calculate_visibility_attribute_test('status','{".join(',', @{$filter->args})."}',$negate)";
1725 } elsif ($filter->name eq 'has_browse_entry') {
1726 if (@{$filter->args} >= 2) {
1727 my $entry = int(shift @{$filter->args});
1728 my $fields = join(",", map(int, @{$filter->args}));
1729 $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);
1731 } elsif ($filter->name eq 'edit_date' or $filter->name eq 'create_date') {
1732 # bre.create_date and bre.edit_date filtering
1733 my $datefilter = $filter->name;
1737 if ($filter && $filter->args && scalar(@{$filter->args}) > 0 && scalar(@{$filter->args}) < 3) {
1738 my ($cstart, $cend) = @{$filter->args};
1740 if (!$cstart and !$cend) {
1741 # useless use of filter
1742 } elsif (!$cstart or $cstart eq '-infinity') { # no start supplied
1743 if ($cend eq 'infinity') {
1744 # useless use of filter
1747 $cend = clean_ISO8601($cend);
1748 $where .= $joiner if $where ne '';
1749 $where .= "bre.$datefilter <= \$_$$\$$cend\$_$$\$";
1752 } elsif (!$cend or $cend eq 'infinity') { # no end supplied
1753 if ($cstart eq '-infinity') {
1754 # useless use of filter
1755 } else { # "after $cstart"
1756 $cstart = clean_ISO8601($cstart);
1757 $where .= $joiner if $where ne '';
1758 $where .= "bre.$datefilter >= \$_$$\$$cstart\$_$$\$";
1760 } else { # both supplied
1761 # "between $cstart and $cend"
1762 $cstart = clean_ISO8601($cstart);
1763 $cend = clean_ISO8601($cend);
1764 $where .= $joiner if $where ne '';
1765 $where .= "bre.$datefilter BETWEEN \$_$$\$$cstart\$_$$\$ AND \$_$$\$$cend\$_$$\$";
1768 } elsif ($filter->name eq 'bib_source') {
1769 if (@{$filter->args} > 0) {
1771 my $negate = $filter->negate ? 'TRUE' : 'FALSE';
1772 push @{$vis_filter{'b_attr'}},
1773 "search.calculate_visibility_attribute_test('source','{".join(',', @{$filter->args})."}',$negate)";
1775 } elsif ($filter->name eq 'from_metarecord') {
1776 if (@{$filter->args} > 0) {
1777 my $key = 'm.metarecord';
1778 $where .= $joiner if $where ne '';
1779 $where .= "$key ${NOT}IN (" . join(',', map { $self->QueryParser->quote_value($_) } @{$filter->args}) . ')';
1787 $where .= $joiner if $where ne '';
1788 if ($common) { # Use a function wrapper to inform PG of the non-rareness of one or more filter elements
1790 'evergreen.query_int_wrapper(mrv.vlist, \'%s\')',
1795 'mrv.vlist @@ \'%s\'',
1801 warn "flatten(): full filter where => $where\n" if $self->QueryParser->debug;
1804 rank_list => \@rank_list,
1808 vis_filter => \%vis_filter,
1809 uses_bre => $uses_bre,
1810 uses_mrv => $uses_mrv,
1811 uses_mrd => $uses_mrd
1816 #-------------------------------
1817 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::filter;
1818 use base 'QueryParser::query_plan::filter';
1820 #-------------------------------
1821 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::facet;
1822 use base 'QueryParser::query_plan::facet';
1826 my ($classname) = split '\|', $self->name;
1832 my ($classname,@fields) = split '\|', $self->name;
1840 my $table_alias = "$self";
1841 $table_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1842 $table_alias .= '_' . $self->name;
1843 $table_alias =~ s/\|/_/go;
1844 $table_alias .= "_$suffix" if ($suffix);
1846 return $table_alias;
1850 #-------------------------------
1851 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::modifier;
1852 use base 'QueryParser::query_plan::modifier';
1854 #-------------------------------
1855 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::node::atom;
1856 use base 'QueryParser::query_plan::node::atom';
1862 $self->{sql} = $sql if ($sql);
1864 return $self->{sql} if ($self->{sql});
1865 return $self->buildSQL;
1871 my $classname = $self->node->classname;
1873 return $self->sql("''::tsquery") if $self->{dummy};
1875 my $normalizers = $self->node->plan->QueryParser->query_normalizers( $classname );
1877 my $fields = $self->node->fields;
1878 $fields = $self->node->plan->QueryParser->search_fields->{$classname} if (!@$fields);
1882 for my $field (@$fields) {
1883 for my $nfield (keys %$normalizers) {
1884 for my $nizer ( @{$$normalizers{$nfield}} ) {
1885 if ($field eq $nfield) {
1886 my $param_string = OpenSRF::Utils::JSON->perl2JSON($nizer->{params});
1887 if (!exists($norms{$nizer->{function}.$param_string})) {
1888 $norms{$nizer->{function}.$param_string} = {p=>$pos++,n=>$nizer};
1895 my $sql = $self->node->plan->QueryParser->quote_value($self->content);
1897 for my $n ( map { $$_{n} } sort { $$a{p} <=> $$b{p} } values %norms ) {
1898 $sql = join(', ', $sql, map { $self->node->plan->QueryParser->quote_value($_) } @{ $n->{params} });
1899 $sql = $n->{function}."($sql)";
1902 my $prefix = $self->prefix || '';
1903 my $suffix = $self->suffix || '';
1904 my $joiner = ' || ';
1905 $joiner = ' && ' if $self->prefix eq '!'; # Negative atoms should be "none of the variants" instead of "any of the variants"
1907 $prefix = "'$prefix' ||" if $prefix;
1909 my $suffix_after = '';
1911 $suffix_op = ":$suffix" if $suffix;
1912 $suffix_after = "|| '$suffix_op'" if $suffix;
1914 my $ts_configs = $self->node->ts_configs;
1917 for my $ts_config (@$ts_configs) {
1918 push @sql_set, "to_tsquery('$ts_config', COALESCE(NULLIF($prefix '(' || btrim(regexp_replace($sql,E'(?:\\\\s+|:)','$suffix_op&','g'),'&|') $suffix_after || ')', $prefix '()'), ''))";
1921 $sql = join($joiner, @sql_set);
1922 $sql = '(' . $sql . ')' if (scalar(@$ts_configs) > 1);
1924 return $self->sql($sql);
1927 #-------------------------------
1928 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::node;
1929 use base 'QueryParser::query_plan::node';
1930 use List::MoreUtils qw/uniq/;
1935 my $ts_configs = $self->{ts_configs} || [];
1937 if (!@$ts_configs) {
1938 my $classname = $self->classname;
1940 my $filter = $self->plan->find_filter('preferred_language');
1941 $lang ||= $filter->args->[0] if ($filter && $filter->args);
1942 $lang ||= $self->plan->QueryParser->default_preferred_language;
1944 my $fields = $self->fields;
1946 $ts_configs = $self->plan->QueryParser->class_ts_config($classname, $lang);
1948 for my $field (@$fields) {
1949 push @$ts_configs, @{$self->plan->QueryParser->field_ts_config($classname, $field, $lang)};
1952 $ts_configs = [keys %{{map { $_ => 1 } @$ts_configs}}];
1954 # Assume we want exact if none otherwise provided.
1955 # Because we can reasonably expect this to exist
1956 $ts_configs = ['simple'] unless (scalar @$ts_configs);
1957 $self->{ts_configs} = $ts_configs;
1963 sub abstract_node_additions {
1967 my $hm = $self->plan
1970 ->get_abstract_data('highlight_map') // {};
1972 return unless ref($hm);
1974 my $field_set = $self->fields;
1975 $field_set = $self->plan->QueryParser->search_fields->{$self->classname}
1978 my @field_ids = grep defined, (
1980 $self->plan->QueryParser->search_field_ids_by_class(
1981 $self->classname, $_
1986 push @field_ids, @{$self->{vfields}} if $self->{vfields};
1988 my $ts_query = $self->tsquery_rank;
1990 # We need to rework the hash so fields are only ever pointed at once.
1991 # That means if a field is already being looked at elsewhere then we'll
1992 # need to separate it out and combine its preexisting tsqueries. This
1993 # will be fairly brute-force, and could be improved later, likely, with
1994 # a clever algorithm.
1997 for my $t (keys %$hm) {
1998 for my $f (@{$$hm{$t}}) {
1999 $inverted_hm{$f} = $t;
2003 # Then, loop over new fields and put them in the inverted hash.
2004 my @existing_fields = keys %inverted_hm;
2006 for my $f (@field_ids) {
2007 if (grep { $f == $_ } @existing_fields) { # We've seen the field, should we combine?
2008 my $t = $inverted_hm{$f};
2009 if ($t ne $ts_query) { # Different tsquery, do it!
2010 $t .= ' || '. $ts_query;
2011 $inverted_hm{$f} = $t;
2013 } else { # New field
2014 $inverted_hm{$f} = $ts_query;
2018 # Now, flip it back over.
2020 for my $f (keys %inverted_hm) {
2021 my $t = $inverted_hm{$f};
2023 push @{$$hm{$t}}, $f;
2029 # finally, ask the database to give us an hstore literal
2030 my $hl_map_string = "";
2031 for my $tsq (keys %$hm) {
2032 my $field_list = join(',', @{$$hm{$tsq}});
2033 $hl_map_string .= ' || ' if $hl_map_string;
2034 $hl_map_string .= "hstore(($tsq)\:\:TEXT,'$field_list')";
2037 my $calculated_hm = '';
2038 $calculated_hm = $self->plan->QueryParser->dbh->selectcol_arrayref(
2039 "SELECT $hl_map_string AS hm"
2040 )->[0] if ($hl_map_string);
2045 ->set_abstract_data('highlight_map', $calculated_hm);
2052 $self->{vfields} ||= [];
2053 push @{$self->{vfields}}, $vfield;
2059 $self->{dummy_count} = 0;
2061 my $atoms = $self->query_atoms;
2063 for my $a (@$atoms) {
2064 push(@only_atoms, $a) if (ref($a) && $a->isa('QueryParser::query_plan::node::atom'));
2065 $self->{dummy_count}++ if (ref($a) && $a->{dummy});
2068 return \@only_atoms;
2071 sub only_real_atoms {
2074 my $atoms = $self->query_atoms;
2075 my @only_real_atoms;
2076 for my $a (@$atoms) {
2077 push(@only_real_atoms, $a) if (ref($a) && $a->isa('QueryParser::query_plan::node::atom') && !($a->{dummy}));
2080 return \@only_real_atoms;
2083 sub only_positive_atoms {
2086 my $atoms = $self->query_atoms;
2087 my @only_positive_atoms;
2088 for my $a (@$atoms) {
2089 push(@only_positive_atoms, $a) if (ref($a) && $a->isa('QueryParser::query_plan::node::atom') && !($a->{dummy}) && ($a->{prefix} ne '!'));
2092 return \@only_positive_atoms;
2097 return $self->{dummy_count};
2102 my $classname = shift || $self->classname;
2103 return 'metabib.' . $classname . '_field_entry';
2106 sub combined_table {
2108 my $classname = shift || $self->classname;
2109 return 'metabib.combined_' . $classname . '_field_entry';
2112 sub combined_search {
2114 return $self->plan->QueryParser->search_class_combined($self->classname);
2121 my $table_alias = "$self";
2122 $table_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
2123 $table_alias .= '_' . $self->requested_class;
2124 $table_alias =~ s/\|/_/go;
2125 $table_alias .= "_$suffix" if ($suffix);
2127 return $table_alias;
2132 return $self->{tsquery} if ($self->{tsquery});
2134 for my $atom (@{$self->query_atoms}) {
2136 $self->{tsquery} .= "\n" . ${spc} x 3;
2137 $self->{tsquery} .= '(' x $atom->explicit_start if $atom->explicit_start;
2138 $self->{tsquery} .= $atom->sql;
2139 $self->{tsquery} .= ')' x $atom->explicit_end if $atom->explicit_end;
2141 $self->{tsquery} .= $atom x 2;
2145 # any phrases that are more than empty or all-whitespace
2146 if (my @phrases = grep { /\S+/ } @{$self->phrases}) {
2147 my $neg = $self->negate ? '!!' : '';
2148 $self->{tsquery} ||= "''::tsquery";
2149 $self->{tsquery} .= ' && ' . join(
2151 map { "${neg}phraseto_tsquery('simple', \$_$$\$$_\$_$$\$)" } @phrases
2155 return $self->{tsquery};
2160 return $self->{tsquery_rank} if ($self->{tsquery_rank});
2163 for my $atom (@{$self->only_positive_atoms}) {
2164 push @atomlines, "\n" . ${spc} x 3 . $atom->sql;
2166 $self->{tsquery_rank} = join(' ||', @atomlines);
2167 $self->{tsquery_rank} = "''::tsquery" unless $self->{tsquery_rank};
2169 # any non-negated phrases that are more than empty or all-whitespace
2170 if (!$self->negate) {
2171 if (my @phrases = grep { /\S+/ } @{$self->phrases}) {
2172 for my $tsc (@{$self->ts_configs}) {
2173 $self->{tsquery_rank} .= ' || ' . join(
2175 map { "phraseto_tsquery('$tsc', \$_$$\$$_\$_$$\$)" } @phrases
2181 return $self->{tsquery_rank};
2186 return $self->{rank} if ($self->{rank});
2188 my $rank_norm_map = $self->plan->QueryParser->custom_data->{rank_cd_weight_map};
2190 my $cover_density = 0;
2191 for my $norm ( keys %$rank_norm_map) {
2192 $cover_density += $$rank_norm_map{$norm} if ($self->plan->QueryParser->parse_tree->find_modifier($norm));
2195 my $weights = join(', ', @{$self->plan->QueryParser->search_class_weights($self->classname)});
2197 return $self->{rank} = "ts_rank_cd('{" . $weights . "}', " . $self->table_alias . '.index_vector, ' . $self->table_alias . ".tsq_rank, $cover_density)";