4 package OpenILS::Application::Storage::Driver::Pg::QueryParser;
5 use OpenILS::Application::Storage::QueryParser;
6 use base 'QueryParser';
7 use OpenSRF::Utils qw/:datetime/;
8 use OpenSRF::Utils::JSON;
9 use OpenILS::Application::AppUtils;
10 use OpenILS::Utils::CStoreEditor;
11 my $U = 'OpenILS::Application::AppUtils';
14 sub subquery_callback {
15 my ($invocant, $self, $struct, $filter, $params, $negate) = @_;
17 return sprintf(' ((%s)) ',
23 OpenILS::Utils::CStoreEditor
25 ->search_actor_search_query({ id => $params })
31 sub filter_group_entry_callback {
32 my ($invocant, $self, $struct, $filter, $params, $negate) = @_;
34 return sprintf(' saved_query(%s)',
40 OpenILS::Utils::CStoreEditor
42 ->search_actor_search_filter_group_entry({ id => $params })
49 my ($invocant, $self, $struct, $filter, $params, $negate) = @_;
52 my $negate_flag = ($negate ? '-' : '');
54 for my $param (@$params) {
55 my ($t,$f) = split('-', $param);
57 $treturn .= 'item_type(' . join(',',split('', $t)) . ')' if ($t);
58 $treturn .= ' ' if ($t and $f);
59 $treturn .= 'item_form(' . join(',',split('', $f)) . ')' if ($f);
60 $treturn = '(' . $treturn . ')' if ($t and $f);
61 push(@returns, $treturn) if $treturn;
63 $return = join(' || ', @returns);
64 $return = '(' . $return . ')' if(@returns > 1);
65 $return = $negate_flag.$return if($return);
73 if ($value =~ /^\d/) { # may have to use non-$ quoting
75 $value =~ s/\\/\\\\/g;
78 return "\$_$$\$$value\$_$$\$";
81 sub quote_phrase_value {
86 my $left_anchored = '';
87 my $right_anchored = '';
91 $left_anchored = $1 if $value =~ m/^([*\^])/;
92 $right_anchored = $1 if $value =~ m/([*\$])$/;
94 # We can't use word-boundary bracket expressions if the relevant char
95 # is not actually a "word" characters.
96 $left_wb = $wb if $value =~ m/^\w+/;
97 $right_wb = $wb if $value =~ m/\w+$/;
99 $value =~ s/^[*\^]// if $left_anchored;
100 $value =~ s/[*\$]$// if $right_anchored;
101 $value = quotemeta($value);
102 $value = '^' . $value if $left_anchored eq '^';
103 $value = "$value\$" if $right_anchored eq '$';
104 $value = '[[:<:]]' . $value if $left_wb && !$left_anchored;
105 $value .= '[[:>:]]' if $right_wb && !$right_anchored;
106 return $self->quote_value($value);
113 sub default_preferred_language {
117 $self->custom_data->{default_preferred_language} = $lang if ($lang);
118 return $self->custom_data->{default_preferred_language};
121 sub default_preferred_language_multiplier {
125 $self->custom_data->{default_preferred_language_multiplier} = $lang if ($lang);
126 return $self->custom_data->{default_preferred_language_multiplier};
129 sub max_popularity_importance_multiplier {
133 $self->custom_data->{max_popularity_importance_multiplier} = $max if defined($max);
134 return $self->custom_data->{max_popularity_importance_multiplier};
140 return 0 unless $self->parse_tree;
141 return 0 if @{$self->parse_tree->filters};
142 return 0 if @{$self->parse_tree->modifiers};
143 for my $node ( @{ $self->parse_tree->query_nodes } ) {
144 return 0 if (!ref($node) && $node eq '|');
145 next unless (ref($node));
146 return 0 if ($node->isa('QueryParser::query_plan'));
154 return $self->parse_tree->toSQL;
157 sub dynamic_filters {
161 $self->custom_data->{dynamic_filters} ||= [];
162 push(@{$self->custom_data->{dynamic_filters}}, $new) if ($new);
163 return $self->custom_data->{dynamic_filters};
166 sub dynamic_sorters {
170 $self->custom_data->{dynamic_sorters} ||= [];
171 push(@{$self->custom_data->{dynamic_sorters}}, $new) if ($new);
172 return $self->custom_data->{dynamic_sorters};
175 sub facet_field_id_map {
179 $self->custom_data->{facet_field_id_map} ||= {};
180 $self->custom_data->{facet_field_id_map} = $map if ($map);
181 return $self->custom_data->{facet_field_id_map};
184 sub add_facet_field_id_map {
191 $self->add_facet_field( $class => $field );
192 $self->facet_field_id_map->{by_id}{$id} = { classname => $class, field => $field, weight => $weight };
193 $self->facet_field_id_map->{by_class}{$class}{$field} = $id;
196 by_id => { $id => { classname => $class, field => $field, weight => $weight } },
197 by_class => { $class => { $field => $id } }
201 sub facet_field_class_by_id {
205 return $self->facet_field_id_map->{by_id}{$id};
208 sub facet_field_ids_by_class {
213 return undef unless ($class);
216 return [$self->facet_field_id_map->{by_class}{$class}{$field}];
219 return [values( %{ $self->facet_field_id_map->{by_class}{$class} } )];
222 sub search_field_id_map {
226 $self->custom_data->{search_field_id_map} ||= {};
227 $self->custom_data->{search_field_id_map} = $map if ($map);
228 return $self->custom_data->{search_field_id_map};
231 sub add_search_field_id_map {
237 my $combined = shift;
239 $self->add_search_field( $class => $field );
240 $self->search_field_id_map->{by_id}{$id} = { classname => $class, field => $field, weight => $weight };
241 $self->search_field_id_map->{by_class}{$class}{$field} = $id;
244 by_id => { $id => { classname => $class, field => $field, weight => $weight } },
245 by_class => { $class => { $field => $id } }
249 sub search_field_class_by_id {
253 return $self->search_field_id_map->{by_id}{$id};
256 sub search_field_ids_by_class {
261 return undef unless ($class);
264 return [$self->search_field_id_map->{by_class}{$class}{$field}];
267 return [values( %{ $self->search_field_id_map->{by_class}{$class} } )];
270 sub relevance_bumps {
274 $self->custom_data->{rel_bumps} ||= {};
275 $self->custom_data->{rel_bumps} = $bumps if ($bumps);
276 return $self->custom_data->{rel_bumps};
279 sub find_relevance_bumps {
284 return $self->relevance_bumps->{$class}{$field};
287 sub add_relevance_bump {
292 my $multiplier = shift;
295 if (defined($active) and $active eq 'f') {
301 $self->relevance_bumps->{$class}{$field}{$type} = { multiplier => $multiplier, active => $active };
303 return { $class => { $field => { $type => { multiplier => $multiplier, active => $active } } } };
306 sub search_class_weights {
309 my $a_weight = shift;
310 my $b_weight = shift;
311 my $c_weight = shift;
312 my $d_weight = shift;
314 $self->custom_data->{class_weights} ||= {};
315 # Note: This reverses the A-D order, putting D first, because that is how the call actually works in PG
316 $self->custom_data->{class_weights}->{$class} ||= [0.1, 0.2, 0.4, 1.0];
317 $self->custom_data->{class_weights}->{$class} = [$d_weight, $c_weight, $b_weight, $a_weight] if $a_weight;
318 return $self->custom_data->{class_weights}->{$class};
321 sub search_class_combined {
326 $self->custom_data->{class_combined} ||= {};
327 # Note: This reverses the A-D order, putting D first, because that is how the call actually works in PG
328 $self->custom_data->{class_combined}->{$class} ||= 0;
329 $self->custom_data->{class_combined}->{$class} = 1 if $c && $c =~ /^(?:t|y|1)/i;
330 return $self->custom_data->{class_combined}->{$class};
333 sub class_ts_config {
336 my $lang = shift || 'DEFAULT';
338 my $ts_config = shift;
340 $self->custom_data->{class_ts_config} ||= {};
341 $self->custom_data->{class_ts_config}->{$class} ||= {};
342 $self->custom_data->{class_ts_config}->{$class}->{$lang} ||= {};
343 $self->custom_data->{class_ts_config}->{$class}->{$lang}->{normal} ||= [];
344 $self->custom_data->{class_ts_config}->{$class}->{$lang}->{always} ||= [];
345 $self->custom_data->{class_ts_config}->{$class}->{'DEFAULT'} ||= {};
346 $self->custom_data->{class_ts_config}->{$class}->{'DEFAULT'}->{normal} ||= [];
347 $self->custom_data->{class_ts_config}->{$class}->{'DEFAULT'}->{always} ||= [];
350 push @{$self->custom_data->{class_ts_config}->{$class}->{$lang}->{normal}}, $ts_config unless $always;
351 push @{$self->custom_data->{class_ts_config}->{$class}->{$lang}->{always}}, $ts_config if $always;
355 push @$return, @{$self->custom_data->{class_ts_config}->{$class}->{$lang}->{always}};
356 push @$return, @{$self->custom_data->{class_ts_config}->{$class}->{$lang}->{normal}} unless $always;
357 if($lang ne 'DEFAULT') {
358 push @$return, @{$self->custom_data->{class_ts_config}->{$class}->{'DEFAULT'}->{always}};
359 push @$return, @{$self->custom_data->{class_ts_config}->{$class}->{'DEFAULT'}->{normal}} unless $always;
364 sub field_ts_config {
368 my $lang = shift || 'DEFAULT';
369 my $ts_config = shift;
371 $self->custom_data->{field_ts_config} ||= {};
372 $self->custom_data->{field_ts_config}->{$class} ||= {};
373 $self->custom_data->{field_ts_config}->{$class}->{$field} ||= {};
374 $self->custom_data->{field_ts_config}->{$class}->{$field}->{$lang} ||= [];
375 $self->custom_data->{field_ts_config}->{$class}->{$field}->{'DEFAULT'} ||= [];
378 push @{$self->custom_data->{field_ts_config}->{$class}->{$field}->{$lang}}, $ts_config;
382 push @$return, @{$self->custom_data->{field_ts_config}->{$class}->{$field}->{$lang}};
383 if($lang ne 'DEFAULT') {
384 push @$return, @{$self->custom_data->{field_ts_config}->{$class}->{$field}->{'DEFAULT'}};
386 # Make it easy on us: Grab any "always" for the class here. If we have none we grab them all.
387 push @$return, @{$self->class_ts_config($class, $lang, scalar(@$return))};
391 sub initialize_search_field_id_map {
393 my $cmf_list = shift;
395 for my $cmf (@$cmf_list) {
396 __PACKAGE__->add_search_field_id_map( $cmf->field_class, $cmf->name, $cmf->id, $cmf->weight ) if ($U->is_true($cmf->search_field));
397 __PACKAGE__->add_facet_field_id_map( $cmf->field_class, $cmf->name, $cmf->id, $cmf->weight ) if ($U->is_true($cmf->facet_field));
400 return $self->search_field_id_map;
403 sub initialize_aliases {
405 my $cmsa_list = shift;
407 for my $cmsa (@$cmsa_list) {
409 __PACKAGE__->add_search_class_alias( $cmsa->field_class, $cmsa->alias );
411 my $c = $self->search_field_class_by_id( $cmsa->field );
412 __PACKAGE__->add_search_field_alias( $cmsa->field_class, $c->{field}, $cmsa->alias );
417 sub initialize_relevance_bumps {
419 my $sra_list = shift;
421 for my $sra (@$sra_list) {
422 my $c = $self->search_field_class_by_id( $sra->field );
423 __PACKAGE__->add_relevance_bump( $c->{classname}, $c->{field}, $sra->bump_type, $sra->multiplier, $sra->active );
426 return $self->relevance_bumps;
429 sub initialize_query_normalizers {
431 my $tree = shift; # open-ils.cstore.direct.config.metabib_field_index_norm_map.search.atomic { "id" : { "!=" : null } }, { "flesh" : 1, "flesh_fields" : { "cmfinm" : ["norm"] }, "order_by" : [{ "class" : "cmfinm", "field" : "pos" }] }
433 for my $cmfinm ( @$tree ) {
434 my $field_info = $self->search_field_class_by_id( $cmfinm->field );
435 next unless $field_info;
436 __PACKAGE__->add_query_normalizer( $field_info->{classname}, $field_info->{field}, $cmfinm->norm->func, OpenSRF::Utils::JSON->JSON2perl($cmfinm->params) );
440 sub initialize_dynamic_filters {
442 my $list = shift; # open-ils.cstore.direct.config.record_attr_definition.search.atomic { "id" : { "!=" : null } }
444 for my $crad ( @$list ) {
445 __PACKAGE__->dynamic_filters( __PACKAGE__->add_search_filter( $crad->name ) ) if ($U->is_true($crad->filter));
446 __PACKAGE__->dynamic_sorters( $crad->name ) if ($U->is_true($crad->sorter));
450 sub initialize_filter_normalizers {
452 my $tree = shift; # open-ils.cstore.direct.config.record_attr_index_norm_map.search.atomic { "id" : { "!=" : null } }, { "flesh" : 1, "flesh_fields" : { "crainm" : ["norm"] }, "order_by" : [{ "class" : "crainm", "field" : "pos" }] }
454 for my $crainm ( @$tree ) {
455 __PACKAGE__->add_filter_normalizer( $crainm->attr, $crainm->norm->func, OpenSRF::Utils::JSON->JSON2perl($crainm->params) );
459 sub initialize_search_class_weights {
463 for my $search_class (@$classes) {
464 __PACKAGE__->search_class_weights( $search_class->name, $search_class->a_weight, $search_class->b_weight, $search_class->c_weight, $search_class->d_weight );
465 __PACKAGE__->search_class_combined( $search_class->name, $search_class->combined );
469 sub initialize_class_ts_config {
471 my $class_entries = shift;
473 for my $search_class_entry (@$class_entries) {
474 __PACKAGE__->class_ts_config($search_class_entry->field_class,$search_class_entry->search_lang,$U->is_true($search_class_entry->always),$search_class_entry->ts_config);
478 sub initialize_field_ts_config {
480 my $field_entries = shift;
481 my $field_objects = shift;
482 my %field_hash = map { $_->id => $_ } @$field_objects;
484 for my $search_field_entry (@$field_entries) {
485 my $field_object = $field_hash{$search_field_entry->metabib_field};
486 __PACKAGE__->field_ts_config($field_object->field_class,$field_object->name,$search_field_entry->search_lang,$search_field_entry->ts_config);
491 sub initialization_complete {
499 return $_complete if ($_complete);
501 # tsearch rank normalization adjustments. see http://www.postgresql.org/docs/9.0/interactive/textsearch-controls.html#TEXTSEARCH-RANKING for details
502 $self->custom_data->{rank_cd_weight_map} = {
503 CD_logDocumentLength => 1,
504 CD_documentLength => 2,
505 CD_meanHarmonic => 4,
507 CD_logUniqueWords => 16,
511 $self->add_search_modifier( $_ ) for (keys %{ $self->custom_data->{rank_cd_weight_map} });
513 $self->initialize_search_field_id_map( $args{config_metabib_field} )
514 if ($args{config_metabib_field});
516 $self->initialize_aliases( $args{config_metabib_search_alias} )
517 if ($args{config_metabib_search_alias});
519 $self->initialize_relevance_bumps( $args{search_relevance_adjustment} )
520 if ($args{search_relevance_adjustment});
522 $self->initialize_query_normalizers( $args{config_metabib_field_index_norm_map} )
523 if ($args{config_metabib_field_index_norm_map});
525 $self->initialize_dynamic_filters( $args{config_record_attr_definition} )
526 if ($args{config_record_attr_definition});
528 $self->initialize_filter_normalizers( $args{config_record_attr_index_norm_map} )
529 if ($args{config_record_attr_index_norm_map});
531 $self->initialize_search_class_weights( $args{config_metabib_class} )
532 if ($args{config_metabib_class});
534 $self->initialize_class_ts_config( $args{config_metabib_class_ts_map} )
535 if ($args{config_metabib_class_ts_map});
537 $self->initialize_field_ts_config( $args{config_metabib_field_ts_map}, $args{config_metabib_field} )
538 if ($args{config_metabib_field_ts_map} && $args{config_metabib_field});
541 $args{config_metabib_field_index_norm_map} &&
542 $args{search_relevance_adjustment} &&
543 $args{config_metabib_search_alias} &&
544 $args{config_metabib_field} &&
545 $args{config_record_attr_definition}
553 __PACKAGE__->allow_nested_modifiers(1);
555 __PACKAGE__->add_search_field_id_map( series => seriestitle => 1 => 1 );
557 __PACKAGE__->add_search_field_id_map( series => seriestitle => 1 => 1 );
558 __PACKAGE__->add_relevance_bump( series => seriestitle => first_word => 1.5 );
559 __PACKAGE__->add_relevance_bump( series => seriestitle => full_match => 20 );
561 __PACKAGE__->add_search_field_id_map( title => abbreviated => 2 => 1 );
562 __PACKAGE__->add_relevance_bump( title => abbreviated => first_word => 1.5 );
563 __PACKAGE__->add_relevance_bump( title => abbreviated => full_match => 20 );
565 __PACKAGE__->add_search_field_id_map( title => translated => 3 => 1 );
566 __PACKAGE__->add_relevance_bump( title => translated => first_word => 1.5 );
567 __PACKAGE__->add_relevance_bump( title => translated => full_match => 20 );
569 __PACKAGE__->add_search_field_id_map( title => proper => 6 => 1 );
570 __PACKAGE__->add_query_normalizer( title => proper => 'search_normalize' );
571 __PACKAGE__->add_relevance_bump( title => proper => first_word => 1.5 );
572 __PACKAGE__->add_relevance_bump( title => proper => full_match => 20 );
573 __PACKAGE__->add_relevance_bump( title => proper => word_order => 10 );
575 __PACKAGE__->add_search_field_id_map( author => corporate => 7 => 1 );
576 __PACKAGE__->add_relevance_bump( author => corporate => first_word => 1.5 );
577 __PACKAGE__->add_relevance_bump( author => corporate => full_match => 20 );
579 __PACKAGE__->add_facet_field_id_map( author => personal => 8 => 1 );
581 __PACKAGE__->add_search_field_id_map( author => personal => 8 => 1 );
582 __PACKAGE__->add_relevance_bump( author => personal => first_word => 1.5 );
583 __PACKAGE__->add_relevance_bump( author => personal => full_match => 20 );
584 __PACKAGE__->add_query_normalizer( author => personal => 'search_normalize' );
585 __PACKAGE__->add_query_normalizer( author => personal => 'split_date_range' );
587 __PACKAGE__->add_facet_field_id_map( subject => topic => 14 => 1 );
589 __PACKAGE__->add_search_field_id_map( subject => topic => 14 => 1 );
590 __PACKAGE__->add_relevance_bump( subject => topic => first_word => 1 );
591 __PACKAGE__->add_relevance_bump( subject => topic => full_match => 1 );
593 __PACKAGE__->add_search_field_id_map( subject => complete => 16 => 1 );
594 __PACKAGE__->add_relevance_bump( subject => complete => first_word => 1 );
595 __PACKAGE__->add_relevance_bump( subject => complete => full_match => 1 );
597 __PACKAGE__->add_search_field_id_map( keyword => keyword => 15 => 1 );
598 __PACKAGE__->add_relevance_bump( keyword => keyword => first_word => 1 );
599 __PACKAGE__->add_relevance_bump( keyword => keyword => full_match => 1 );
601 __PACKAGE__->class_ts_config( 'series', undef, 1, 'english_nostop' );
602 __PACKAGE__->class_ts_config( 'title', undef, 1, 'english_nostop' );
603 __PACKAGE__->class_ts_config( 'author', undef, 1, 'english_nostop' );
604 __PACKAGE__->class_ts_config( 'subject', undef, 1, 'english_nostop' );
605 __PACKAGE__->class_ts_config( 'keyword', undef, 1, 'english_nostop' );
606 __PACKAGE__->class_ts_config( 'series', undef, 1, 'simple' );
607 __PACKAGE__->class_ts_config( 'title', undef, 1, 'simple' );
608 __PACKAGE__->class_ts_config( 'author', undef, 1, 'simple' );
609 __PACKAGE__->class_ts_config( 'subject', undef, 1, 'simple' );
610 __PACKAGE__->class_ts_config( 'keyword', undef, 1, 'simple' );
612 # French! To test language limiters
613 __PACKAGE__->class_ts_config( 'series', 'fre', 1, 'french_nostop' );
614 __PACKAGE__->class_ts_config( 'title', 'fre', 1, 'french_nostop' );
615 __PACKAGE__->class_ts_config( 'author', 'fre', 1, 'french_nostop' );
616 __PACKAGE__->class_ts_config( 'subject', 'fre', 1, 'french_nostop' );
617 __PACKAGE__->class_ts_config( 'keyword', 'fre', 1, 'french_nostop' );
619 # Not a default config by any means, but good for some testing
620 __PACKAGE__->field_ts_config( 'author', 'personal', 'eng', 'english' );
621 __PACKAGE__->field_ts_config( 'author', 'personal', 'fre', 'french' );
623 __PACKAGE__->add_search_class_alias( keyword => 'kw' );
624 __PACKAGE__->add_search_class_alias( title => 'ti' );
625 __PACKAGE__->add_search_class_alias( author => 'au' );
626 __PACKAGE__->add_search_class_alias( author => 'name' );
627 __PACKAGE__->add_search_class_alias( author => 'dc.contributor' );
628 __PACKAGE__->add_search_class_alias( subject => 'su' );
629 __PACKAGE__->add_search_class_alias( subject => 'bib.subject(?:Title|Place|Occupation)' );
630 __PACKAGE__->add_search_class_alias( series => 'se' );
631 __PACKAGE__->add_search_class_alias( keyword => 'dc.identifier' );
633 __PACKAGE__->add_query_normalizer( author => corporate => 'search_normalize' );
634 __PACKAGE__->add_query_normalizer( keyword => keyword => 'search_normalize' );
636 __PACKAGE__->add_search_field_alias( subject => name => 'bib.subjectName' );
640 __PACKAGE__->default_search_class( 'keyword' );
642 # implements EG-specific stored subqueries
643 __PACKAGE__->add_search_filter( 'saved_query', sub { return __PACKAGE__->subquery_callback(@_) } );
644 __PACKAGE__->add_search_filter( 'filter_group_entry', sub { return __PACKAGE__->filter_group_entry_callback(@_) } );
646 # will be retained simply for back-compat
647 __PACKAGE__->add_search_filter( 'format', sub { return __PACKAGE__->format_callback(@_) } );
649 # grumble grumble, special cases against date1 and date2
650 __PACKAGE__->add_search_filter( 'before' );
651 __PACKAGE__->add_search_filter( 'after' );
652 __PACKAGE__->add_search_filter( 'between' );
653 __PACKAGE__->add_search_filter( 'during' );
655 # various filters for limiting in various ways
656 __PACKAGE__->add_search_filter( 'edit_date' );
657 __PACKAGE__->add_search_filter( 'create_date' );
658 __PACKAGE__->add_search_filter( 'statuses' );
659 __PACKAGE__->add_search_filter( 'locations' );
660 __PACKAGE__->add_search_filter( 'location_groups' );
661 __PACKAGE__->add_search_filter( 'bib_source' );
662 __PACKAGE__->add_search_filter( 'badge_orgs' );
663 __PACKAGE__->add_search_filter( 'badges' );
664 __PACKAGE__->add_search_filter( 'site' );
665 __PACKAGE__->add_search_filter( 'pref_ou' );
666 __PACKAGE__->add_search_filter( 'lasso' );
667 __PACKAGE__->add_search_filter( 'my_lasso' );
668 __PACKAGE__->add_search_filter( 'depth' );
669 __PACKAGE__->add_search_filter( 'language' );
670 __PACKAGE__->add_search_filter( 'offset' );
671 __PACKAGE__->add_search_filter( 'limit' );
672 __PACKAGE__->add_search_filter( 'check_limit' );
673 __PACKAGE__->add_search_filter( 'skip_check' );
674 __PACKAGE__->add_search_filter( 'superpage' );
675 __PACKAGE__->add_search_filter( 'superpage_size' );
676 __PACKAGE__->add_search_filter( 'estimation_strategy' );
677 __PACKAGE__->add_search_filter( 'from_metarecord' );
678 __PACKAGE__->add_search_modifier( 'available' );
679 __PACKAGE__->add_search_modifier( 'staff' );
680 __PACKAGE__->add_search_modifier( 'deleted' );
681 __PACKAGE__->add_search_modifier( 'lucky' );
683 # Start from container data (bre, acn, acp): container(bre,bookbag,123,deadb33fdeadb33fdeadb33fdeadb33f)
684 __PACKAGE__->add_search_filter( 'container' );
686 # Start from a list of record ids, either bre or metarecords, depending on the #metabib modifier
687 __PACKAGE__->add_search_filter( 'record_list' );
689 __PACKAGE__->add_search_filter( 'has_browse_entry' );
691 # copy_tag(copy_tag_code,copy_tag_search)
692 __PACKAGE__->add_search_filter( 'copy_tag' );
694 # used internally, but generally not user-settable
695 __PACKAGE__->add_search_filter( 'preferred_language' );
696 __PACKAGE__->add_search_filter( 'preferred_language_weight' );
697 __PACKAGE__->add_search_filter( 'preferred_language_multiplier' );
698 __PACKAGE__->add_search_filter( 'core_limit' );
700 # XXX Valid values to be supplied by SVF
701 __PACKAGE__->add_search_filter( 'sort' );
703 # modifies core query, not configurable
704 __PACKAGE__->add_search_modifier( 'descending' );
705 __PACKAGE__->add_search_modifier( 'ascending' );
706 __PACKAGE__->add_search_modifier( 'nullsfirst' );
707 __PACKAGE__->add_search_modifier( 'nullslast' );
708 __PACKAGE__->add_search_modifier( 'metarecord' );
709 __PACKAGE__->add_search_modifier( 'metabib' );
712 #-------------------------------
713 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan;
714 use base 'QueryParser::query_plan';
715 use OpenSRF::Utils::Logger qw($logger);
716 use OpenSRF::Utils qw/:datetime/;
718 use OpenILS::Application::AppUtils;
719 use OpenILS::Utils::Normalize qw/search_normalize/;
720 my $apputils = "OpenILS::Application::AppUtils";
722 our %_dfilter_controlled_cache = ();
723 our %_dfilter_stats_cache = ();
724 our $_pg_version = 0;
726 sub dynamic_filter_compile {
727 my ($self, $filter, $params, $negate) = @_;
728 my $e = OpenILS::Utils::CStoreEditor->new;
730 $negate = $negate ? '!' : '';
733 ($_pg_version = $e->json_query({from => ['version']})->[0]->{version}) =~ s/^.+?(\d\.\d).+$/$1/;
737 if ($_pg_version >= 9.2) {
738 if (!scalar keys %_dfilter_stats_cache) {
739 my $data = $e->json_query({from => ['evergreen.pg_statistics', 'record_attr_vector_list', 'vlist']});
740 %_dfilter_stats_cache = map {
741 ( $_->{element}, $_->{frequency} )
742 } grep { $_->{frequency} > 5 } @$data; # Pin floor to 5% of the table
745 $common = 1; # Assume it's expensive
748 if (!exists($_dfilter_controlled_cache{$filter})) {
749 my $crad = $e->retrieve_config_record_attr_definition($filter);
750 my $ccvm_list = $e->search_config_coded_value_map({ctype =>$filter});
752 $_dfilter_controlled_cache{$filter} = $crad->to_bare_hash;
753 $_dfilter_controlled_cache{$filter}{controlled} = scalar @$ccvm_list;
756 my $method = $_dfilter_controlled_cache{$filter}{controlled} ?
757 'search_config_coded_value_map' : 'search_metabib_uncontrolled_record_attr_value';
758 my $attr_field = $_dfilter_controlled_cache{$filter}{controlled} ?
760 my $value_field = $_dfilter_controlled_cache{$filter}{controlled} ?
763 my $attr_objects = $e->$method({ $attr_field => $filter, $value_field => $params });
764 $common = scalar(grep { exists($_dfilter_stats_cache{$_->id}) } @$attr_objects) unless $common;
766 return (sprintf('%s(%s)', $negate,
769 map { $_->id } @$attr_objects
779 for my $f ( qw/preferred_language preferred_language_multiplier preferred_language_weight core_limit check_limit skip_check superpage superpage_size/ ) {
781 $col = 'preferred_language_multiplier' if ($f eq 'preferred_language_weight');
782 my ($filter) = $self->find_filter($f);
783 if ($filter and @{$filter->args}) {
784 $filters{$col} = $filter->args->[0];
788 $self->QueryParser->superpage($filters{superpage}) if ($filters{superpage});
789 $self->QueryParser->superpage_size($filters{superpage_size}) if ($filters{superpage_size});
790 $self->QueryParser->core_limit($filters{core_limit}) if ($filters{core_limit});
792 $logger->debug("Query plan:\n".Dumper($self));
794 my $flat_plan = $self->flatten;
796 # generate the relevance ranking
797 my $rel = '1'; # Default to something simple in case rank_list is empty.
798 if (@{$$flat_plan{rank_list}}) {
801 . join(")\n" . ${spc} x 5 . "+ (", @{$$flat_plan{rank_list}})
803 . ${spc} x 4 . ")+1";
806 # find any supplied sort option
807 my ($sort_filter) = $self->find_filter('sort');
809 $sort_filter = $sort_filter->args->[0];
811 $sort_filter = 'rel';
815 if (($filters{preferred_language} || $self->QueryParser->default_preferred_language) && ($filters{preferred_language_multiplier} || $self->QueryParser->default_preferred_language_multiplier)) {
817 my $pl = $self->QueryParser->quote_value( $filters{preferred_language} ? $filters{preferred_language} : $self->QueryParser->default_preferred_language );
818 $$flat_plan{with} .= ',' if $$flat_plan{with};
819 $$flat_plan{with} .= "lang_with AS (SELECT id FROM config.coded_value_map WHERE ctype = 'item_lang' AND code = $pl)";
820 $lang_join = ",lang_with";
822 my $plw = $filters{preferred_language_multiplier} ? $filters{preferred_language_multiplier} : $self->QueryParser->default_preferred_language_multiplier;
823 $rel = "($rel * COALESCE( NULLIF( FIRST(mrv.vlist \@> ARRAY[lang_with.id]), FALSE )::INT * $plw, 1))";
824 $$flat_plan{uses_mrv} = 1;
828 if ($$flat_plan{uses_mrv}) {
829 $mrv_join = 'INNER JOIN metabib.record_attr_vector_list mrv ON m.source = mrv.source';
833 if ($$flat_plan{uses_mrd}) {
834 $mra_join = 'INNER JOIN metabib.record_attr mrd ON m.source = mrd.id';
837 my $pubdate_join = "LEFT JOIN metabib.record_sorter pubdate_t ON m.source = pubdate_t.source AND attr = 'pubdate'";
840 if ($self->find_modifier('deleted')) {
841 $bre_join = 'INNER JOIN biblio.record_entry bre ON m.source = bre.id AND bre.deleted';
842 # The above suffices for filters too when the #deleted modifier
844 } elsif ($$flat_plan{uses_bre} or !$self->find_modifier('staff')) {
845 $bre_join = 'INNER JOIN biblio.record_entry bre ON m.source = bre.id';
849 $desc = 'DESC' if ($self->find_modifier('descending'));
851 my $nullpos = 'NULLS LAST';
852 $nullpos = 'NULLS FIRST' if ($self->find_modifier('nullsfirst'));
854 # Do we have a badges() filter?
856 my ($badge_filter) = $self->find_filter('badges');
857 if ($badge_filter && @{$badge_filter->args}) {
858 $badges = join (',', grep /^\d+$/, @{$badge_filter->args});
861 # Do we have a badge_orgs() filter? (used for calculating popularity)
863 my ($bo_filter) = $self->find_filter('badge_orgs');
864 if ($bo_filter && @{$bo_filter->args}) {
865 $borgs = join (',', grep /^\d+$/, @{$bo_filter->args});
868 # Build the badge-ish WITH query
869 my $pop_with = <<' WITH';
872 ARRAY_AGG(badge) AS badges,
873 SUM(s.score::NUMERIC*b.weight::NUMERIC)/SUM(b.weight::NUMERIC) AS total_score
874 FROM rating.record_badge_score s
875 JOIN rating.badge b ON (
879 $pop_with .= " AND b.id = ANY ('{$badges}')" if ($badges);
880 $pop_with .= " AND b.scope = ANY ('{$borgs}')" if ($borgs);
881 $pop_with .= ') GROUP BY 1)';
883 my $pop_join = $badges ? # inner join if we are restricting via badges()
884 'INNER JOIN pop_with ON ( m.source = pop_with.record )' :
885 'LEFT JOIN pop_with ON ( m.source = pop_with.record )';
887 $$flat_plan{with} .= ',' if $$flat_plan{with};
888 $$flat_plan{with} .= $pop_with;
892 my $pop_extra_sort = '';
893 if (grep {$_ eq $sort_filter} @{$self->QueryParser->dynamic_sorters}) {
894 $rank = "FIRST((SELECT value FROM metabib.record_sorter rbr WHERE rbr.source = m.source and attr = '$sort_filter'))"
895 } elsif ($sort_filter eq 'create_date') {
896 $rank = "FIRST((SELECT create_date FROM biblio.record_entry rbr WHERE rbr.id = m.source))";
897 } elsif ($sort_filter eq 'edit_date') {
898 $rank = "FIRST((SELECT edit_date FROM biblio.record_entry rbr WHERE rbr.id = m.source))";
899 } elsif ($sort_filter eq 'poprel') {
900 my $max_mult = $self->QueryParser->max_popularity_importance_multiplier() // 2.0;
901 $max_mult = 0.1 if $max_mult < 0.1; # keep it within reasonable bounds,
902 # and avoid the division-by-zero error
903 # you'd get if you allowed it to be
906 if ( $max_mult == 1.0 ) { # no adjustment requested by the configuration
907 $rank = "1.0/($rel)::NUMERIC";
908 } else { # calculate adjustment
910 # Scale the 0-5 effect of popularity badges by providing a multiplier
911 # for the badge average based on the overall maximum
912 # multiplier. Two examples, comparing the effect to the default
913 # $max_mult value of 2.0, which causes a $adjusted_scale value
916 # * Given the default $max_mult of 2.0, the value of
917 # $adjusted_scale will be 0.2 [($max_mult - 1.0) / 5.0].
918 # For a record whose average badge score is the maximum
919 # of 5.0, that would make the relevance multiplier be
921 # 1.0 + (5.0 [average score] * 0.2 [ $adjusted_scale ],
922 # This would have the effect of doubling the effective
923 # relevance of highly popular items.
925 # * Given a $max_mult of 1.1, the value of $adjusted_scale
926 # will be 0.02, meaning that the average badge value will be
927 # multiplied by 0.02 rather than 0.2, then added to 1.0 and
928 # used as a multiplier against the base relevance. Thus a
929 # change of at most 10% to the base relevance for a record
930 # with a 5.0 average badge score. This will allow records
931 # that are naturally very relevant to avoid being pushed
932 # below badge-heavy records.
934 # * Given a $max_mult of 3.0, the value of $adjusted_scale
935 # will be 0.4, meaning that the average badge value will be
936 # multiplied by 0.4 rather than 0.2, then added to 1.0 and
937 # used as a multiplier against the base relevance. Thus a
938 # change of as much as 200% to (or three times the size of)
939 # the base relevance for a record with a 5.0 average badge
940 # score. This in turn will cause badges to outweigh
941 # relevance to a very large degree.
943 # The maximum badge multiplier can be set to a value less than
944 # 1.0; this would have the effect of making less popular items
945 # show up higher in the results. While this is not a likely
946 # option for production use, it could be useful for identifying
947 # interesting long-tail hits, particularly in a database
948 # where enough badges are configured so that very few records
949 # have an overage badge score of zero.
951 my $adjusted_scale = ( $max_mult - 1.0 ) / 5.0;
952 $rank = "1.0/(( $rel ) * (1.0 + (AVG(COALESCE(pop_with.total_score::NUMERIC,0.0::NUMERIC)) * ${adjusted_scale}::NUMERIC)))::NUMERIC";
954 } elsif ($sort_filter =~ /^pop/) {
955 $rank = '1.0/(AVG(COALESCE(pop_with.total_score::NUMERIC,0.0::NUMERIC)) + 5.0::NUMERIC)::NUMERIC';
956 my $pop_desc = $desc eq 'ASC' ? 'DESC' : 'ASC';
957 $pop_extra_sort = "3 $pop_desc $nullpos,";
959 # default to rel ranking
960 $rank = "1.0/($rel)::NUMERIC";
963 my $key = 'm.source';
964 $key = 'm.metarecord' if (grep {$_->name eq 'metarecord' or $_->name eq 'metabib'} @{$self->modifiers});
966 my $core_limit = $self->QueryParser->core_limit || 'NULL';
967 if ($self->find_modifier('lucky')) {
968 $filters{check_limit} = 1;
969 $filters{skip_check} = 0;
974 my $flat_where = $$flat_plan{where};
975 if ($flat_where ne '') {
976 $flat_where = "AND (\n" . ${spc} x 5 . $flat_where . "\n" . ${spc} x 4 . ")";
979 my $final_c_attr_test;
980 my $c_attr_join = '';
982 my $pc_vis_test = '';
984 # copy visibility testing
985 if (!$self->find_modifier('staff')) {
986 $pc_vis_test = "c_attrs";
987 $c_attr_join = ",c_attr"
990 if ($self->find_modifier('available')) {
991 push @{$$flat_plan{vis_filter}{'c_attr'}},
992 "search.calculate_visibility_attribute_test('status','{0,7,12}')";
995 if (@{$$flat_plan{vis_filter}{c_attr}}) {
996 $c_vis_test = join(",",@{$$flat_plan{vis_filter}{c_attr}});
997 $c_attr_join = ',c_attr';
1000 if ($c_vis_test or $pc_vis_test) {
1003 if ($c_vis_test and $pc_vis_test) {
1004 $vis_test = $pc_vis_test . ",". $c_vis_test;
1005 } elsif ($pc_vis_test) {
1006 $vis_test = $pc_vis_test;
1008 $vis_test = $c_vis_test;
1011 # WITH-clause just generates vis test
1012 $$flat_plan{with} .= "\n," if $$flat_plan{with};
1013 $$flat_plan{with} .= "c_attr AS (SELECT (ARRAY_TO_STRING(ARRAY[$vis_test],'&'))::query_int AS vis_test FROM asset.patron_default_visibility_mask() x)";
1015 $final_c_attr_test = 'EXISTS (SELECT 1 FROM asset.copy_vis_attr_cache WHERE record = m.source AND vis_attr_vector @@ c_attr.vis_test)';
1016 if (!$pc_vis_test) { # staff search
1017 $final_c_attr_test = '(' . $final_c_attr_test . ' OR NOT EXISTS (SELECT 1 FROM asset.copy_vis_attr_cache WHERE record = m.source))';
1021 my $final_b_attr_test;
1022 my $b_attr_join = '';
1023 my $b_vis_test = '';
1024 my $pb_vis_test = '';
1026 # bib visibility testing
1027 if (!$self->find_modifier('staff')) {
1028 $pb_vis_test = "b_attrs";
1029 $b_attr_join = ",b_attr"
1032 if (@{$$flat_plan{vis_filter}{b_attr}}) {
1033 $b_attr_join = ',b_attr ';
1034 $b_vis_test = join("||'&'||",@{$$flat_plan{vis_filter}{b_attr}});
1037 if ($b_vis_test or $pb_vis_test) {
1040 if ($b_vis_test and $pb_vis_test) {
1041 $vis_test = $pb_vis_test . ",". $b_vis_test;
1042 } elsif ($pb_vis_test) {
1043 $vis_test = $pb_vis_test;
1045 $vis_test = $b_vis_test;
1048 # WITH-clause just generates vis test
1049 $$flat_plan{with} .= "\n," if $$flat_plan{with};
1050 $$flat_plan{with} .= "b_attr AS (SELECT (ARRAY_TO_STRING(ARRAY[$vis_test],'&'))::query_int AS vis_test FROM asset.patron_default_visibility_mask() x)";
1052 # These are magic numbers... see: search.calculate_visibility_attribute() UDF
1053 $final_b_attr_test = '(b_attr.vis_test IS NULL OR bre.vis_attr_vector @@ b_attr.vis_test)';
1054 if (!$pb_vis_test) { # staff search
1055 $final_b_attr_test .= " OR NOT ( int4range(0,268435455,'[]') @> ANY(bre.vis_attr_vector) )";
1059 if ($final_c_attr_test or $final_b_attr_test) { # something...
1060 if ($final_c_attr_test and $final_b_attr_test) { # both!
1061 my $plan = "($final_c_attr_test) OR ($final_b_attr_test)";
1062 $flat_where .= "\n" . ${spc} x 4 . "AND (\n" . ${spc} x 5 . $plan . "\n" . ${spc} x 4 . ")";
1063 } elsif ($final_c_attr_test) { # just copies...
1064 $flat_where .= "\n" . ${spc} x 4 . "AND (\n" . ${spc} x 5 . $final_c_attr_test . "\n" . ${spc} x 4 . ")";
1065 } else { # just bibs...
1066 $flat_where .= "\n" . ${spc} x 4 . "AND (\n" . ${spc} x 5 . $final_b_attr_test . "\n" . ${spc} x 4 . ")";
1070 my $with = $$flat_plan{with};
1071 $with= "\nWITH $with" if $with;
1073 # Need an array for query parser db function; this gives a better plan
1074 # than the ARRAY_AGG(DISTINCT m.source) option as of PostgreSQL 9.1
1075 my $agg_records = 'ARRAY[m.source] AS records';
1076 if ($key =~ /metarecord/) {
1077 # metarecord searches still require the ARRAY_AGG approach
1078 $agg_records = 'ARRAY_AGG(DISTINCT m.source) AS records';
1087 CASE WHEN cardinality(records) = 1 THEN records[1] ELSE NULL END AS record,
1089 NULL::INT AS checked,
1090 NULL::INT AS visible,
1091 NULL::INT AS deleted,
1092 NULL::INT AS excluded,
1095 FROM (SELECT $key AS id,
1097 ${rel}::NUMERIC AS rel,
1099 FIRST(pubdate_t.value) AS tie_break,
1100 STRING_AGG(ARRAY_TO_STRING(pop_with.badges,','),',') AS badges,
1101 AVG(COALESCE(pop_with.total_score::NUMERIC,0.0::NUMERIC))::NUMERIC(2,1) AS popularity
1102 FROM metabib.metarecord_source_map m
1115 ORDER BY 4 $desc $nullpos, $pop_extra_sort 5 DESC $nullpos, 3 DESC
1118 ) (SELECT * FROM w LIMIT $filters{check_limit} OFFSET $filters{skip_check})
1120 SELECT NULL,NULL,NULL,COUNT(*),COUNT(*),COUNT(*),0,0,NULL,NULL FROM w;
1123 warn $sql if $self->QueryParser->debug;
1131 die 'ERROR: nesting too deep or boolean list too long' if ($self->plan_level > 40);
1133 my $from = shift || '';
1134 my $where = shift || '';
1136 my %vis_filter = ( c_attr => [], b_attr => [] );
1142 for my $node ( @{$self->query_nodes} ) {
1145 if ($node->isa( 'QueryParser::query_plan::node' )) {
1147 unless (@{$node->only_atoms}) {
1148 push @rank_list, '1';
1153 my $table = $node->table;
1154 my $ctable = $node->combined_table;
1155 my $talias = $node->table_alias;
1157 my $node_rank = 'COALESCE(' . $node->rank . " * ${talias}.weight, 0.0)";
1159 $from .= "\n" . ${spc} x 4 ."LEFT JOIN (\n"
1160 . ${spc} x 5 . "SELECT fe.*, fe_weight.weight, ${talias}_xq.tsq, ${talias}_xq.tsq_rank /* search */\n"
1161 . ${spc} x 6 . "FROM $table AS fe";
1162 $from .= "\n" . ${spc} x 7 . "JOIN config.metabib_field AS fe_weight ON (fe_weight.id = fe.field)";
1166 if (@{$node->fields} > 0) {
1167 @bump_fields = @{$node->fields};
1169 @field_ids = grep defined, (
1171 $self->QueryParser->search_field_ids_by_class(
1172 $node->classname, $_
1177 @bump_fields = @{$self->QueryParser->search_fields->{$node->classname}};
1180 if ($node->dummy_count < @{$node->only_atoms} ) {
1181 $with .= ",\n " if $with;
1182 $with .= "${talias}_xq AS (SELECT ". $node->tsquery ." AS tsq,". $node->tsquery_rank ." AS tsq_rank )";
1183 if ($node->combined_search) {
1184 $from .= "\n" . ${spc} x 6 . "JOIN $ctable AS com ON (com.record = fe.source";
1186 $from .= " AND com.metabib_field IN (" . join(',',@field_ids) . "))";
1188 $from .= " AND com.metabib_field IS NULL)";
1190 $from .= "\n" . ${spc} x 6 . "JOIN ${talias}_xq ON (com.index_vector @@ ${talias}_xq.tsq)";
1192 $from .= "\n" . ${spc} x 6 . "JOIN ${talias}_xq ON (fe.index_vector @@ ${talias}_xq.tsq)";
1195 $from .= "\n" . ${spc} x 6 . ", (SELECT NULL::tsquery AS tsq, NULL:tsquery AS tsq_rank ) AS ${talias}_xq";
1199 $from .= "\n" . ${spc} x 6 . "WHERE fe_weight.id IN (" .
1200 join(',', @field_ids) . ")";
1203 $from .= "\n" . ${spc} x 4 . ") AS $talias ON (m.source = ${talias}.source)";
1208 for my $field ( @bump_fields ) {
1209 my $bumps = $self->QueryParser->find_relevance_bumps( $node->classname => $field );
1210 for my $b (keys %$bumps) {
1211 next if (!$$bumps{$b}{active});
1212 next if ($used_bumps{$b});
1213 $used_bumps{$b} = 1;
1215 next if ($$bumps{$b}{multiplier} == 1); # optimization to remove unneeded bumps
1217 push @bumpmults, $$bumps{$b}{multiplier};
1221 if(scalar @bumps > 0 && scalar @{$node->only_positive_atoms} > 0) {
1222 # Note: Previous rank function used search_normalize outright. Duplicating that here.
1223 $node_rank .= "\n" . ${spc} x 5 . "* evergreen.rel_bump(('{' || quote_literal(search_normalize(";
1224 $node_rank .= join(")) || ',' || quote_literal(search_normalize(",map { $self->QueryParser->quote_phrase_value($_->content) } @{$node->only_positive_atoms});
1225 $node_rank .= ")) || '}')::TEXT[], " . $node->table_alias . ".value, '{" . join(",",@bumps) . "}'::TEXT[], '{" . join(",",@bumpmults) . "}'::NUMERIC[])";
1229 $NOT = 'NOT ' if $node->negate;
1231 $where .= "$NOT(" . $talias . ".id IS NOT NULL";
1232 if (@{$node->phrases}) {
1233 $where .= ' AND ' . join(' AND ', map {
1234 "${talias}.value ~* ".$self->QueryParser->quote_phrase_value($_, 1)
1235 } @{$node->phrases});
1237 for my $atom (@{$node->only_real_atoms}) {
1238 next unless $atom->{content} && $atom->{content} =~ /(^\^|\$$)/;
1239 $where .= " AND ${talias}.value ~* ".$self->QueryParser->quote_phrase_value($atom->{content});
1244 push @rank_list, $node_rank;
1246 } elsif ($node->isa( 'QueryParser::query_plan::facet' )) {
1248 my $talias = $node->table_alias;
1251 if (@{$node->fields} > 0) {
1252 push(@field_ids, $self->QueryParser->facet_field_ids_by_class( $node->classname, $_ )->[0]) for (@{$node->fields});
1254 @field_ids = @{ $self->QueryParser->facet_field_ids_by_class( $node->classname ) };
1257 my $join_type = ($node->negate or !$self->top_plan) ? 'LEFT' : 'INNER';
1258 $from .= "\n${spc}$join_type JOIN /* facet */ metabib.facet_entry $talias ON (\n"
1259 . ${spc} x 2 . "m.source = ${talias}.source\n"
1260 . ${spc} x 2 . "AND SUBSTRING(${talias}.value,1,1024) IN ("
1261 . join(",", map { $self->QueryParser->quote_value($_) } @{$node->values}) . ")\n"
1262 . ${spc} x 2 ."AND ${talias}.field IN (". join(',', @field_ids) . ")\n"
1265 if ($join_type ne 'INNER') {
1266 my $NOT = $node->negate ? '' : ' NOT';
1267 $where .= "${talias}.id IS$NOT NULL";
1268 } elsif ($where ne '') {
1269 # Strip extra joiner
1270 $where =~ s/(\s|\n)+(AND|OR)\s$//;
1274 my $subnode = $node->flatten;
1276 # strip the trailing bool from the previous loop if there is
1277 # nothing to add to the where within this loop.
1278 if ($$subnode{where} eq '') {
1279 $where =~ s/(\s|\n)+(AND|OR)\s$//;
1282 push(@rank_list, @{$$subnode{rank_list}});
1283 $from .= $$subnode{from};
1286 $NOT = 'NOT ' if $node->negate;
1288 if ($$subnode{where} ne '') {
1290 . ${spc} x ($self->plan_level + 6) . $$subnode{where} . "\n"
1291 . ${spc} x ($self->plan_level + 5) . ')';
1294 if ($$subnode{with}) {
1295 $with .= ",\n " if $with;
1296 $with .= $$subnode{with};
1299 $uses_bre = $$subnode{uses_bre};
1300 $uses_mrd = $$subnode{uses_mrd};
1301 $uses_mrv = $$subnode{uses_mrv};
1305 warn "flatten(): appending WHERE bool to: $where\n" if $self->QueryParser->debug;
1308 $where .= "\n" . ${spc} x ( $self->plan_level + 5 ) . 'AND ' if ($node eq '&');
1309 $where .= "\n" . ${spc} x ( $self->plan_level + 5 ) . 'OR ' if ($node eq '|');
1314 my $joiner = "\n" . ${spc} x ( $self->plan_level + 5 ) . ($self->joiner eq '&' ? 'AND ' : 'OR ');
1316 my ($depth_filter) = grep { $_->name eq 'depth' } @{$self->filters};
1317 if ($depth_filter and @{$depth_filter->args} == 1) {
1318 $depth_filter = $depth_filter->args->[0];
1323 # for each dynamic filter, build more of the WHERE clause
1324 for my $filter (@{$self->filters}) {
1325 my $NOT = $filter->negate ? 'NOT ' : '';
1326 if (grep { $_ eq $filter->name } @{ $self->QueryParser->dynamic_filters }) {
1328 my $fname = $filter->name;
1329 $fname = 'item_lang' if $fname eq 'language'; #XXX filter aliases
1331 warn "flatten(): processing dynamic filter ". $filter->name ."\n"
1332 if $self->QueryParser->debug;
1335 ($vlist_query, $common) = $self->dynamic_filter_compile( $fname, $filter->args, $filter->negate );
1337 # bool joiner for intra-plan nodes/filters
1338 push(@dlist, $self->joiner) if @dlist;
1339 push(@dlist, $vlist_query);
1342 if ($filter->name eq 'before') {
1343 if (@{$filter->args} == 1) {
1344 $where .= $joiner if $where ne '';
1345 $where .= "${NOT}COALESCE(pubdate_t.value <= "
1346 . $self->QueryParser->quote_value($filter->args->[0])
1349 } elsif ($filter->name eq 'after') {
1350 if (@{$filter->args} == 1) {
1351 $where .= $joiner if $where ne '';
1352 $where .= "${NOT}COALESCE(pubdate_t.value >= "
1353 . $self->QueryParser->quote_value($filter->args->[0])
1356 } elsif ($filter->name eq 'during') {
1357 if (@{$filter->args} == 1) {
1358 $where .= $joiner if $where ne '';
1359 $where .= "${NOT}COALESCE("
1360 . $self->QueryParser->quote_value($filter->args->[0])
1361 . " BETWEEN pubdate_t.value AND (mrd.attrs->'date2'), false)";
1364 } elsif ($filter->name eq 'between') {
1365 if (@{$filter->args} == 2) {
1366 $where .= $joiner if $where ne '';
1367 $where .= "${NOT}COALESCE(pubdate_t.value BETWEEN "
1368 . $self->QueryParser->quote_value($filter->args->[0])
1370 . $self->QueryParser->quote_value($filter->args->[1])
1373 } elsif ($filter->name eq 'container') {
1374 if (@{$filter->args} >= 3) {
1375 my ($class, $ctype, $cid, $token) = @{$filter->args};
1378 my $rec_field = 'ci.target_biblio_record_entry';
1379 if ($class eq 'bre') {
1380 $class = 'biblio_record_entry';
1381 } elsif ($class eq 'acn') {
1382 $class = 'call_number';
1383 $rec_field = 'cn.record';
1384 $rec_join = 'JOIN asset.call_number cn ON (ci.target_call_number = cn.id)';
1385 } elsif ($class eq 'acp') {
1387 $rec_field = 'cn.record';
1388 $rec_join = 'JOIN asset.copy cp ON (ci.target_copy = cp.id) JOIN asset.call_number cn ON (cp.call_number = cn.id)';
1394 my ($u,$e) = $apputils->checksesperm($token) if ($token);
1395 $perm_join = ' OR c.owner = ' . $u->id if ($u && !$e);
1397 my $filter_alias = "$filter";
1398 $filter_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1399 $filter_alias =~ s/\|/_/go;
1401 $with .= ",\n " if $with;
1402 $with .= "container_${filter_alias} AS (\n";
1403 $with .= " SELECT $rec_field AS record FROM container.${class}_bucket_item ci\n"
1404 . " JOIN container.${class}_bucket c ON (c.id = ci.bucket) $rec_join\n"
1405 . " WHERE c.btype = " . $self->QueryParser->quote_value($ctype) . "\n"
1406 . " AND c.id = " . $self->QueryParser->quote_value($cid) . "\n"
1407 . " AND (c.pub IS TRUE$perm_join)\n";
1408 if ($class eq 'copy') {
1410 . " SELECT pr.peer_record AS record FROM container.copy_bucket_item ci\n"
1411 . " JOIN container.copy_bucket c ON (c.id = ci.bucket)\n"
1412 . " JOIN biblio.peer_bib_copy_map pr ON ci.target_copy = pr.target_copy\n"
1413 . " WHERE c.btype = " . $self->QueryParser->quote_value($ctype) . "\n"
1414 . " AND c.id = " . $self->QueryParser->quote_value($cid) . "\n"
1415 . " AND (c.pub IS TRUE$perm_join)\n";
1419 my $optimize_join = 1 if $self->top_plan and !$NOT;
1420 $from .= "\n" . ${spc} x 3 . ( $optimize_join ? 'INNER' : 'LEFT') . " JOIN container_${filter_alias} ON container_${filter_alias}.record = m.source";
1422 if (!$optimize_join) {
1423 $where .= $joiner if $where ne '';
1424 $where .= "(container_${filter_alias} IS " . ( $NOT ? 'NULL)' : 'NOT NULL)');
1428 } elsif ($filter->name eq 'copy_tag') {
1429 my $valid_copy_tag_search = 0;
1432 if (@{$filter->args} >= 2) { # must have at least two parts, tag (or *) and terms
1433 my @fargs = @{$filter->args};
1434 $copy_tag_type = shift(@fargs);
1435 $tag_value = join(' ', @fargs);
1436 $valid_copy_tag_search = 1;
1438 if ($valid_copy_tag_search) {
1439 my $norm_value = search_normalize($tag_value);
1440 my @tokens = split /\s+/, $norm_value;
1442 my $filter_alias = "$filter";
1443 $filter_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1444 $filter_alias =~ s/\|/_/go;
1446 $with .= ",\n " if $with;
1447 $with .= "copy_tag_${filter_alias} AS (\n";
1448 $with .= " SELECT cn.record AS record FROM config.copy_tag_type cctt\n";
1449 $with .= " JOIN asset.copy_tag acpt ON (cctt.code = acpt.tag_type)\n";
1450 $with .= " JOIN asset.copy_tag_copy_map acptcm ON (acpt.id = acptcm.tag)\n";
1451 $with .= " JOIN asset.copy cp ON (acptcm.copy = cp.id)\n";
1452 $with .= " JOIN asset.call_number cn ON (cp.call_number = cn.id)\n";
1453 $with .= " WHERE 1 = 1 \n";
1454 if ($copy_tag_type ne '*') {
1455 $with .= " AND cctt.code = " . $self->QueryParser->quote_value($copy_tag_type) . "\n";
1458 $with .= ' AND acpt.value @@ to_tsquery(' . $self->QueryParser->quote_value(join(' & ', @tokens)) . ")\n";
1460 if (!$self->find_modifier('staff')) {
1461 $with .= " AND acpt.pub IS TRUE\n";
1465 my $optimize_join = 1 if $self->top_plan and !$NOT;
1466 $from .= "\n" . ${spc} x 3 . ( $optimize_join ? 'INNER' : 'LEFT') . " JOIN copy_tag_${filter_alias} ON copy_tag_${filter_alias}.record = m.source";
1468 if (!$optimize_join) {
1469 $where .= $joiner if $where ne '';
1470 $where .= "(copy_tag_${filter_alias} IS " . ( $NOT ? 'NULL)' : 'NOT NULL)');
1473 } elsif ($filter->name eq 'record_list') {
1474 if (@{$filter->args} > 0) {
1475 my $key = 'm.source';
1476 $key = 'm.metarecord' if (grep {$_->name eq 'metarecord' or $_->name eq 'metabib'} @{$self->QueryParser->parse_tree->modifiers});
1477 $where .= $joiner if $where ne '';
1478 $where .= "$key ${NOT}IN (" . join(',', map { $self->QueryParser->quote_value($_) } @{$filter->args}) . ')';
1481 } elsif ($filter->name eq 'site') {
1482 if (@{$filter->args} == 1) {
1483 if (!defined($depth_filter) or $depth_filter > 0) { # no point in filtering by "all"
1484 my $sitename = $filter->args->[0];
1486 my $ot = $U->get_org_tree;
1487 my $site_org = $U->find_org_by_shortname($ot, $sitename);
1489 if ($site_org and $site_org->id != $ot->id) { # no point in filtering by "all"
1490 my $dorgs = $U->get_org_descendants($site_org->id, $depth_filter);
1491 my $aorgs = $U->get_org_ancestors($site_org->id);
1493 my $negate = $filter->negate ? 'TRUE' : 'FALSE';
1494 push @{$vis_filter{'c_attr'}},
1495 "search.calculate_visibility_attribute_test('circ_lib','{".join(',', @$dorgs)."}',$negate)";
1497 my $lorgs = [@$aorgs];
1498 my $luri_as_copy_gf = $U->get_global_flag('opac.located_uri.act_as_copy');
1499 push @$lorgs, @$dorgs if (
1501 and $U->is_true($luri_as_copy_gf->enabled)
1502 and $U->is_true($luri_as_copy_gf->value)
1506 push @{$vis_filter{'b_attr'}},
1507 "search.calculate_visibility_attribute_test('luri_org','{".join(',', @$lorgs)."}',$negate)";
1512 } elsif ($filter->name eq 'locations') {
1513 if (@{$filter->args} > 0) {
1514 my $negate = $filter->negate ? 'TRUE' : 'FALSE';
1515 push @{$vis_filter{'c_attr'}},
1516 "search.calculate_visibility_attribute_test('location','{".join(',', @{$filter->args})."}',$negate)";
1519 } elsif ($filter->name eq 'location_groups') {
1520 if (@{$filter->args} > 0) {
1521 my $negate = $filter->negate ? 'TRUE' : 'FALSE';
1522 push @{$vis_filter{'c_attr'}},
1523 "search.calculate_visibility_attribute_test('location_group','{".join(',', @{$filter->args})."}',$negate)";
1526 } elsif ($filter->name eq 'statuses') {
1527 if (@{$filter->args} > 0) {
1528 my $negate = $filter->negate ? 'TRUE' : 'FALSE';
1529 push @{$vis_filter{'c_attr'}},
1530 "search.calculate_visibility_attribute_test('status','{".join(',', @{$filter->args})."}',$negate)";
1533 } elsif ($filter->name eq 'has_browse_entry') {
1534 if (@{$filter->args} >= 2) {
1535 my $entry = int(shift @{$filter->args});
1536 my $fields = join(",", map(int, @{$filter->args}));
1537 $from .= "\n" . $spc x 3 . sprintf("INNER JOIN metabib.browse_entry_def_map mbedm ON (mbedm.source = m.source AND mbedm.entry = %d AND mbedm.def IN (%s))", $entry, $fields);
1539 } elsif ($filter->name eq 'edit_date' or $filter->name eq 'create_date') {
1540 # bre.create_date and bre.edit_date filtering
1541 my $datefilter = $filter->name;
1545 if ($filter && $filter->args && scalar(@{$filter->args}) > 0 && scalar(@{$filter->args}) < 3) {
1546 my ($cstart, $cend) = @{$filter->args};
1548 if (!$cstart and !$cend) {
1549 # useless use of filter
1550 } elsif (!$cstart or $cstart eq '-infinity') { # no start supplied
1551 if ($cend eq 'infinity') {
1552 # useless use of filter
1555 $cend = cleanse_ISO8601($cend);
1556 $where .= $joiner if $where ne '';
1557 $where .= "bre.$datefilter <= \$_$$\$$cend\$_$$\$";
1560 } elsif (!$cend or $cend eq 'infinity') { # no end supplied
1561 if ($cstart eq '-infinity') {
1562 # useless use of filter
1563 } else { # "after $cstart"
1564 $cstart = cleanse_ISO8601($cstart);
1565 $where .= $joiner if $where ne '';
1566 $where .= "bre.$datefilter >= \$_$$\$$cstart\$_$$\$";
1568 } else { # both supplied
1569 # "between $cstart and $cend"
1570 $cstart = cleanse_ISO8601($cstart);
1571 $cend = cleanse_ISO8601($cend);
1572 $where .= $joiner if $where ne '';
1573 $where .= "bre.$datefilter BETWEEN \$_$$\$$cstart\$_$$\$ AND \$_$$\$$cend\$_$$\$";
1576 } elsif ($filter->name eq 'bib_source') {
1577 if (@{$filter->args} > 0) {
1579 my $negate = $filter->negate ? 'TRUE' : 'FALSE';
1580 push @{$vis_filter{'c_attr'}},
1581 "search.calculate_visibility_attribute_test('source','{".join(',', @{$filter->args})."}',$negate)";
1583 } elsif ($filter->name eq 'from_metarecord') {
1584 if (@{$filter->args} > 0) {
1585 my $key = 'm.metarecord';
1586 $where .= $joiner if $where ne '';
1587 $where .= "$key ${NOT}IN (" . join(',', map { $self->QueryParser->quote_value($_) } @{$filter->args}) . ')';
1595 $where .= $joiner if $where ne '';
1596 if ($common) { # Use a function wrapper to inform PG of the non-rareness of one or more filter elements
1598 'evergreen.query_int_wrapper(mrv.vlist, \'%s\')',
1603 'mrv.vlist @@ \'%s\'',
1609 warn "flatten(): full filter where => $where\n" if $self->QueryParser->debug;
1612 rank_list => \@rank_list,
1616 vis_filter => \%vis_filter,
1617 uses_bre => $uses_bre,
1618 uses_mrv => $uses_mrv,
1619 uses_mrd => $uses_mrd
1624 #-------------------------------
1625 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::filter;
1626 use base 'QueryParser::query_plan::filter';
1628 #-------------------------------
1629 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::facet;
1630 use base 'QueryParser::query_plan::facet';
1634 my ($classname) = split '\|', $self->name;
1640 my ($classname,@fields) = split '\|', $self->name;
1647 my $table_alias = "$self";
1648 $table_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1649 $table_alias .= '_' . $self->name;
1650 $table_alias =~ s/\|/_/go;
1652 return $table_alias;
1656 #-------------------------------
1657 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::modifier;
1658 use base 'QueryParser::query_plan::modifier';
1660 #-------------------------------
1661 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::node::atom;
1662 use base 'QueryParser::query_plan::node::atom';
1668 $self->{sql} = $sql if ($sql);
1670 return $self->{sql} if ($self->{sql});
1671 return $self->buildSQL;
1677 my $classname = $self->node->classname;
1679 return $self->sql("to_tsquery('$classname','')") if $self->{dummy};
1681 my $normalizers = $self->node->plan->QueryParser->query_normalizers( $classname );
1682 my $fields = $self->node->fields;
1685 my $filter = $self->node->plan->find_filter('preferred_language');
1686 $lang ||= $filter->args->[0] if ($filter && $filter->args);
1687 $lang ||= $self->node->plan->QueryParser->default_preferred_language;
1688 my $ts_configs = [];
1690 if (@{$self->node->phrases}) {
1691 # We assume we want 'simple' for phrases. Gives us less to match against later.
1692 $ts_configs = ['simple'];
1695 $ts_configs = $self->node->plan->QueryParser->class_ts_config($classname, $lang);
1697 for my $field (@$fields) {
1698 push @$ts_configs, @{$self->node->plan->QueryParser->field_ts_config($classname, $field, $lang)};
1701 $ts_configs = [keys %{{map { $_ => 1 } @$ts_configs}}];
1704 # Assume we want exact if none otherwise provided.
1705 # Because we can reasonably expect this to exist
1706 $ts_configs = ['simple'] unless (scalar @$ts_configs);
1708 $fields = $self->node->plan->QueryParser->search_fields->{$classname} if (!@$fields);
1712 for my $field (@$fields) {
1713 for my $nfield (keys %$normalizers) {
1714 for my $nizer ( @{$$normalizers{$nfield}} ) {
1715 if ($field eq $nfield) {
1716 my $param_string = OpenSRF::Utils::JSON->perl2JSON($nizer->{params});
1717 if (!exists($norms{$nizer->{function}.$param_string})) {
1718 $norms{$nizer->{function}.$param_string} = {p=>$pos++,n=>$nizer};
1725 my $sql = $self->node->plan->QueryParser->quote_value($self->content);
1727 for my $n ( map { $$_{n} } sort { $$a{p} <=> $$b{p} } values %norms ) {
1728 $sql = join(', ', $sql, map { $self->node->plan->QueryParser->quote_value($_) } @{ $n->{params} });
1729 $sql = $n->{function}."($sql)";
1732 my $prefix = $self->prefix || '';
1733 my $suffix = $self->suffix || '';
1734 my $joiner = ' || ';
1735 $joiner = ' && ' if $self->prefix eq '!'; # Negative atoms should be "none of the variants" instead of "any of the variants"
1737 $prefix = "'$prefix' ||" if $prefix;
1739 my $suffix_after = '';
1741 $suffix_op = ":$suffix" if $suffix;
1742 $suffix_after = "|| '$suffix_op'" if $suffix;
1745 for my $ts_config (@$ts_configs) {
1746 push @sql_set, "to_tsquery('$ts_config', COALESCE(NULLIF($prefix '(' || btrim(regexp_replace($sql,E'(?:\\\\s+|:)','$suffix_op&','g'),'&|') $suffix_after || ')', '()'), ''))";
1749 $sql = join($joiner, @sql_set);
1750 $sql = '(' . $sql . ')' if (scalar(@$ts_configs) > 1);
1752 return $self->sql($sql);
1755 #-------------------------------
1756 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::node;
1757 use base 'QueryParser::query_plan::node';
1762 $self->{dummy_count} = 0;
1764 my $atoms = $self->query_atoms;
1766 for my $a (@$atoms) {
1767 push(@only_atoms, $a) if (ref($a) && $a->isa('QueryParser::query_plan::node::atom'));
1768 $self->{dummy_count}++ if (ref($a) && $a->{dummy});
1771 return \@only_atoms;
1774 sub only_real_atoms {
1777 my $atoms = $self->query_atoms;
1778 my @only_real_atoms;
1779 for my $a (@$atoms) {
1780 push(@only_real_atoms, $a) if (ref($a) && $a->isa('QueryParser::query_plan::node::atom') && !($a->{dummy}));
1783 return \@only_real_atoms;
1786 sub only_positive_atoms {
1789 my $atoms = $self->query_atoms;
1790 my @only_positive_atoms;
1791 for my $a (@$atoms) {
1792 push(@only_positive_atoms, $a) if (ref($a) && $a->isa('QueryParser::query_plan::node::atom') && !($a->{dummy}) && ($a->{prefix} ne '!'));
1795 return \@only_positive_atoms;
1800 return $self->{dummy_count};
1806 $self->{table} = $table if ($table);
1807 return $self->{table} if $self->{table};
1808 return $self->table( 'metabib.' . $self->classname . '_field_entry' );
1811 sub combined_table {
1814 $self->{ctable} = $ctable if ($ctable);
1815 return $self->{ctable} if $self->{ctable};
1816 return $self->combined_table( 'metabib.combined_' . $self->classname . '_field_entry' );
1819 sub combined_search {
1821 return $self->plan->QueryParser->search_class_combined($self->classname);
1826 my $table_alias = shift;
1827 $self->{table_alias} = $table_alias if ($table_alias);
1828 return $self->{table_alias} if ($self->{table_alias});
1830 $table_alias = "$self";
1831 $table_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1832 $table_alias .= '_' . $self->requested_class;
1833 $table_alias =~ s/\|/_/go;
1835 return $self->table_alias( $table_alias );
1840 return $self->{tsquery} if ($self->{tsquery});
1842 for my $atom (@{$self->query_atoms}) {
1844 $self->{tsquery} .= "\n" . ${spc} x 3 . $atom->sql;
1846 $self->{tsquery} .= $atom x 2;
1850 return $self->{tsquery};
1855 return $self->{tsquery_rank} if ($self->{tsquery_rank});
1858 for my $atom (@{$self->only_positive_atoms}) {
1859 push @atomlines, "\n" . ${spc} x 3 . $atom->sql;
1861 $self->{tsquery_rank} = join(' ||', @atomlines);
1862 $self->{tsquery_rank} = 'NULL::tsquery' unless $self->{tsquery_rank};
1863 return $self->{tsquery_rank};
1868 return $self->{rank} if ($self->{rank});
1870 my $rank_norm_map = $self->plan->QueryParser->custom_data->{rank_cd_weight_map};
1872 my $cover_density = 0;
1873 for my $norm ( keys %$rank_norm_map) {
1874 $cover_density += $$rank_norm_map{$norm} if ($self->plan->QueryParser->parse_tree->find_modifier($norm));
1877 my $weights = join(', ', @{$self->plan->QueryParser->search_class_weights($self->classname)});
1879 return $self->{rank} = "ts_rank_cd('{" . $weights . "}', " . $self->table_alias . '.index_vector, ' . $self->table_alias . ".tsq_rank, $cover_density)";