]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Storage/Driver/Pg/QueryParser.pm
LP1915464 follow-up: use spaces, not tabs; remove extra comma
[Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / Application / Storage / Driver / Pg / QueryParser.pm
1 use strict;
2 use warnings;
3
4 package OpenILS::Application::Storage::Driver::Pg::QueryParser;
5 use OpenILS::Application::Storage::QueryParser;
6 use base 'QueryParser';
7 use 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);
12 use Data::Dumper;
13 my $U = 'OpenILS::Application::AppUtils';
14
15 my ${spc} = ' ' x 2;
16 sub subquery_callback {
17     my ($invocant, $self, $struct, $filter, $params, $negate) = @_;
18
19     return sprintf(' ((%s)) ',
20         join(
21             ') || (',
22             map {
23                 $_->query_text
24             } @{
25                 OpenILS::Utils::CStoreEditor
26                     ->new
27                     ->search_actor_search_query({ id => $params })
28             }
29         )
30     );
31 }
32
33 sub filter_group_entry_callback {
34     my ($invocant, $self, $struct, $filter, $params, $negate) = @_;
35
36     return sprintf(' saved_query(%s)', 
37         join(
38             ',', 
39             map {
40                 $_->query
41             } @{
42                 OpenILS::Utils::CStoreEditor
43                     ->new
44                     ->search_actor_search_filter_group_entry({ id => $params })
45             }
46         )
47     );
48 }
49
50 sub format_callback {
51     my ($invocant, $self, $struct, $filter, $params, $negate) = @_;
52
53     my $return = '';
54     my $negate_flag = ($negate ? '-' : '');
55     my @returns;
56     for my $param (@$params) {
57         my ($t,$f) = split('-', $param);
58         my $treturn = '';
59         $treturn .= 'item_type(' . join(',',split('', $t)) . ')' if ($t);
60         $treturn .= ' ' if ($t and $f);
61         $treturn .= 'item_form(' . join(',',split('', $f)) . ')' if ($f);
62         $treturn = '(' . $treturn . ')' if ($t and $f);
63         push(@returns, $treturn) if $treturn;
64     }
65     $return = join(' || ', @returns);
66     $return = '(' . $return . ')' if(@returns > 1);
67     $return = $negate_flag.$return if($return);
68     return $return;
69 }
70
71 sub quote_value {
72     my $self = shift;
73     my $value = shift;
74
75     if ($value =~ /^\d/) { # may have to use non-$ quoting
76         $value =~ s/'/''/g;
77         $value =~ s/\\/\\\\/g;
78         return "E'$value'";
79     }
80     return "\$_$$\$$value\$_$$\$";
81 }
82
83 sub quote_phrase_value {
84     my $self = shift;
85     my $value = shift;
86     my $wb = shift;
87
88     my $left_anchored = '';
89     my $right_anchored = '';
90     my $left_wb = 0;
91     my $right_wb = 0;
92
93     $left_anchored  = $1 if $value =~ m/^([*\^])/;
94     $right_anchored = $1 if $value =~ m/([*\$])$/;
95
96     # We can't use word-boundary bracket expressions if the relevant char
97     # is not actually a "word" characters.
98     $left_wb  = $wb if $value =~ m/^\w+/;
99     $right_wb = $wb if $value =~ m/\w+$/;
100
101     $value =~ s/^[*\^]//   if $left_anchored;
102     $value =~ s/[*\$]$//  if $right_anchored;
103     $value = quotemeta($value);
104     $value = '^' . $value if $left_anchored eq '^';
105     $value = "$value\$"   if $right_anchored eq '$';
106     $value = '[[:<:]]' . $value if $left_wb && !$left_anchored;
107     $value .= '[[:>:]]' if $right_wb && !$right_anchored;
108     return $self->quote_value($value);
109 }
110
111 sub init {
112     my $class = shift;
113 }
114
115 sub default_preferred_language {
116     my $self = shift;
117     my $lang = shift;
118
119     $self->custom_data->{default_preferred_language} = $lang if ($lang);
120     return $self->custom_data->{default_preferred_language};
121 }
122
123 sub default_preferred_language_multiplier {
124     my $self = shift;
125     my $lang = shift;
126
127     $self->custom_data->{default_preferred_language_multiplier} = $lang if ($lang);
128     return $self->custom_data->{default_preferred_language_multiplier};
129 }
130
131 sub max_popularity_importance_multiplier {
132     my $self = shift;
133     my $max = shift;
134
135     $self->custom_data->{max_popularity_importance_multiplier} = $max if defined($max);
136     return $self->custom_data->{max_popularity_importance_multiplier};
137 }
138
139 sub dbh {
140     my $self = shift;
141     my $dbh = shift;
142
143     $self->custom_data->{dbh} = $dbh if defined($dbh);
144     return $self->custom_data->{dbh};
145 }
146
147 sub simple_plan {
148     my $self = shift;
149
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'));
157     }
158
159     return 1;
160 }
161
162 sub toSQL {
163     my $self = shift;
164     return $self->parse_tree->toSQL;
165 }
166
167 sub dynamic_filters {
168     my $self = shift;
169     my $new = shift;
170
171     $self->custom_data->{dynamic_filters} ||= [];
172     push(@{$self->custom_data->{dynamic_filters}}, $new) if ($new);
173     return $self->custom_data->{dynamic_filters};
174 }
175
176 sub dynamic_sorters {
177     my $self = shift;
178     my $new = shift;
179
180     $self->custom_data->{dynamic_sorters} ||= [];
181     push(@{$self->custom_data->{dynamic_sorters}}, $new) if ($new);
182     return $self->custom_data->{dynamic_sorters};
183 }
184
185 sub facet_field_id_map {
186     my $self = shift;
187     my $map = shift;
188
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};
192 }
193
194 sub add_facet_field_id_map {
195     my $self = shift;
196     my $class = shift;
197     my $field = shift;
198     my $id = shift;
199     my $weight = shift;
200
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;
204
205     return {
206         by_id => { $id => { classname => $class, field => $field, weight => $weight } },
207         by_class => { $class => { $field => $id } }
208     };
209 }
210
211 sub facet_field_class_by_id {
212     my $self = shift;
213     my $id = shift;
214
215     return $self->facet_field_id_map->{by_id}{$id};
216 }
217
218 sub facet_field_ids_by_class {
219     my $self = shift;
220     my $class = shift;
221     my $field = shift;
222
223     return undef unless ($class);
224
225     if ($field) {
226         return [$self->facet_field_id_map->{by_class}{$class}{$field}];
227     }
228
229     return [values( %{ $self->facet_field_id_map->{by_class}{$class} } )];
230 }
231
232 sub search_field_id_map {
233     my $self = shift;
234     my $map = shift;
235
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};
239 }
240
241 sub search_field_virtual_map {
242     my $self = shift;
243     my $map = shift;
244
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};
248 }
249
250 sub add_search_field_id_map {
251     my $self = shift;
252     my $class = shift;
253     my $field = shift;
254     my $id = shift;
255     my $weight = shift;
256     my $combined = shift;
257
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;
261
262     return {
263         by_id => { $id => { classname => $class, field => $field, weight => $weight } },
264         by_class => { $class => { $field => $id } }
265     };
266 }
267
268 sub add_search_field_virtual_map {
269     my $self = shift;
270     my $realid = shift;
271     my $virtid = shift;
272     my $weight = shift;
273
274     $self->search_field_virtual_map->{by_virt}{$virtid} ||= [];
275     push @{$self->search_field_virtual_map->{by_virt}{$virtid}}, { real => $realid, weight => $weight };
276
277     $self->search_field_virtual_map->{by_real}{$realid} ||= [];
278     push @{$self->search_field_virtual_map->{by_real}{$realid}}, { virt => $virtid, weight => $weight };
279 }
280
281 sub search_field_class_by_id {
282     my $self = shift;
283     my $id = shift;
284
285     return $self->search_field_id_map->{by_id}{$id};
286 }
287
288 sub search_field_ids_by_class {
289     my $self = shift;
290     my $class = shift;
291     my $field = shift;
292
293     return undef unless ($class);
294
295     if ($field) {
296         return [$self->search_field_id_map->{by_class}{$class}{$field}];
297     }
298
299     return [values( %{ $self->search_field_id_map->{by_class}{$class} } )];
300 }
301
302 sub relevance_bumps {
303     my $self = shift;
304     my $bumps = shift;
305
306     $self->custom_data->{rel_bumps} ||= {};
307     $self->custom_data->{rel_bumps} = $bumps if ($bumps);
308     return $self->custom_data->{rel_bumps};
309 }
310
311 sub find_relevance_bumps {
312     my $self = shift;
313     my $class = shift;
314     my $field = shift;
315
316     return $self->relevance_bumps->{$class}{$field};
317 }
318
319 sub add_relevance_bump {
320     my $self = shift;
321     my $class = shift;
322     my $field = shift;
323     my $type = shift;
324     my $multiplier = shift;
325     my $active = shift;
326
327     if (defined($active) and $active eq 'f') {
328         $active = 0;
329     } else {
330         $active = 1;
331     }
332
333     $self->relevance_bumps->{$class}{$field}{$type} = { multiplier => $multiplier, active => $active };
334
335     return { $class => { $field => { $type => { multiplier => $multiplier, active => $active } } } };
336 }
337
338 sub search_class_weights {
339     my $self = shift;
340     my $class = shift;
341     my $a_weight = shift;
342     my $b_weight = shift;
343     my $c_weight = shift;
344     my $d_weight = shift;
345
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};
351 }
352
353 sub search_class_combined {
354     my $self = shift;
355     my $class = shift;
356     my $c = shift;
357
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};
363 }
364
365 sub class_ts_config {
366     my $self = shift;
367     my $class = shift;
368     my $lang = shift || 'DEFAULT';
369     my $always = shift;
370     my $ts_config = shift;
371
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} ||= [];
380
381     if ($ts_config) {
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;
384     }
385
386     my $return = [];
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;
392     }
393     return $return;
394 }
395
396 sub field_ts_config {
397     my $self = shift;
398     my $class = shift;
399     my $field = shift;
400     my $lang = shift || 'DEFAULT';
401     my $ts_config = shift;
402
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'} ||= [];
408
409     if ($ts_config) {
410         push @{$self->custom_data->{field_ts_config}->{$class}->{$field}->{$lang}}, $ts_config;
411     }
412
413     my $return = [];
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'}};
417     }
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))};
420     return $return;
421 }
422
423 sub initialize_search_field_id_map {
424     my $self = shift;
425     my $cmf_list = shift;
426
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));
430     }
431
432     return $self->search_field_id_map;
433 }
434
435 sub initialize_search_field_virtual_map {
436     my $self = shift;
437     my $cmfvm_list = shift;
438
439     __PACKAGE__->add_search_field_virtual_map( $_->real, $_->virtual, $_->weight )
440         for (@$cmfvm_list);
441
442     $logger->debug('Virtual field map: ' . Dumper($self->search_field_virtual_map));
443     return $self->search_field_virtual_map;
444 }
445
446 sub initialize_aliases {
447     my $self = shift;
448     my $cmsa_list = shift;
449
450     for my $cmsa (@$cmsa_list) {
451         if (!$cmsa->field) {
452             __PACKAGE__->add_search_class_alias( $cmsa->field_class, $cmsa->alias );
453         } else {
454             my $c = $self->search_field_class_by_id( $cmsa->field );
455             __PACKAGE__->add_search_field_alias( $cmsa->field_class, $c->{field}, $cmsa->alias );
456         }
457     }
458 }
459
460 sub initialize_relevance_bumps {
461     my $self = shift;
462     my $sra_list = shift;
463
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 );
467     }
468
469     return $self->relevance_bumps;
470 }
471
472 sub initialize_query_normalizers {
473     my $self = shift;
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" }] }
475
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) );
480     }
481 }
482
483 sub initialize_dynamic_filters {
484     my $self = shift;
485     my $list = shift; # open-ils.cstore.direct.config.record_attr_definition.search.atomic { "id" : { "!=" : null } }
486
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));
490     }
491 }
492
493 sub initialize_filter_normalizers {
494     my $self = shift;
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" }] }
496
497     for my $crainm ( @$tree ) {
498         __PACKAGE__->add_filter_normalizer( $crainm->attr, $crainm->norm->func, OpenSRF::Utils::JSON->JSON2perl($crainm->params) );
499     }
500 }
501
502 sub initialize_search_class_weights {
503     my $self = shift;
504     my $classes = shift;
505
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 );
509     }
510 }
511
512 sub initialize_class_ts_config {
513     my $self = shift;
514     my $class_entries = shift;
515
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);
518     }
519 }
520
521 sub initialize_field_ts_config {
522     my $self = shift;
523     my $field_entries = shift;
524     my $field_objects = shift;
525     my %field_hash = map { $_->id => $_ } @$field_objects;
526
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);
530     }
531 }
532
533 our $_complete = 0;
534 sub initialization_complete {
535     return $_complete;
536 }
537
538 sub initialize {
539     my $self = shift;
540     my %args = @_;
541
542     return $_complete if ($_complete);
543
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,
549         CD_uniqueWords          => 8,
550         CD_logUniqueWords       => 16,
551         CD_selfPlusOne          => 32
552     };
553
554     $self->add_search_modifier( $_ ) for (keys %{ $self->custom_data->{rank_cd_weight_map} });
555
556     $self->initialize_search_field_id_map( $args{config_metabib_field} )
557         if ($args{config_metabib_field});
558
559     $self->initialize_search_field_virtual_map( $args{config_metabib_field_virtual_map} )
560         if ($args{config_metabib_field_virtual_map});
561
562     $self->initialize_aliases( $args{config_metabib_search_alias} )
563         if ($args{config_metabib_search_alias});
564
565     $self->initialize_relevance_bumps( $args{search_relevance_adjustment} )
566         if ($args{search_relevance_adjustment});
567
568     $self->initialize_query_normalizers( $args{config_metabib_field_index_norm_map} )
569         if ($args{config_metabib_field_index_norm_map});
570
571     $self->initialize_dynamic_filters( $args{config_record_attr_definition} )
572         if ($args{config_record_attr_definition});
573
574     $self->initialize_filter_normalizers( $args{config_record_attr_index_norm_map} )
575         if ($args{config_record_attr_index_norm_map});
576
577     $self->initialize_search_class_weights( $args{config_metabib_class} )
578         if ($args{config_metabib_class});
579
580     $self->initialize_class_ts_config( $args{config_metabib_class_ts_map} )
581         if ($args{config_metabib_class_ts_map});
582
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});
585
586     $_complete = 1 if (
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}
592     );
593
594     return $_complete;
595 }
596
597 sub TEST_SETUP {
598     
599     __PACKAGE__->allow_nested_modifiers(1);
600
601     __PACKAGE__->add_search_field_id_map( series => seriestitle => 1 => 1 );
602
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 );
606     
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 );
610     
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 );
614     
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 );
620     
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 );
624     
625     __PACKAGE__->add_facet_field_id_map( author => personal => 8 => 1 );
626
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' );
632     
633     __PACKAGE__->add_facet_field_id_map( subject => topic => 14 => 1 );
634
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 );
638     
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 );
642     
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 );
646     
647     __PACKAGE__->add_search_field_virtual_map( 6 => 15 => 5 );
648
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' );
659
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' );
666
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' );
670     
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' );
680     
681     __PACKAGE__->add_query_normalizer( author => corporate => 'search_normalize' );
682     __PACKAGE__->add_query_normalizer( keyword => keyword => 'search_normalize' );
683     
684     __PACKAGE__->add_search_field_alias( subject => name => 'bib.subjectName' );
685     
686     #__PACKAGE__->search_class_combined( keyword => 1 );
687     __PACKAGE__->search_class_combined( author => 1 );
688 }
689
690 __PACKAGE__->default_search_class( 'keyword' );
691
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(@_) } );
695
696 # will be retained simply for back-compat
697 __PACKAGE__->add_search_filter( 'format', sub { return __PACKAGE__->format_callback(@_) } );
698
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' );
704
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' );
733
734 # Start from container data (bre, acn, acp): container(bre,bookbag,123,deadb33fdeadb33fdeadb33fdeadb33f)
735 __PACKAGE__->add_search_filter( 'container' );
736
737 # Start from a list of record ids, either bre or metarecords, depending on the #metabib modifier
738 __PACKAGE__->add_search_filter( 'record_list' );
739
740 __PACKAGE__->add_search_filter( 'has_browse_entry' );
741
742 # copy_tag(copy_tag_code,copy_tag_search)
743 __PACKAGE__->add_search_filter( 'copy_tag' );
744
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' );
750
751 # XXX Valid values to be supplied by SVF
752 __PACKAGE__->add_search_filter( 'sort' );
753
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' );
761
762
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/;
768 use Data::Dumper;
769 use OpenILS::Application::AppUtils;
770 use OpenILS::Utils::Normalize qw/search_normalize/;
771 my $apputils = "OpenILS::Application::AppUtils";
772
773 our %_dfilter_controlled_cache = ();
774 our %_dfilter_stats_cache = ();
775 our $_pg_version = 0;
776
777 sub dynamic_filter_compile {
778     my ($self, $filter, $params, $negate) = @_;
779     my $e = OpenILS::Utils::CStoreEditor->new;
780
781     $negate = $negate ? '!' : '';
782
783     if (!$_pg_version) {
784         ($_pg_version = $e->json_query({from => ['version']})->[0]->{version}) =~ s/^.+?(\d\.\d).+$/$1/;
785     }
786
787     my $common = 0;
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
794         }
795     } else {
796         $common = 1; # Assume it's expensive
797     }
798
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});
802
803         $_dfilter_controlled_cache{$filter} = $crad->to_bare_hash;
804         $_dfilter_controlled_cache{$filter}{controlled} = scalar @$ccvm_list;
805     }
806
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} ?
810         'ctype' : 'attr';
811     my $value_field = $_dfilter_controlled_cache{$filter}{controlled} ?
812         'code' : 'value';
813
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;
816     
817     return (sprintf('%s(%s)', $negate,
818         join(
819             '|', 
820             map { $_->id } @$attr_objects
821         )
822     ), $common);
823 }
824
825 sub toSQL {
826     my $self = shift;
827
828     my %filters;
829
830     for my $f ( qw/preferred_language preferred_language_multiplier preferred_language_weight core_limit check_limit skip_check superpage superpage_size/ ) {
831         my $col = $f;
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];
836         }
837     }
838
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});
842
843     $logger->debug("Query plan:\n".Dumper($self));
844
845     my $flat_plan = $self->flatten;
846
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}}) {
850         $rel = "AVG(\n"
851              . ${spc} x 5 ."("
852              . join(")\n" . ${spc} x 5 . "+ (", @{$$flat_plan{rank_list}})
853              . ")\n"
854              . ${spc} x 4 . ")+1";
855     }
856
857     # find any supplied sort option
858     my ($sort_filter) = $self->find_filter('sort');
859     if ($sort_filter) {
860         $sort_filter = $sort_filter->args->[0];
861     } else {
862         $sort_filter = 'rel';
863     }
864
865     my $lang_join = '';
866     if (($filters{preferred_language} || $self->QueryParser->default_preferred_language) && ($filters{preferred_language_multiplier} || $self->QueryParser->default_preferred_language_multiplier)) {
867     
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";
872
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;
876     }
877
878     my $mrv_join = '';
879     if ($$flat_plan{uses_mrv}) {
880         $mrv_join = 'INNER JOIN metabib.record_attr_vector_list mrv ON m.source = mrv.source';
881     }
882
883     my $mra_join = '';
884     if ($$flat_plan{uses_mrd}) {
885         $mra_join = 'INNER JOIN metabib.record_attr mrd ON m.source = mrd.id';
886     }
887
888     my $pubdate_join = "LEFT JOIN metabib.record_sorter pubdate_t ON m.source = pubdate_t.source AND attr = 'pubdate'";
889
890     my $bre_join = '';
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
894         # is in use.
895     } else {
896         $bre_join = 'INNER JOIN biblio.record_entry bre ON m.source = bre.id AND NOT bre.deleted';
897     }
898
899     my $desc = 'ASC';
900     $desc = 'DESC' if ($self->find_modifier('descending'));
901
902     my $nullpos = 'NULLS LAST';
903     $nullpos = 'NULLS FIRST' if ($self->find_modifier('nullsfirst'));
904
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($_)};
919                 }
920                 my $course_org_string = join q{,}, @$course_orgs_with_descendants;
921                 $course_org_filter .= "AND acmc.owning_lib IN ($course_org_string) ";
922             }
923         }
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';
929         } else {
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";
932         }
933     }
934
935     # Do we have a badges() filter?
936     my $badges = '';
937     my ($badge_filter) = $self->find_filter('badges');
938     if ($badge_filter && @{$badge_filter->args}) {
939         $badges = join (',', grep /^\d+$/, @{$badge_filter->args});
940     }
941
942     # Do we have a badge_orgs() filter? (used for calculating popularity)
943     my $borgs = '';
944     my ($bo_filter) = $self->find_filter('badge_orgs');
945     if ($bo_filter && @{$bo_filter->args}) {
946         $borgs = join (',', grep /^\d+$/, @{$bo_filter->args});
947     }
948
949     # Build the badge-ish WITH query
950     my $pop_with = <<'    WITH';
951         pop_with AS (
952             SELECT  record,
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 (
957                         b.id = s.badge
958     WITH
959
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)'; 
963
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 )';
967
968     $$flat_plan{with} .= ',' if $$flat_plan{with};
969     $$flat_plan{with} .= $pop_with;
970
971
972     my $rank;
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
985                                             # zero
986
987         if ( $max_mult == 1.0 ) { # no adjustment requested by the configuration
988             $rank = "1.0/($rel)::NUMERIC";
989         } else { # calculate adjustment
990
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
995             # of 0.2:
996             #
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
1001             #    2.0:
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.
1005             #
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.
1014             #
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.
1023             #
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.
1031
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";
1034         }
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,";
1039     } else {
1040         # default to rel ranking
1041         $rank = "1.0/($rel)::NUMERIC";
1042     }
1043
1044     my $key = 'm.source';
1045     $key = 'm.metarecord' if (grep {$_->name eq 'metarecord' or $_->name eq 'metabib'} @{$self->modifiers});
1046
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;
1051         $core_limit = 1;
1052     }
1053
1054
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 . ")";
1058     }
1059
1060     my $final_c_attr_test;
1061     my $c_attr_join = '';
1062     my $c_vis_test = '';
1063     my $pc_vis_test = '';
1064
1065     # copy visibility testing
1066     if (!$self->find_modifier('staff')) {
1067         $pc_vis_test = "c_attrs";
1068         $c_attr_join = ",c_attr"
1069     }
1070
1071     if ($self->find_modifier('available')) {
1072         push @{$$flat_plan{vis_filter}{'c_attr'}},
1073             "search.calculate_visibility_attribute_test('status','{0,7,12}')";
1074     }
1075
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';
1079     }
1080
1081     if ($c_vis_test or $pc_vis_test) {
1082         my $vis_test = '';
1083
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;
1088         } else {
1089             $vis_test = $c_vis_test;
1090         }
1091
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)";
1095
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)';
1097     }
1098  
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) ))".
1104             "))";
1105         # We need bre here, regardless
1106         $bre_join ||= 'INNER JOIN biblio.record_entry bre ON m.source = bre.id AND NOT bre.deleted';
1107     }
1108
1109     my $final_b_attr_test;
1110     my $b_attr_join = '';
1111     my $b_vis_test = '';
1112     my $pb_vis_test = '';
1113
1114     # bib visibility testing
1115     if (!$self->find_modifier('staff')) {
1116         $pb_vis_test = "b_attrs";
1117         $b_attr_join = ",b_attr"
1118     }
1119
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}});
1123     }
1124
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) {
1127         my $vis_test = '';
1128
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,'|&')";
1133         } else {
1134             $vis_test = $b_vis_test;
1135         }
1136
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)";
1140
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)';
1143     }
1144
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 . ")";
1153         }
1154     }
1155
1156     my $with = $$flat_plan{with};
1157     $with= "\nWITH $with" if $with;
1158
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';
1165     }
1166
1167     my $sql = <<SQL;
1168 WITH w AS (
1169
1170 $with
1171 SELECT  id,
1172         rel,
1173         CASE WHEN cardinality(records) = 1 THEN records[1] ELSE NULL END AS record,
1174         NULL::INT AS total,
1175         NULL::INT AS checked,
1176         NULL::INT AS visible,
1177         NULL::INT AS deleted,
1178         NULL::INT AS excluded,
1179         badges,
1180         popularity
1181   FROM  (SELECT $key AS id,
1182                 $agg_records,
1183                 ${rel}::NUMERIC AS rel,
1184                 $rank AS rank, 
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
1189                 $$flat_plan{from}
1190                 $mra_join
1191                 $mrv_join
1192                 $bre_join
1193                 $course_join
1194                 $pop_join
1195                 $pubdate_join
1196                 $lang_join
1197                 $c_attr_join
1198                 $b_attr_join
1199           WHERE 1=1
1200                 $flat_where
1201                 $course_where
1202           GROUP BY 1
1203           ORDER BY 4 $desc $nullpos, $pop_extra_sort 5 DESC $nullpos, 3 DESC
1204           LIMIT $core_limit
1205         ) AS core_query
1206 ) (SELECT * FROM w LIMIT $filters{check_limit} OFFSET $filters{skip_check})
1207         UNION ALL
1208   SELECT NULL,NULL,NULL,COUNT(*),COUNT(*),COUNT(*),0,0,NULL,NULL FROM w;
1209 SQL
1210
1211     warn $sql if $self->QueryParser->debug;
1212     return $sql;
1213
1214 }
1215
1216 sub is_org_visible {
1217     my $org = shift;
1218     return 0 if (!$U->is_true($org->opac_visible));
1219
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));
1222
1223     while ($org = $org->parent_ou) {
1224         return 0 if (!$U->is_true($org->opac_visible));
1225     }
1226     return 1;
1227 }
1228
1229 sub flesh_parents {
1230     my $t = shift;
1231     my $kids = $t->children;
1232     if ($kids && @$kids) {
1233         map {$_->parent_ou($t); flesh_parents($_)} @$kids;
1234     }
1235 }
1236
1237 sub unflesh_parents {
1238     my $t = shift;
1239     my $kids = $t->children;
1240     if ($kids && @$kids) {
1241         map {$_->parent_ou($t->id); unflesh_parents($_)} @$kids;
1242     }
1243 }
1244
1245 sub flatten {
1246     my $self = shift;
1247
1248     die 'ERROR: nesting too deep or boolean list too long' if ($self->plan_level > 40);
1249
1250     my $from = shift || '';
1251     my $where = shift || '';
1252     my $with = '';
1253     my %vis_filter = ( c_attr => [], b_attr => [] );
1254     my $uses_bre = 0;
1255     my $uses_mrd = 0;
1256     my $uses_mrv = 0;
1257
1258     my @rank_list;
1259     for my $node ( @{$self->query_nodes} ) {
1260
1261         if (ref($node)) {
1262             if ($node->isa( 'QueryParser::query_plan::node' )) {
1263
1264                 unless (@{$node->only_atoms}) {
1265                     push @rank_list, '1';
1266                     $where .= 'TRUE';
1267                     next;
1268                 }
1269
1270                 my @bump_fields;
1271                 my @field_ids;
1272                 if (@{$node->fields} > 0) {
1273                     @bump_fields = @{$node->fields};
1274
1275                     @field_ids = grep defined, (
1276                         map {
1277                             $self->QueryParser->search_field_ids_by_class(
1278                                 $node->classname, $_
1279                             )->[0]
1280                         } @bump_fields
1281                     );
1282                 } else {
1283                     @bump_fields = @{$self->QueryParser->search_fields->{$node->classname}};
1284                 }
1285
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);
1289
1290                 my $table = $node->table;
1291                 my $ctable = $node->combined_table;
1292                 my $talias = $node->table_alias;
1293
1294                 my $node_rank = 'COALESCE(' . $node->rank . " * ${talias}.weight * 1000, 0.0)";
1295
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)";
1300
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";
1306                         if (@field_ids) {
1307                             $search_cte .= " AND com.metabib_field IN (" . join(',',@field_ids) . "))";
1308                         } else {
1309                             $search_cte .= " AND com.metabib_field IS NULL)";
1310                         }
1311                         $search_cte .= "\n" . ${spc} x 7 . "JOIN ${talias}_xq ON (com.index_vector @@ ${talias}_xq.tsq)";
1312                     } else {
1313                         $search_cte .= "\n" . ${spc} x 7 . "JOIN ${talias}_xq ON (fe.index_vector @@ ${talias}_xq.tsq)";
1314                     }
1315                 } else {
1316                     $search_cte .= "\n" . ${spc} x 7 . ", (SELECT NULL::tsquery AS tsq, NULL::tsquery AS tsq_rank ) AS ${talias}_xq";
1317                 }
1318
1319                 if (@field_ids) {
1320                     $search_cte .= "\n" . ${spc} x 6 . "WHERE fe_weight.id IN  (" .
1321                         join(',', @field_ids) . ")";
1322                 }
1323
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;
1334
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}};
1338
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(
1342                                     $self->QueryParser
1343                                         ->search_field_class_by_id($$real_field{real})
1344                                         ->{classname}
1345                                 );
1346                                 $vtable_field_map{$vtable} ||= [];
1347                                 push(@{$vtable_field_map{$vtable}}, $$real_field{real})
1348                                     if ($$real_field{weight} != $$natural_field{weight});
1349                             }
1350
1351                             for my $vtable (keys %vtable_field_map) {
1352                                 my $rfields = $vtable_field_map{$vtable};
1353                                 next unless (@$rfields);
1354
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)"
1366                                 ;
1367                             }
1368                         }
1369                     }
1370                 }
1371
1372                 $with .= $search_cte . ')';
1373                 $from .= "\n" . ${spc} x 4 . "LEFT JOIN $talias ON (m.source = ${talias}.source)";
1374
1375                 my %used_bumps;
1376                 my @bumps;
1377                 my @bumpmults;
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;
1384
1385                         next if ($$bumps{$b}{multiplier} == 1); # optimization to remove unneeded bumps
1386                         push @bumps, $b;
1387                         push @bumpmults, $$bumps{$b}{multiplier};
1388                     }
1389                 }
1390
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)";
1396                 }
1397
1398                 my $NOT = '';
1399                 $NOT = 'NOT ' if $node->negate;
1400
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});
1405                 }
1406                 $where .= ')';
1407
1408                 push @rank_list, $node_rank;
1409
1410             } elsif ($node->isa( 'QueryParser::query_plan::facet' )) {
1411
1412                 my $talias = $node->table_alias;
1413
1414                 my @field_ids;
1415                 if (@{$node->fields} > 0) {
1416                     push(@field_ids, $self->QueryParser->facet_field_ids_by_class( $node->classname, $_ )->[0]) for (@{$node->fields});
1417                 } else {
1418                     @field_ids = @{ $self->QueryParser->facet_field_ids_by_class( $node->classname ) };
1419                 }
1420
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"
1427                       . "${spc})";
1428
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$//;
1435                 }
1436
1437             } else {
1438                 my $subnode = $node->flatten;
1439
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$//;
1444                 }
1445
1446                 push(@rank_list, @{$$subnode{rank_list}});
1447                 $from .= $$subnode{from};
1448
1449                 my $NOT = '';
1450                 $NOT = 'NOT ' if $node->negate;
1451
1452                 if ($$subnode{where} ne '') {
1453                     $where .= "$NOT(\n"
1454                            . ${spc} x ($self->plan_level + 6) . $$subnode{where} . "\n"
1455                            . ${spc} x ($self->plan_level + 5) . ')';
1456                 }
1457
1458                 if ($$subnode{with}) {
1459                     $with .= ",\n     " if $with;
1460                     $with .= $$subnode{with};
1461                 }
1462
1463                 $uses_bre = $$subnode{uses_bre};
1464                 $uses_mrd = $$subnode{uses_mrd};
1465                 $uses_mrv = $$subnode{uses_mrv};
1466             }
1467         } else {
1468
1469             warn "flatten(): appending WHERE bool to: $where\n" if $self->QueryParser->debug;
1470
1471             if ($where ne '') {
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 '|');
1474             }
1475         }
1476     }
1477
1478     my $joiner = "\n" . ${spc} x ( $self->plan_level + 5 ) . ($self->joiner eq '&' ? 'AND ' : 'OR ');
1479
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];
1483     }
1484
1485     my $ot = $U->get_org_tree;
1486     my $site_org = $ot;
1487     my $negate = 'FALSE';
1488
1489     my @lasso_list;
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';
1493
1494         my $lasso = $lasso_filter->args->[0];
1495         if ($lasso !~ /^\d+$/) {
1496             $lasso = $U->find_lasso_by_name($lasso);
1497         }
1498
1499         if ($lasso) {
1500             $lasso = $lasso->id if (ref $lasso);
1501             @lasso_list = map { $_->org_unit } @{ $U->fetch_lasso_org_maps($lasso) };
1502         }
1503     }
1504
1505
1506     if (!@lasso_list) {
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';
1510
1511            my $sitename = $site_filter->args->[0];
1512            $site_org = $U->find_org_by_shortname($ot, $sitename) || $ot;
1513         }
1514     }
1515
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);
1518
1519     flesh_parents($ot);
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 ];
1524     }
1525     unflesh_parents($ot);
1526
1527     push @{$vis_filter{'c_attr'}},
1528         "search.calculate_visibility_attribute_test('circ_lib','{".join(',', @$dorgs)."}',$negate)";
1529
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));
1535
1536         $uses_bre = 1;
1537         push @{$vis_filter{'b_attr'}},
1538             "search.calculate_visibility_attribute_test('luri_org','{".join(',', @$lorgs)."}',$negate)";
1539     }
1540
1541     my @dlist = ();
1542     my $common = 0;
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 }) {
1547
1548             my $fname = $filter->name;
1549             $fname = 'item_lang' if $fname eq 'language'; #XXX filter aliases 
1550
1551             warn "flatten(): processing dynamic filter ". $filter->name ."\n"
1552                 if $self->QueryParser->debug;
1553
1554             my $vlist_query;
1555             ($vlist_query, $common) = $self->dynamic_filter_compile( $fname, $filter->args, $filter->negate );
1556
1557             # bool joiner for intra-plan nodes/filters
1558             push(@dlist, $self->joiner) if @dlist;
1559             push(@dlist, $vlist_query);
1560             $uses_mrv = 1;
1561         } else {
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])
1567                            . ", false)";
1568                 }
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])
1574                            . ", false)";
1575                 }
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)";
1582                     $uses_mrd = 1;
1583                 }
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])
1589                            . " AND "
1590                            . $self->QueryParser->quote_value($filter->args->[1])
1591                            . ", false)";
1592                 }
1593             } elsif ($filter->name eq 'container') {
1594                 if (@{$filter->args} >= 3) {
1595                     my ($class, $ctype, $cid, $token) = @{$filter->args};
1596                     my $perm_join = '';
1597                     my $rec_join = '';
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') {
1606                         $class = 'copy';
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)';
1609                     } else {
1610                         $class = undef;
1611                     }
1612
1613                     if ($class) {
1614                         my ($u,$e) = $apputils->checksesperm($token) if ($token);
1615                         $perm_join = ' OR c.owner = ' . $u->id if ($u && !$e);
1616
1617                         my $filter_alias = "$filter";
1618                         $filter_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1619                         $filter_alias =~ s/\|/_/go;
1620
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') {
1629                             $with .= "       UNION\n"
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";
1636                         }
1637                         $with .= "     )";
1638
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";
1641
1642                         if (!$optimize_join) {
1643                             $where .= $joiner if $where ne '';
1644                             $where .= "(container_${filter_alias} IS " . ( $NOT ? 'NULL)' : 'NOT NULL)');
1645                         }
1646                     }
1647                 }
1648             } elsif ($filter->name eq 'copy_tag') {
1649                 my $valid_copy_tag_search = 0;
1650                 my $copy_tag_type;
1651                 my $tag_value;
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;
1657                 }
1658                 if ($valid_copy_tag_search) {
1659                     my $norm_value = search_normalize($tag_value);
1660                     my @tokens = split /\s+/, $norm_value;
1661                     
1662                     my $filter_alias = "$filter";
1663                     $filter_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1664                     $filter_alias =~ s/\|/_/go;
1665
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";
1677                     }
1678                     if (@tokens) {
1679                         $with .= '             AND acpt.value @@ to_tsquery(' . $self->QueryParser->quote_value(join(' & ', @tokens)) . ")\n";
1680                     }
1681                     if (!$self->find_modifier('staff')) {
1682                         $with .= "             AND acpt.pub IS TRUE\n";
1683                     }
1684                     $with .= "     )";
1685
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";
1688
1689                     if (!$optimize_join) {
1690                         $where .= $joiner if $where ne '';
1691                         $where .= "(copy_tag_${filter_alias} IS " . ( $NOT ? 'NULL)' : 'NOT NULL)');
1692                     }
1693                 }
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}) . ')';
1700                 }
1701
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)";
1708                 }
1709
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)";
1716                 }
1717
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)";
1723                 }
1724
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);
1730                 }
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;
1734
1735                 $uses_bre = 1;
1736
1737                 if ($filter && $filter->args && scalar(@{$filter->args}) > 0 && scalar(@{$filter->args}) < 3) {
1738                     my ($cstart, $cend) = @{$filter->args};
1739         
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
1745                         } else {
1746                             # "before $cend"
1747                             $cend = clean_ISO8601($cend);
1748                             $where .= $joiner if $where ne '';
1749                             $where .= "bre.$datefilter <= \$_$$\$$cend\$_$$\$";
1750                         }
1751             
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\$_$$\$";
1759                         }
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\$_$$\$";
1766                     }
1767                 }
1768             } elsif ($filter->name eq 'bib_source') {
1769                 if (@{$filter->args} > 0) {
1770                     $uses_bre = 1;
1771                     my $negate = $filter->negate ? 'TRUE' : 'FALSE';
1772                     push @{$vis_filter{'b_attr'}},
1773                         "search.calculate_visibility_attribute_test('source','{".join(',', @{$filter->args})."}',$negate)";
1774                 }
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}) . ')';
1780                 }
1781             }
1782         }
1783     }
1784
1785     if (@dlist) {
1786
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
1789             $where .= sprintf(
1790                 'evergreen.query_int_wrapper(mrv.vlist, \'%s\')',
1791                 join('', @dlist)
1792             );
1793         } else {
1794             $where .= sprintf(
1795                 'mrv.vlist @@ \'%s\'',
1796                 join('', @dlist)
1797             );
1798         }
1799     }
1800
1801     warn "flatten(): full filter where => $where\n" if $self->QueryParser->debug;
1802
1803     return {
1804         rank_list => \@rank_list,
1805         from => $from,
1806         where => $where,
1807         with => $with,
1808         vis_filter => \%vis_filter,
1809         uses_bre => $uses_bre,
1810         uses_mrv => $uses_mrv,
1811         uses_mrd => $uses_mrd
1812     };
1813 }
1814
1815
1816 #-------------------------------
1817 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::filter;
1818 use base 'QueryParser::query_plan::filter';
1819
1820 #-------------------------------
1821 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::facet;
1822 use base 'QueryParser::query_plan::facet';
1823
1824 sub classname {
1825     my $self = shift;
1826     my ($classname) = split '\|', $self->name;
1827     return $classname;
1828 }
1829
1830 sub fields {
1831     my $self = shift;
1832     my ($classname,@fields) = split '\|', $self->name;
1833     return \@fields;
1834 }
1835
1836 sub table_alias {
1837     my $self = shift;
1838     my $suffix = shift;
1839
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);
1845
1846     return $table_alias;
1847 }
1848
1849
1850 #-------------------------------
1851 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::modifier;
1852 use base 'QueryParser::query_plan::modifier';
1853
1854 #-------------------------------
1855 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::node::atom;
1856 use base 'QueryParser::query_plan::node::atom';
1857
1858 sub sql {
1859     my $self = shift;
1860     my $sql = shift;
1861
1862     $self->{sql} = $sql if ($sql);
1863
1864     return $self->{sql} if ($self->{sql});
1865     return $self->buildSQL;
1866 }
1867
1868 sub buildSQL {
1869     my $self = shift;
1870
1871     my $classname = $self->node->classname;
1872
1873     return $self->sql("''::tsquery") if $self->{dummy};
1874
1875     my $normalizers = $self->node->plan->QueryParser->query_normalizers( $classname );
1876
1877     my $fields = $self->node->fields;
1878     $fields = $self->node->plan->QueryParser->search_fields->{$classname} if (!@$fields);
1879
1880     my %norms;
1881     my $pos = 0;
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};
1889                     }
1890                 }
1891             }
1892         }
1893     }
1894
1895     my $sql = $self->node->plan->QueryParser->quote_value($self->content);
1896
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)";
1900     }
1901
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"
1906
1907     $prefix = "'$prefix' ||" if $prefix;
1908     my $suffix_op = '';
1909     my $suffix_after = '';
1910
1911     $suffix_op = ":$suffix" if $suffix;
1912     $suffix_after = "|| '$suffix_op'" if $suffix;
1913
1914     my $ts_configs = $self->node->ts_configs;
1915
1916     my @sql_set = ();
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 '()'), ''))";
1919     }
1920
1921     $sql = join($joiner, @sql_set);
1922     $sql = '(' . $sql . ')' if (scalar(@$ts_configs) > 1);
1923
1924     return $self->sql($sql);
1925 }
1926
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/;
1931 use Data::Dumper;
1932
1933 sub ts_configs {
1934     my $self = shift;
1935     my $ts_configs = $self->{ts_configs} || [];
1936
1937     if (!@$ts_configs) {
1938         my $classname = $self->classname;
1939         my $lang;
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;
1943
1944         my $fields = $self->fields;
1945         if (!@$fields) {
1946             $ts_configs = $self->plan->QueryParser->class_ts_config($classname, $lang);
1947         } else {
1948             for my $field (@$fields) {
1949                 push @$ts_configs, @{$self->plan->QueryParser->field_ts_config($classname, $field, $lang)};
1950             }
1951         }
1952         $ts_configs = [keys %{{map { $_ => 1 } @$ts_configs}}];
1953
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;
1958     }
1959
1960     return $ts_configs;
1961 }
1962
1963 sub abstract_node_additions {
1964     my $self = shift;
1965     my $aq = shift;
1966
1967     my $hm = $self->plan
1968                 ->QueryParser
1969                 ->parse_tree
1970                 ->get_abstract_data('highlight_map') // {};
1971
1972     return unless ref($hm);
1973
1974     my $field_set = $self->fields;
1975     $field_set = $self->plan->QueryParser->search_fields->{$self->classname}
1976         if (!@$field_set);
1977
1978     my @field_ids = grep defined, (
1979         map {
1980             $self->plan->QueryParser->search_field_ids_by_class(
1981                 $self->classname, $_
1982             )->[0]
1983         } @$field_set
1984     );
1985
1986     push @field_ids, @{$self->{vfields}} if $self->{vfields};
1987
1988     my $ts_query = $self->tsquery_rank;
1989
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.
1995
1996     my %inverted_hm;
1997     for my $t (keys %$hm) {
1998         for my $f (@{$$hm{$t}}) {
1999             $inverted_hm{$f} = $t;
2000         }
2001     }
2002
2003     # Then, loop over new fields and put them in the inverted hash.
2004     my @existing_fields = keys %inverted_hm;
2005
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;
2012             }
2013         } else { # New field
2014             $inverted_hm{$f} = $ts_query;
2015         }
2016     }
2017
2018     # Now, flip it back over.
2019     $hm = {};
2020     for my $f (keys %inverted_hm) {
2021         my $t = $inverted_hm{$f};
2022         if ($$hm{$t}) {
2023             push @{$$hm{$t}}, $f;
2024         } else {
2025             $$hm{$t} = [$f];
2026         }
2027     }
2028
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')";
2035     }
2036
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);
2041
2042     $self->plan
2043         ->QueryParser
2044         ->parse_tree
2045         ->set_abstract_data('highlight_map', $calculated_hm);
2046 }
2047
2048 sub add_vfield {
2049     my $self = shift;
2050     my $vfield = shift;
2051
2052     $self->{vfields} ||= [];
2053     push @{$self->{vfields}}, $vfield;
2054 }
2055
2056 sub only_atoms {
2057     my $self = shift;
2058
2059     $self->{dummy_count} = 0;
2060
2061     my $atoms = $self->query_atoms;
2062     my @only_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});
2066     }
2067
2068     return \@only_atoms;
2069 }
2070
2071 sub only_real_atoms {
2072     my $self = shift;
2073
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}));
2078     }
2079
2080     return \@only_real_atoms;
2081 }
2082
2083 sub only_positive_atoms {
2084     my $self = shift;
2085
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 '!'));
2090     }
2091
2092     return \@only_positive_atoms;
2093 }
2094
2095 sub dummy_count {
2096     my $self = shift;
2097     return $self->{dummy_count};
2098 }
2099
2100 sub table {
2101     my $self = shift;
2102     my $classname = shift || $self->classname;
2103     return 'metabib.' . $classname . '_field_entry';
2104 }
2105
2106 sub combined_table {
2107     my $self = shift;
2108     my $classname = shift || $self->classname;
2109     return 'metabib.combined_' . $classname . '_field_entry';
2110 }
2111
2112 sub combined_search {
2113     my $self = shift;
2114     return $self->plan->QueryParser->search_class_combined($self->classname);
2115 }
2116
2117 sub table_alias {
2118     my $self = shift;
2119     my $suffix = shift;
2120
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);
2126
2127     return $table_alias;
2128 }
2129
2130 sub tsquery {
2131     my $self = shift;
2132     return $self->{tsquery} if ($self->{tsquery});
2133
2134     for my $atom (@{$self->query_atoms}) {
2135         if (ref($atom)) {
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;
2140         } else {
2141             $self->{tsquery} .= $atom x 2;
2142         }
2143     }
2144
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(
2150             ' && ',
2151             map { "${neg}phraseto_tsquery('simple', \$_$$\$$_\$_$$\$)" } @phrases
2152         );
2153     }
2154
2155     return $self->{tsquery};
2156 }
2157
2158 sub tsquery_rank {
2159     my $self = shift;
2160     return $self->{tsquery_rank} if ($self->{tsquery_rank});
2161     my @atomlines;
2162
2163     for my $atom (@{$self->only_positive_atoms}) {
2164         push @atomlines, "\n" . ${spc} x 3 . $atom->sql;
2165     }
2166     $self->{tsquery_rank} = join(' ||', @atomlines);
2167     $self->{tsquery_rank} = "''::tsquery" unless $self->{tsquery_rank};
2168
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(
2174                     ' || ',
2175                     map { "phraseto_tsquery('$tsc', \$_$$\$$_\$_$$\$)" } @phrases
2176                 );
2177             }
2178         }
2179     }
2180
2181     return $self->{tsquery_rank};
2182 }
2183
2184 sub rank {
2185     my $self = shift;
2186     return $self->{rank} if ($self->{rank});
2187
2188     my $rank_norm_map = $self->plan->QueryParser->custom_data->{rank_cd_weight_map};
2189
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));
2193     }
2194
2195     my $weights = join(', ', @{$self->plan->QueryParser->search_class_weights($self->classname)});
2196
2197     return $self->{rank} = "ts_rank_cd('{" . $weights . "}', " . $self->table_alias . '.index_vector, ' . $self->table_alias . ".tsq_rank, $cover_density)";
2198 }
2199
2200
2201 1;
2202