]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Storage/Driver/Pg/QueryParser.pm
LP#1673857: add search filter for copy_tags
[Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / Application / Storage / Driver / Pg / QueryParser.pm
1 use strict;
2 use warnings;
3
4 package OpenILS::Application::Storage::Driver::Pg::QueryParser;
5 use OpenILS::Application::Storage::QueryParser;
6 use base 'QueryParser';
7 use OpenSRF::Utils qw/:datetime/;
8 use OpenSRF::Utils::JSON;
9 use OpenILS::Application::AppUtils;
10 use OpenILS::Utils::CStoreEditor;
11 my $U = 'OpenILS::Application::AppUtils';
12
13 my ${spc} = ' ' x 2;
14 sub subquery_callback {
15     my ($invocant, $self, $struct, $filter, $params, $negate) = @_;
16
17     return sprintf(' ((%s)) ',
18         join(
19             ') || (',
20             map {
21                 $_->query_text
22             } @{
23                 OpenILS::Utils::CStoreEditor
24                     ->new
25                     ->search_actor_search_query({ id => $params })
26             }
27         )
28     );
29 }
30
31 sub filter_group_entry_callback {
32     my ($invocant, $self, $struct, $filter, $params, $negate) = @_;
33
34     return sprintf(' saved_query(%s)', 
35         join(
36             ',', 
37             map {
38                 $_->query
39             } @{
40                 OpenILS::Utils::CStoreEditor
41                     ->new
42                     ->search_actor_search_filter_group_entry({ id => $params })
43             }
44         )
45     );
46 }
47
48 sub format_callback {
49     my ($invocant, $self, $struct, $filter, $params, $negate) = @_;
50
51     my $return = '';
52     my $negate_flag = ($negate ? '-' : '');
53     my @returns;
54     for my $param (@$params) {
55         my ($t,$f) = split('-', $param);
56         my $treturn = '';
57         $treturn .= 'item_type(' . join(',',split('', $t)) . ')' if ($t);
58         $treturn .= ' ' if ($t and $f);
59         $treturn .= 'item_form(' . join(',',split('', $f)) . ')' if ($f);
60         $treturn = '(' . $treturn . ')' if ($t and $f);
61         push(@returns, $treturn) if $treturn;
62     }
63     $return = join(' || ', @returns);
64     $return = '(' . $return . ')' if(@returns > 1);
65     $return = $negate_flag.$return if($return);
66     return $return;
67 }
68
69 sub quote_value {
70     my $self = shift;
71     my $value = shift;
72
73     if ($value =~ /^\d/) { # may have to use non-$ quoting
74         $value =~ s/'/''/g;
75         $value =~ s/\\/\\\\/g;
76         return "E'$value'";
77     }
78     return "\$_$$\$$value\$_$$\$";
79 }
80
81 sub quote_phrase_value {
82     my $self = shift;
83     my $value = shift;
84     my $wb = shift;
85
86     my $left_anchored = '';
87     my $right_anchored = '';
88     my $left_wb = 0;
89     my $right_wb = 0;
90
91     $left_anchored  = $1 if $value =~ m/^([*\^])/;
92     $right_anchored = $1 if $value =~ m/([*\$])$/;
93
94     # We can't use word-boundary bracket expressions if the relevant char
95     # is not actually a "word" characters.
96     $left_wb  = $wb if $value =~ m/^\w+/;
97     $right_wb = $wb if $value =~ m/\w+$/;
98
99     $value =~ s/^[*\^]//   if $left_anchored;
100     $value =~ s/[*\$]$//  if $right_anchored;
101     $value = quotemeta($value);
102     $value = '^' . $value if $left_anchored eq '^';
103     $value = "$value\$"   if $right_anchored eq '$';
104     $value = '[[:<:]]' . $value if $left_wb && !$left_anchored;
105     $value .= '[[:>:]]' if $right_wb && !$right_anchored;
106     return $self->quote_value($value);
107 }
108
109 sub init {
110     my $class = shift;
111 }
112
113 sub default_preferred_language {
114     my $self = shift;
115     my $lang = shift;
116
117     $self->custom_data->{default_preferred_language} = $lang if ($lang);
118     return $self->custom_data->{default_preferred_language};
119 }
120
121 sub default_preferred_language_multiplier {
122     my $self = shift;
123     my $lang = shift;
124
125     $self->custom_data->{default_preferred_language_multiplier} = $lang if ($lang);
126     return $self->custom_data->{default_preferred_language_multiplier};
127 }
128
129 sub max_popularity_importance_multiplier {
130     my $self = shift;
131     my $max = shift;
132
133     $self->custom_data->{max_popularity_importance_multiplier} = $max if defined($max);
134     return $self->custom_data->{max_popularity_importance_multiplier};
135 }
136
137 sub simple_plan {
138     my $self = shift;
139
140     return 0 unless $self->parse_tree;
141     return 0 if @{$self->parse_tree->filters};
142     return 0 if @{$self->parse_tree->modifiers};
143     for my $node ( @{ $self->parse_tree->query_nodes } ) {
144         return 0 if (!ref($node) && $node eq '|');
145         next unless (ref($node));
146         return 0 if ($node->isa('QueryParser::query_plan'));
147     }
148
149     return 1;
150 }
151
152 sub toSQL {
153     my $self = shift;
154     return $self->parse_tree->toSQL;
155 }
156
157 sub dynamic_filters {
158     my $self = shift;
159     my $new = shift;
160
161     $self->custom_data->{dynamic_filters} ||= [];
162     push(@{$self->custom_data->{dynamic_filters}}, $new) if ($new);
163     return $self->custom_data->{dynamic_filters};
164 }
165
166 sub dynamic_sorters {
167     my $self = shift;
168     my $new = shift;
169
170     $self->custom_data->{dynamic_sorters} ||= [];
171     push(@{$self->custom_data->{dynamic_sorters}}, $new) if ($new);
172     return $self->custom_data->{dynamic_sorters};
173 }
174
175 sub facet_field_id_map {
176     my $self = shift;
177     my $map = shift;
178
179     $self->custom_data->{facet_field_id_map} ||= {};
180     $self->custom_data->{facet_field_id_map} = $map if ($map);
181     return $self->custom_data->{facet_field_id_map};
182 }
183
184 sub add_facet_field_id_map {
185     my $self = shift;
186     my $class = shift;
187     my $field = shift;
188     my $id = shift;
189     my $weight = shift;
190
191     $self->add_facet_field( $class => $field );
192     $self->facet_field_id_map->{by_id}{$id} = { classname => $class, field => $field, weight => $weight };
193     $self->facet_field_id_map->{by_class}{$class}{$field} = $id;
194
195     return {
196         by_id => { $id => { classname => $class, field => $field, weight => $weight } },
197         by_class => { $class => { $field => $id } }
198     };
199 }
200
201 sub facet_field_class_by_id {
202     my $self = shift;
203     my $id = shift;
204
205     return $self->facet_field_id_map->{by_id}{$id};
206 }
207
208 sub facet_field_ids_by_class {
209     my $self = shift;
210     my $class = shift;
211     my $field = shift;
212
213     return undef unless ($class);
214
215     if ($field) {
216         return [$self->facet_field_id_map->{by_class}{$class}{$field}];
217     }
218
219     return [values( %{ $self->facet_field_id_map->{by_class}{$class} } )];
220 }
221
222 sub search_field_id_map {
223     my $self = shift;
224     my $map = shift;
225
226     $self->custom_data->{search_field_id_map} ||= {};
227     $self->custom_data->{search_field_id_map} = $map if ($map);
228     return $self->custom_data->{search_field_id_map};
229 }
230
231 sub add_search_field_id_map {
232     my $self = shift;
233     my $class = shift;
234     my $field = shift;
235     my $id = shift;
236     my $weight = shift;
237     my $combined = shift;
238
239     $self->add_search_field( $class => $field );
240     $self->search_field_id_map->{by_id}{$id} = { classname => $class, field => $field, weight => $weight };
241     $self->search_field_id_map->{by_class}{$class}{$field} = $id;
242
243     return {
244         by_id => { $id => { classname => $class, field => $field, weight => $weight } },
245         by_class => { $class => { $field => $id } }
246     };
247 }
248
249 sub search_field_class_by_id {
250     my $self = shift;
251     my $id = shift;
252
253     return $self->search_field_id_map->{by_id}{$id};
254 }
255
256 sub search_field_ids_by_class {
257     my $self = shift;
258     my $class = shift;
259     my $field = shift;
260
261     return undef unless ($class);
262
263     if ($field) {
264         return [$self->search_field_id_map->{by_class}{$class}{$field}];
265     }
266
267     return [values( %{ $self->search_field_id_map->{by_class}{$class} } )];
268 }
269
270 sub relevance_bumps {
271     my $self = shift;
272     my $bumps = shift;
273
274     $self->custom_data->{rel_bumps} ||= {};
275     $self->custom_data->{rel_bumps} = $bumps if ($bumps);
276     return $self->custom_data->{rel_bumps};
277 }
278
279 sub find_relevance_bumps {
280     my $self = shift;
281     my $class = shift;
282     my $field = shift;
283
284     return $self->relevance_bumps->{$class}{$field};
285 }
286
287 sub add_relevance_bump {
288     my $self = shift;
289     my $class = shift;
290     my $field = shift;
291     my $type = shift;
292     my $multiplier = shift;
293     my $active = shift;
294
295     if (defined($active) and $active eq 'f') {
296         $active = 0;
297     } else {
298         $active = 1;
299     }
300
301     $self->relevance_bumps->{$class}{$field}{$type} = { multiplier => $multiplier, active => $active };
302
303     return { $class => { $field => { $type => { multiplier => $multiplier, active => $active } } } };
304 }
305
306 sub search_class_weights {
307     my $self = shift;
308     my $class = shift;
309     my $a_weight = shift;
310     my $b_weight = shift;
311     my $c_weight = shift;
312     my $d_weight = shift;
313
314     $self->custom_data->{class_weights} ||= {};
315     # Note: This reverses the A-D order, putting D first, because that is how the call actually works in PG
316     $self->custom_data->{class_weights}->{$class} ||= [0.1, 0.2, 0.4, 1.0];
317     $self->custom_data->{class_weights}->{$class} = [$d_weight, $c_weight, $b_weight, $a_weight] if $a_weight;
318     return $self->custom_data->{class_weights}->{$class};
319 }
320
321 sub search_class_combined {
322     my $self = shift;
323     my $class = shift;
324     my $c = shift;
325
326     $self->custom_data->{class_combined} ||= {};
327     # Note: This reverses the A-D order, putting D first, because that is how the call actually works in PG
328     $self->custom_data->{class_combined}->{$class} ||= 0;
329     $self->custom_data->{class_combined}->{$class} = 1 if $c && $c =~ /^(?:t|y|1)/i;
330     return $self->custom_data->{class_combined}->{$class};
331 }
332
333 sub class_ts_config {
334     my $self = shift;
335     my $class = shift;
336     my $lang = shift || 'DEFAULT';
337     my $always = shift;
338     my $ts_config = shift;
339
340     $self->custom_data->{class_ts_config} ||= {};
341     $self->custom_data->{class_ts_config}->{$class} ||= {};
342     $self->custom_data->{class_ts_config}->{$class}->{$lang} ||= {};
343     $self->custom_data->{class_ts_config}->{$class}->{$lang}->{normal} ||= [];
344     $self->custom_data->{class_ts_config}->{$class}->{$lang}->{always} ||= [];
345     $self->custom_data->{class_ts_config}->{$class}->{'DEFAULT'} ||= {};
346     $self->custom_data->{class_ts_config}->{$class}->{'DEFAULT'}->{normal} ||= [];
347     $self->custom_data->{class_ts_config}->{$class}->{'DEFAULT'}->{always} ||= [];
348
349     if ($ts_config) {
350         push @{$self->custom_data->{class_ts_config}->{$class}->{$lang}->{normal}}, $ts_config unless $always;
351         push @{$self->custom_data->{class_ts_config}->{$class}->{$lang}->{always}}, $ts_config if $always;
352     }
353
354     my $return = [];
355     push @$return, @{$self->custom_data->{class_ts_config}->{$class}->{$lang}->{always}};
356     push @$return, @{$self->custom_data->{class_ts_config}->{$class}->{$lang}->{normal}} unless $always;
357     if($lang ne 'DEFAULT') {
358         push @$return, @{$self->custom_data->{class_ts_config}->{$class}->{'DEFAULT'}->{always}};
359         push @$return, @{$self->custom_data->{class_ts_config}->{$class}->{'DEFAULT'}->{normal}} unless $always;
360     }
361     return $return;
362 }
363
364 sub field_ts_config {
365     my $self = shift;
366     my $class = shift;
367     my $field = shift;
368     my $lang = shift || 'DEFAULT';
369     my $ts_config = shift;
370
371     $self->custom_data->{field_ts_config} ||= {};
372     $self->custom_data->{field_ts_config}->{$class} ||= {};
373     $self->custom_data->{field_ts_config}->{$class}->{$field} ||= {};
374     $self->custom_data->{field_ts_config}->{$class}->{$field}->{$lang} ||= [];
375     $self->custom_data->{field_ts_config}->{$class}->{$field}->{'DEFAULT'} ||= [];
376
377     if ($ts_config) {
378         push @{$self->custom_data->{field_ts_config}->{$class}->{$field}->{$lang}}, $ts_config;
379     }
380
381     my $return = [];
382     push @$return, @{$self->custom_data->{field_ts_config}->{$class}->{$field}->{$lang}};
383     if($lang ne 'DEFAULT') {
384         push @$return, @{$self->custom_data->{field_ts_config}->{$class}->{$field}->{'DEFAULT'}};
385     }
386     # Make it easy on us: Grab any "always" for the class here. If we have none we grab them all.
387     push @$return, @{$self->class_ts_config($class, $lang, scalar(@$return))};
388     return $return;
389 }
390
391 sub initialize_search_field_id_map {
392     my $self = shift;
393     my $cmf_list = shift;
394
395     for my $cmf (@$cmf_list) {
396         __PACKAGE__->add_search_field_id_map( $cmf->field_class, $cmf->name, $cmf->id, $cmf->weight ) if ($U->is_true($cmf->search_field));
397         __PACKAGE__->add_facet_field_id_map( $cmf->field_class, $cmf->name, $cmf->id, $cmf->weight ) if ($U->is_true($cmf->facet_field));
398     }
399
400     return $self->search_field_id_map;
401 }
402
403 sub initialize_aliases {
404     my $self = shift;
405     my $cmsa_list = shift;
406
407     for my $cmsa (@$cmsa_list) {
408         if (!$cmsa->field) {
409             __PACKAGE__->add_search_class_alias( $cmsa->field_class, $cmsa->alias );
410         } else {
411             my $c = $self->search_field_class_by_id( $cmsa->field );
412             __PACKAGE__->add_search_field_alias( $cmsa->field_class, $c->{field}, $cmsa->alias );
413         }
414     }
415 }
416
417 sub initialize_relevance_bumps {
418     my $self = shift;
419     my $sra_list = shift;
420
421     for my $sra (@$sra_list) {
422         my $c = $self->search_field_class_by_id( $sra->field );
423         __PACKAGE__->add_relevance_bump( $c->{classname}, $c->{field}, $sra->bump_type, $sra->multiplier, $sra->active );
424     }
425
426     return $self->relevance_bumps;
427 }
428
429 sub initialize_query_normalizers {
430     my $self = shift;
431     my $tree = shift; # open-ils.cstore.direct.config.metabib_field_index_norm_map.search.atomic { "id" : { "!=" : null } }, { "flesh" : 1, "flesh_fields" : { "cmfinm" : ["norm"] }, "order_by" : [{ "class" : "cmfinm", "field" : "pos" }] }
432
433     for my $cmfinm ( @$tree ) {
434         my $field_info = $self->search_field_class_by_id( $cmfinm->field );
435         next unless $field_info;
436         __PACKAGE__->add_query_normalizer( $field_info->{classname}, $field_info->{field}, $cmfinm->norm->func, OpenSRF::Utils::JSON->JSON2perl($cmfinm->params) );
437     }
438 }
439
440 sub initialize_dynamic_filters {
441     my $self = shift;
442     my $list = shift; # open-ils.cstore.direct.config.record_attr_definition.search.atomic { "id" : { "!=" : null } }
443
444     for my $crad ( @$list ) {
445         __PACKAGE__->dynamic_filters( __PACKAGE__->add_search_filter( $crad->name ) ) if ($U->is_true($crad->filter));
446         __PACKAGE__->dynamic_sorters( $crad->name ) if ($U->is_true($crad->sorter));
447     }
448 }
449
450 sub initialize_filter_normalizers {
451     my $self = shift;
452     my $tree = shift; # open-ils.cstore.direct.config.record_attr_index_norm_map.search.atomic { "id" : { "!=" : null } }, { "flesh" : 1, "flesh_fields" : { "crainm" : ["norm"] }, "order_by" : [{ "class" : "crainm", "field" : "pos" }] }
453
454     for my $crainm ( @$tree ) {
455         __PACKAGE__->add_filter_normalizer( $crainm->attr, $crainm->norm->func, OpenSRF::Utils::JSON->JSON2perl($crainm->params) );
456     }
457 }
458
459 sub initialize_search_class_weights {
460     my $self = shift;
461     my $classes = shift;
462
463     for my $search_class (@$classes) {
464         __PACKAGE__->search_class_weights( $search_class->name, $search_class->a_weight, $search_class->b_weight, $search_class->c_weight, $search_class->d_weight );
465         __PACKAGE__->search_class_combined( $search_class->name, $search_class->combined );
466     }
467 }
468
469 sub initialize_class_ts_config {
470     my $self = shift;
471     my $class_entries = shift;
472
473     for my $search_class_entry (@$class_entries) {
474         __PACKAGE__->class_ts_config($search_class_entry->field_class,$search_class_entry->search_lang,$U->is_true($search_class_entry->always),$search_class_entry->ts_config);
475     }
476 }
477
478 sub initialize_field_ts_config {
479     my $self = shift;
480     my $field_entries = shift;
481     my $field_objects = shift;
482     my %field_hash = map { $_->id => $_ } @$field_objects;
483
484     for my $search_field_entry (@$field_entries) {
485         my $field_object = $field_hash{$search_field_entry->metabib_field};
486         __PACKAGE__->field_ts_config($field_object->field_class,$field_object->name,$search_field_entry->search_lang,$search_field_entry->ts_config);
487     }
488 }
489
490 our $_complete = 0;
491 sub initialization_complete {
492     return $_complete;
493 }
494
495 sub initialize {
496     my $self = shift;
497     my %args = @_;
498
499     return $_complete if ($_complete);
500
501     # tsearch rank normalization adjustments. see http://www.postgresql.org/docs/9.0/interactive/textsearch-controls.html#TEXTSEARCH-RANKING for details
502     $self->custom_data->{rank_cd_weight_map} = {
503         CD_logDocumentLength    => 1,
504         CD_documentLength       => 2,
505         CD_meanHarmonic         => 4,
506         CD_uniqueWords          => 8,
507         CD_logUniqueWords       => 16,
508         CD_selfPlusOne          => 32
509     };
510
511     $self->add_search_modifier( $_ ) for (keys %{ $self->custom_data->{rank_cd_weight_map} });
512
513     $self->initialize_search_field_id_map( $args{config_metabib_field} )
514         if ($args{config_metabib_field});
515
516     $self->initialize_aliases( $args{config_metabib_search_alias} )
517         if ($args{config_metabib_search_alias});
518
519     $self->initialize_relevance_bumps( $args{search_relevance_adjustment} )
520         if ($args{search_relevance_adjustment});
521
522     $self->initialize_query_normalizers( $args{config_metabib_field_index_norm_map} )
523         if ($args{config_metabib_field_index_norm_map});
524
525     $self->initialize_dynamic_filters( $args{config_record_attr_definition} )
526         if ($args{config_record_attr_definition});
527
528     $self->initialize_filter_normalizers( $args{config_record_attr_index_norm_map} )
529         if ($args{config_record_attr_index_norm_map});
530
531     $self->initialize_search_class_weights( $args{config_metabib_class} )
532         if ($args{config_metabib_class});
533
534     $self->initialize_class_ts_config( $args{config_metabib_class_ts_map} )
535         if ($args{config_metabib_class_ts_map});
536
537     $self->initialize_field_ts_config( $args{config_metabib_field_ts_map}, $args{config_metabib_field} )
538         if ($args{config_metabib_field_ts_map} && $args{config_metabib_field});
539
540     $_complete = 1 if (
541         $args{config_metabib_field_index_norm_map} &&
542         $args{search_relevance_adjustment} &&
543         $args{config_metabib_search_alias} &&
544         $args{config_metabib_field} &&
545         $args{config_record_attr_definition}
546     );
547
548     return $_complete;
549 }
550
551 sub TEST_SETUP {
552     
553     __PACKAGE__->allow_nested_modifiers(1);
554
555     __PACKAGE__->add_search_field_id_map( series => seriestitle => 1 => 1 );
556
557     __PACKAGE__->add_search_field_id_map( series => seriestitle => 1 => 1 );
558     __PACKAGE__->add_relevance_bump( series => seriestitle => first_word => 1.5 );
559     __PACKAGE__->add_relevance_bump( series => seriestitle => full_match => 20 );
560     
561     __PACKAGE__->add_search_field_id_map( title => abbreviated => 2 => 1 );
562     __PACKAGE__->add_relevance_bump( title => abbreviated => first_word => 1.5 );
563     __PACKAGE__->add_relevance_bump( title => abbreviated => full_match => 20 );
564     
565     __PACKAGE__->add_search_field_id_map( title => translated => 3 => 1 );
566     __PACKAGE__->add_relevance_bump( title => translated => first_word => 1.5 );
567     __PACKAGE__->add_relevance_bump( title => translated => full_match => 20 );
568     
569     __PACKAGE__->add_search_field_id_map( title => proper => 6 => 1 );
570     __PACKAGE__->add_query_normalizer( title => proper => 'search_normalize' );
571     __PACKAGE__->add_relevance_bump( title => proper => first_word => 1.5 );
572     __PACKAGE__->add_relevance_bump( title => proper => full_match => 20 );
573     __PACKAGE__->add_relevance_bump( title => proper => word_order => 10 );
574     
575     __PACKAGE__->add_search_field_id_map( author => corporate => 7 => 1 );
576     __PACKAGE__->add_relevance_bump( author => corporate => first_word => 1.5 );
577     __PACKAGE__->add_relevance_bump( author => corporate => full_match => 20 );
578     
579     __PACKAGE__->add_facet_field_id_map( author => personal => 8 => 1 );
580
581     __PACKAGE__->add_search_field_id_map( author => personal => 8 => 1 );
582     __PACKAGE__->add_relevance_bump( author => personal => first_word => 1.5 );
583     __PACKAGE__->add_relevance_bump( author => personal => full_match => 20 );
584     __PACKAGE__->add_query_normalizer( author => personal => 'search_normalize' );
585     __PACKAGE__->add_query_normalizer( author => personal => 'split_date_range' );
586     
587     __PACKAGE__->add_facet_field_id_map( subject => topic => 14 => 1 );
588
589     __PACKAGE__->add_search_field_id_map( subject => topic => 14 => 1 );
590     __PACKAGE__->add_relevance_bump( subject => topic => first_word => 1 );
591     __PACKAGE__->add_relevance_bump( subject => topic => full_match => 1 );
592     
593     __PACKAGE__->add_search_field_id_map( subject => complete => 16 => 1 );
594     __PACKAGE__->add_relevance_bump( subject => complete => first_word => 1 );
595     __PACKAGE__->add_relevance_bump( subject => complete => full_match => 1 );
596     
597     __PACKAGE__->add_search_field_id_map( keyword => keyword => 15 => 1 );
598     __PACKAGE__->add_relevance_bump( keyword => keyword => first_word => 1 );
599     __PACKAGE__->add_relevance_bump( keyword => keyword => full_match => 1 );
600     
601     __PACKAGE__->class_ts_config( 'series', undef, 1, 'english_nostop' );
602     __PACKAGE__->class_ts_config( 'title', undef, 1, 'english_nostop' );
603     __PACKAGE__->class_ts_config( 'author', undef, 1, 'english_nostop' );
604     __PACKAGE__->class_ts_config( 'subject', undef, 1, 'english_nostop' );
605     __PACKAGE__->class_ts_config( 'keyword', undef, 1, 'english_nostop' );
606     __PACKAGE__->class_ts_config( 'series', undef, 1, 'simple' );
607     __PACKAGE__->class_ts_config( 'title', undef, 1, 'simple' );
608     __PACKAGE__->class_ts_config( 'author', undef, 1, 'simple' );
609     __PACKAGE__->class_ts_config( 'subject', undef, 1, 'simple' );
610     __PACKAGE__->class_ts_config( 'keyword', undef, 1, 'simple' );
611
612     # French! To test language limiters
613     __PACKAGE__->class_ts_config( 'series', 'fre', 1, 'french_nostop' );
614     __PACKAGE__->class_ts_config( 'title', 'fre', 1, 'french_nostop' );
615     __PACKAGE__->class_ts_config( 'author', 'fre', 1, 'french_nostop' );
616     __PACKAGE__->class_ts_config( 'subject', 'fre', 1, 'french_nostop' );
617     __PACKAGE__->class_ts_config( 'keyword', 'fre', 1, 'french_nostop' );
618
619     # Not a default config by any means, but good for some testing
620     __PACKAGE__->field_ts_config( 'author', 'personal', 'eng', 'english' );
621     __PACKAGE__->field_ts_config( 'author', 'personal', 'fre', 'french' );
622     
623     __PACKAGE__->add_search_class_alias( keyword => 'kw' );
624     __PACKAGE__->add_search_class_alias( title => 'ti' );
625     __PACKAGE__->add_search_class_alias( author => 'au' );
626     __PACKAGE__->add_search_class_alias( author => 'name' );
627     __PACKAGE__->add_search_class_alias( author => 'dc.contributor' );
628     __PACKAGE__->add_search_class_alias( subject => 'su' );
629     __PACKAGE__->add_search_class_alias( subject => 'bib.subject(?:Title|Place|Occupation)' );
630     __PACKAGE__->add_search_class_alias( series => 'se' );
631     __PACKAGE__->add_search_class_alias( keyword => 'dc.identifier' );
632     
633     __PACKAGE__->add_query_normalizer( author => corporate => 'search_normalize' );
634     __PACKAGE__->add_query_normalizer( keyword => keyword => 'search_normalize' );
635     
636     __PACKAGE__->add_search_field_alias( subject => name => 'bib.subjectName' );
637     
638 }
639
640 __PACKAGE__->default_search_class( 'keyword' );
641
642 # implements EG-specific stored subqueries
643 __PACKAGE__->add_search_filter( 'saved_query', sub { return __PACKAGE__->subquery_callback(@_) } );
644 __PACKAGE__->add_search_filter( 'filter_group_entry', sub { return __PACKAGE__->filter_group_entry_callback(@_) } );
645
646 # will be retained simply for back-compat
647 __PACKAGE__->add_search_filter( 'format', sub { return __PACKAGE__->format_callback(@_) } );
648
649 # grumble grumble, special cases against date1 and date2
650 __PACKAGE__->add_search_filter( 'before' );
651 __PACKAGE__->add_search_filter( 'after' );
652 __PACKAGE__->add_search_filter( 'between' );
653 __PACKAGE__->add_search_filter( 'during' );
654
655 # various filters for limiting in various ways
656 __PACKAGE__->add_search_filter( 'edit_date' );
657 __PACKAGE__->add_search_filter( 'create_date' );
658 __PACKAGE__->add_search_filter( 'statuses' );
659 __PACKAGE__->add_search_filter( 'locations' );
660 __PACKAGE__->add_search_filter( 'location_groups' );
661 __PACKAGE__->add_search_filter( 'bib_source' );
662 __PACKAGE__->add_search_filter( 'badge_orgs' );
663 __PACKAGE__->add_search_filter( 'badges' );
664 __PACKAGE__->add_search_filter( 'site' );
665 __PACKAGE__->add_search_filter( 'pref_ou' );
666 __PACKAGE__->add_search_filter( 'lasso' );
667 __PACKAGE__->add_search_filter( 'my_lasso' );
668 __PACKAGE__->add_search_filter( 'depth' );
669 __PACKAGE__->add_search_filter( 'language' );
670 __PACKAGE__->add_search_filter( 'offset' );
671 __PACKAGE__->add_search_filter( 'limit' );
672 __PACKAGE__->add_search_filter( 'check_limit' );
673 __PACKAGE__->add_search_filter( 'skip_check' );
674 __PACKAGE__->add_search_filter( 'superpage' );
675 __PACKAGE__->add_search_filter( 'superpage_size' );
676 __PACKAGE__->add_search_filter( 'estimation_strategy' );
677 __PACKAGE__->add_search_filter( 'from_metarecord' );
678 __PACKAGE__->add_search_modifier( 'available' );
679 __PACKAGE__->add_search_modifier( 'staff' );
680 __PACKAGE__->add_search_modifier( 'deleted' );
681 __PACKAGE__->add_search_modifier( 'lucky' );
682
683 # Start from container data (bre, acn, acp): container(bre,bookbag,123,deadb33fdeadb33fdeadb33fdeadb33f)
684 __PACKAGE__->add_search_filter( 'container' );
685
686 # Start from a list of record ids, either bre or metarecords, depending on the #metabib modifier
687 __PACKAGE__->add_search_filter( 'record_list' );
688
689 __PACKAGE__->add_search_filter( 'has_browse_entry' );
690
691 # copy_tag(copy_tag_code,copy_tag_search)
692 __PACKAGE__->add_search_filter( 'copy_tag' );
693
694 # used internally, but generally not user-settable
695 __PACKAGE__->add_search_filter( 'preferred_language' );
696 __PACKAGE__->add_search_filter( 'preferred_language_weight' );
697 __PACKAGE__->add_search_filter( 'preferred_language_multiplier' );
698 __PACKAGE__->add_search_filter( 'core_limit' );
699
700 # XXX Valid values to be supplied by SVF
701 __PACKAGE__->add_search_filter( 'sort' );
702
703 # modifies core query, not configurable
704 __PACKAGE__->add_search_modifier( 'descending' );
705 __PACKAGE__->add_search_modifier( 'ascending' );
706 __PACKAGE__->add_search_modifier( 'nullsfirst' );
707 __PACKAGE__->add_search_modifier( 'nullslast' );
708 __PACKAGE__->add_search_modifier( 'metarecord' );
709 __PACKAGE__->add_search_modifier( 'metabib' );
710
711
712 #-------------------------------
713 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan;
714 use base 'QueryParser::query_plan';
715 use OpenSRF::Utils::Logger qw($logger);
716 use OpenSRF::Utils qw/:datetime/;
717 use Data::Dumper;
718 use OpenILS::Application::AppUtils;
719 use OpenILS::Utils::Normalize qw/search_normalize/;
720 my $apputils = "OpenILS::Application::AppUtils";
721
722 our %_dfilter_controlled_cache = ();
723 our %_dfilter_stats_cache = ();
724 our $_pg_version = 0;
725
726 sub dynamic_filter_compile {
727     my ($self, $filter, $params, $negate) = @_;
728     my $e = OpenILS::Utils::CStoreEditor->new;
729
730     $negate = $negate ? '!' : '';
731
732     if (!$_pg_version) {
733         ($_pg_version = $e->json_query({from => ['version']})->[0]->{version}) =~ s/^.+?(\d\.\d).+$/$1/;
734     }
735
736     my $common = 0;
737     if ($_pg_version >= 9.2) {
738         if (!scalar keys %_dfilter_stats_cache) {
739             my $data = $e->json_query({from => ['evergreen.pg_statistics', 'record_attr_vector_list', 'vlist']});
740             %_dfilter_stats_cache = map {
741                 ( $_->{element}, $_->{frequency} )
742             } grep { $_->{frequency} > 5 } @$data; # Pin floor to 5% of the table
743         }
744     } else {
745         $common = 1; # Assume it's expensive
746     }
747
748     if (!exists($_dfilter_controlled_cache{$filter})) {
749         my $crad = $e->retrieve_config_record_attr_definition($filter);
750         my $ccvm_list = $e->search_config_coded_value_map({ctype =>$filter});
751
752         $_dfilter_controlled_cache{$filter} = $crad->to_bare_hash;
753         $_dfilter_controlled_cache{$filter}{controlled} = scalar @$ccvm_list;
754     }
755
756     my $method = $_dfilter_controlled_cache{$filter}{controlled} ?
757         'search_config_coded_value_map' : 'search_metabib_uncontrolled_record_attr_value';
758     my $attr_field = $_dfilter_controlled_cache{$filter}{controlled} ?
759         'ctype' : 'attr';
760     my $value_field = $_dfilter_controlled_cache{$filter}{controlled} ?
761         'code' : 'value';
762
763     my $attr_objects = $e->$method({ $attr_field => $filter, $value_field => $params });
764     $common = scalar(grep { exists($_dfilter_stats_cache{$_->id}) } @$attr_objects) unless $common;
765     
766     return (sprintf('%s(%s)', $negate,
767         join(
768             '|', 
769             map { $_->id } @$attr_objects
770         )
771     ), $common);
772 }
773
774 sub toSQL {
775     my $self = shift;
776
777     my %filters;
778
779     for my $f ( qw/preferred_language preferred_language_multiplier preferred_language_weight core_limit check_limit skip_check superpage superpage_size/ ) {
780         my $col = $f;
781         $col = 'preferred_language_multiplier' if ($f eq 'preferred_language_weight');
782         my ($filter) = $self->find_filter($f);
783         if ($filter and @{$filter->args}) {
784             $filters{$col} = $filter->args->[0];
785         }
786     }
787
788     $self->QueryParser->superpage($filters{superpage}) if ($filters{superpage});
789     $self->QueryParser->superpage_size($filters{superpage_size}) if ($filters{superpage_size});
790     $self->QueryParser->core_limit($filters{core_limit}) if ($filters{core_limit});
791
792     $logger->debug("Query plan:\n".Dumper($self));
793
794     my $flat_plan = $self->flatten;
795
796     # generate the relevance ranking
797     my $rel = '1'; # Default to something simple in case rank_list is empty.
798     if (@{$$flat_plan{rank_list}}) {
799         $rel = "AVG(\n"
800              . ${spc} x 5 ."("
801              . join(")\n" . ${spc} x 5 . "+ (", @{$$flat_plan{rank_list}})
802              . ")\n"
803              . ${spc} x 4 . ")+1";
804     }
805
806     # find any supplied sort option
807     my ($sort_filter) = $self->find_filter('sort');
808     if ($sort_filter) {
809         $sort_filter = $sort_filter->args->[0];
810     } else {
811         $sort_filter = 'rel';
812     }
813
814     my $lang_join = '';
815     if (($filters{preferred_language} || $self->QueryParser->default_preferred_language) && ($filters{preferred_language_multiplier} || $self->QueryParser->default_preferred_language_multiplier)) {
816     
817         my $pl = $self->QueryParser->quote_value( $filters{preferred_language} ? $filters{preferred_language} : $self->QueryParser->default_preferred_language );
818         $$flat_plan{with} .= ',' if $$flat_plan{with};
819         $$flat_plan{with} .= "lang_with AS (SELECT id FROM config.coded_value_map WHERE ctype = 'item_lang' AND code = $pl)";
820         $lang_join = ",lang_with";
821
822         my $plw = $filters{preferred_language_multiplier} ? $filters{preferred_language_multiplier} : $self->QueryParser->default_preferred_language_multiplier;
823         $rel = "($rel * COALESCE( NULLIF( FIRST(mrv.vlist \@> ARRAY[lang_with.id]), FALSE )::INT * $plw, 1))";
824         $$flat_plan{uses_mrv} = 1;
825     }
826
827     my $mrv_join = '';
828     if ($$flat_plan{uses_mrv}) {
829         $mrv_join = 'INNER JOIN metabib.record_attr_vector_list mrv ON m.source = mrv.source';
830     }
831
832     my $mra_join = '';
833     if ($$flat_plan{uses_mrd}) {
834         $mra_join = 'INNER JOIN metabib.record_attr mrd ON m.source = mrd.id';
835     }
836
837     my $pubdate_join = "LEFT JOIN metabib.record_sorter pubdate_t ON m.source = pubdate_t.source AND attr = 'pubdate'";
838
839     my $bre_join = '';
840     if ($self->find_modifier('deleted')) {
841         $bre_join = 'INNER JOIN biblio.record_entry bre ON m.source = bre.id AND bre.deleted';
842         # The above suffices for filters too when the #deleted modifier
843         # is in use.
844     } elsif ($$flat_plan{uses_bre}) {
845         $bre_join = 'INNER JOIN biblio.record_entry bre ON m.source = bre.id';
846     }
847     
848     my $desc = 'ASC';
849     $desc = 'DESC' if ($self->find_modifier('descending'));
850
851     my $nullpos = 'NULLS LAST';
852     $nullpos = 'NULLS FIRST' if ($self->find_modifier('nullsfirst'));
853
854     # Do we have a badges() filter?
855     my $badges = '';
856     my ($badge_filter) = $self->find_filter('badges');
857     if ($badge_filter && @{$badge_filter->args}) {
858         $badges = join (',', grep /^\d+$/, @{$badge_filter->args});
859     }
860
861     # Do we have a badge_orgs() filter? (used for calculating popularity)
862     my $borgs = '';
863     my ($bo_filter) = $self->find_filter('badge_orgs');
864     if ($bo_filter && @{$bo_filter->args}) {
865         $borgs = join (',', grep /^\d+$/, @{$bo_filter->args});
866     }
867
868     # Build the badge-ish WITH query
869     my $pop_with = <<'    WITH';
870         pop_with AS (
871             SELECT  record,
872                     ARRAY_AGG(badge) AS badges,
873                     SUM(s.score::NUMERIC*b.weight::NUMERIC)/SUM(b.weight::NUMERIC) AS total_score
874               FROM  rating.record_badge_score s
875                     JOIN rating.badge b ON (
876                         b.id = s.badge
877     WITH
878
879     $pop_with .= " AND b.id = ANY ('{$badges}')" if ($badges);
880     $pop_with .= " AND b.scope = ANY ('{$borgs}')" if ($borgs);
881     $pop_with .= ') GROUP BY 1)'; 
882
883     my $pop_join = $badges ? # inner join if we are restricting via badges()
884         'INNER JOIN pop_with ON ( m.source = pop_with.record )' : 
885         'LEFT JOIN pop_with ON ( m.source = pop_with.record )';
886
887     $$flat_plan{with} .= ',' if $$flat_plan{with};
888     $$flat_plan{with} .= $pop_with;
889
890
891     my $rank;
892     my $pop_extra_sort = '';
893     if (grep {$_ eq $sort_filter} @{$self->QueryParser->dynamic_sorters}) {
894         $rank = "FIRST((SELECT value FROM metabib.record_sorter rbr WHERE rbr.source = m.source and attr = '$sort_filter'))"
895     } elsif ($sort_filter eq 'create_date') {
896         $rank = "FIRST((SELECT create_date FROM biblio.record_entry rbr WHERE rbr.id = m.source))";
897     } elsif ($sort_filter eq 'edit_date') {
898         $rank = "FIRST((SELECT edit_date FROM biblio.record_entry rbr WHERE rbr.id = m.source))";
899     } elsif ($sort_filter eq 'poprel') {
900         my $max_mult = $self->QueryParser->max_popularity_importance_multiplier() // 2.0;
901         $max_mult = 0.1 if $max_mult < 0.1; # keep it within reasonable bounds,
902                                             # and avoid the division-by-zero error
903                                             # you'd get if you allowed it to be
904                                             # zero
905
906         if ( $max_mult == 1.0 ) { # no adjustment requested by the configuration
907             $rank = "1.0/($rel)::NUMERIC";
908         } else { # calculate adjustment
909
910             # Scale the 0-5 effect of popularity badges by providing a multiplier
911             # for the badge average based on the overall maximum
912             # multiplier.  Two examples, comparing the effect to the default
913             # $max_mult value of 2.0, which causes a $adjusted_scale value
914             # of 0.2:
915             #
916             #  * Given the default $max_mult of 2.0, the value of
917             #    $adjusted_scale will be 0.2 [($max_mult - 1.0) / 5.0].
918             #    For a record whose average badge score is the maximum
919             #    of 5.0, that would make the relevance multiplier be
920             #    2.0:
921             #       1.0 + (5.0 [average score] * 0.2 [ $adjusted_scale ],
922             #    This would have the effect of doubling the effective
923             #    relevance of highly popular items.
924             #
925             #  * Given a $max_mult of 1.1, the value of $adjusted_scale
926             #    will be 0.02, meaning that the average badge value will be
927             #    multiplied by 0.02 rather than 0.2, then added to 1.0 and
928             #    used as a multiplier against the base relevance.  Thus a
929             #    change of at most 10% to the base relevance for a record
930             #    with a 5.0 average badge score. This will allow records
931             #    that are naturally very relevant to avoid being pushed
932             #    below badge-heavy records.
933             #
934             #  * Given a $max_mult of 3.0, the value of $adjusted_scale
935             #    will be 0.4, meaning that the average badge value will be
936             #    multiplied by 0.4 rather than 0.2, then added to 1.0 and
937             #    used as a multiplier against the base relevance. Thus a
938             #    change of as much as 200% to (or three times the size of)
939             #    the base relevance for a record with a 5.0 average badge
940             #    score.  This in turn will cause badges to outweigh
941             #    relevance to a very large degree.
942             #
943             # The maximum badge multiplier can be set to a value less than
944             # 1.0; this would have the effect of making less popular items
945             # show up higher in the results.  While this is not a likely
946             # option for production use, it could be useful for identifying
947             # interesting long-tail hits, particularly in a database
948             # where enough badges are configured so that very few records
949             # have an overage badge score of zero.
950
951             my $adjusted_scale = ( $max_mult - 1.0 ) / 5.0;
952             $rank = "1.0/(( $rel ) * (1.0 + (AVG(COALESCE(pop_with.total_score::NUMERIC,0.0::NUMERIC)) * ${adjusted_scale}::NUMERIC)))::NUMERIC";
953         }
954     } elsif ($sort_filter =~ /^pop/) {
955         $rank = '1.0/(AVG(COALESCE(pop_with.total_score::NUMERIC,0.0::NUMERIC)) + 5.0::NUMERIC)::NUMERIC';
956         my $pop_desc = $desc eq 'ASC' ? 'DESC' : 'ASC';
957         $pop_extra_sort = "3 $pop_desc $nullpos,";
958     } else {
959         # default to rel ranking
960         $rank = "1.0/($rel)::NUMERIC";
961     }
962
963     my $key = 'm.source';
964     $key = 'm.metarecord' if (grep {$_->name eq 'metarecord' or $_->name eq 'metabib'} @{$self->modifiers});
965
966     my $core_limit = $self->QueryParser->core_limit || 25000;
967     $core_limit = 1 if($self->find_modifier('lucky'));
968
969     my $flat_where = $$flat_plan{where};
970     if ($flat_where ne '') {
971         $flat_where = "AND (\n" . ${spc} x 5 . $flat_where . "\n" . ${spc} x 4 . ")";
972     }
973     my $with = $$flat_plan{with};
974     $with= "\nWITH $with" if $with;
975
976     # Need an array for query parser db function; this gives a better plan
977     # than the ARRAY_AGG(DISTINCT m.source) option as of PostgreSQL 9.1
978     my $agg_records = 'ARRAY[m.source] AS records';
979     if ($key =~ /metarecord/) {
980         # metarecord searches still require the ARRAY_AGG approach
981         $agg_records = 'ARRAY_AGG(DISTINCT m.source) AS records';
982     }
983
984     my $sql = <<SQL;
985 $with
986 SELECT  $key AS id,
987         $agg_records,
988         (${rel})::NUMERIC AS rel,
989         $rank AS rank, 
990         FIRST(pubdate_t.value) AS tie_break,
991         STRING_AGG(ARRAY_TO_STRING(pop_with.badges,','),',') AS badges,
992         AVG(COALESCE(pop_with.total_score::NUMERIC,0.0::NUMERIC))::NUMERIC(2,1) AS popularity
993   FROM  metabib.metarecord_source_map m
994         $$flat_plan{from}
995         $mra_join
996         $mrv_join
997         $bre_join
998         $pop_join
999         $pubdate_join
1000         $lang_join
1001   WHERE 1=1
1002         $flat_where
1003   GROUP BY 1
1004   ORDER BY 4 $desc $nullpos, $pop_extra_sort 5 DESC $nullpos, 3 DESC
1005   LIMIT $core_limit
1006 SQL
1007
1008     warn $sql if $self->QueryParser->debug;
1009     return $sql;
1010
1011 }
1012
1013 sub flatten {
1014     my $self = shift;
1015
1016     die 'ERROR: nesting too deep or boolean list too long' if ($self->plan_level > 40);
1017
1018     my $from = shift || '';
1019     my $where = shift || '';
1020     my $with = '';
1021     my $uses_bre = 0;
1022     my $uses_mrd = 0;
1023     my $uses_mrv = 0;
1024
1025     my @rank_list;
1026     for my $node ( @{$self->query_nodes} ) {
1027
1028         if (ref($node)) {
1029             if ($node->isa( 'QueryParser::query_plan::node' )) {
1030
1031                 unless (@{$node->only_atoms}) {
1032                     push @rank_list, '1';
1033                     $where .= 'TRUE';
1034                     next;
1035                 }
1036
1037                 my $table = $node->table;
1038                 my $ctable = $node->combined_table;
1039                 my $talias = $node->table_alias;
1040
1041                 my $node_rank = 'COALESCE(' . $node->rank . " * ${talias}.weight, 0.0)";
1042
1043                 $from .= "\n" . ${spc} x 4 ."LEFT JOIN (\n"
1044                       . ${spc} x 5 . "SELECT fe.*, fe_weight.weight, ${talias}_xq.tsq, ${talias}_xq.tsq_rank /* search */\n"
1045                       . ${spc} x 6 . "FROM  $table AS fe";
1046                 $from .= "\n" . ${spc} x 7 . "JOIN config.metabib_field AS fe_weight ON (fe_weight.id = fe.field)";
1047
1048                 my @bump_fields;
1049                 my @field_ids;
1050                 if (@{$node->fields} > 0) {
1051                     @bump_fields = @{$node->fields};
1052
1053                     @field_ids = grep defined, (
1054                         map {
1055                             $self->QueryParser->search_field_ids_by_class(
1056                                 $node->classname, $_
1057                             )->[0]
1058                         } @bump_fields
1059                     );
1060                 } else {
1061                     @bump_fields = @{$self->QueryParser->search_fields->{$node->classname}};
1062                 }
1063
1064                 if ($node->dummy_count < @{$node->only_atoms} ) {
1065                     $with .= ",\n     " if $with;
1066                     $with .= "${talias}_xq AS (SELECT ". $node->tsquery ." AS tsq,". $node->tsquery_rank ." AS tsq_rank )";
1067                     if ($node->combined_search) {
1068                         $from .= "\n" . ${spc} x 6 . "JOIN $ctable AS com ON (com.record = fe.source";
1069                         if (@field_ids) {
1070                             $from .= " AND com.metabib_field IN (" . join(',',@field_ids) . "))";
1071                         } else {
1072                             $from .= " AND com.metabib_field IS NULL)";
1073                         }
1074                         $from .= "\n" . ${spc} x 6 . "JOIN ${talias}_xq ON (com.index_vector @@ ${talias}_xq.tsq)";
1075                     } else {
1076                         $from .= "\n" . ${spc} x 6 . "JOIN ${talias}_xq ON (fe.index_vector @@ ${talias}_xq.tsq)";
1077                     }
1078                 } else {
1079                     $from .= "\n" . ${spc} x 6 . ", (SELECT NULL::tsquery AS tsq, NULL:tsquery AS tsq_rank ) AS ${talias}_xq";
1080                 }
1081
1082                 if (@field_ids) {
1083                     $from .= "\n" . ${spc} x 6 . "WHERE fe_weight.id IN  (" .
1084                         join(',', @field_ids) . ")";
1085                 }
1086
1087                 $from .= "\n" . ${spc} x 4 . ") AS $talias ON (m.source = ${talias}.source)";
1088
1089                 my %used_bumps;
1090                 my @bumps;
1091                 my @bumpmults;
1092                 for my $field ( @bump_fields ) {
1093                     my $bumps = $self->QueryParser->find_relevance_bumps( $node->classname => $field );
1094                     for my $b (keys %$bumps) {
1095                         next if (!$$bumps{$b}{active});
1096                         next if ($used_bumps{$b});
1097                         $used_bumps{$b} = 1;
1098
1099                         next if ($$bumps{$b}{multiplier} == 1); # optimization to remove unneeded bumps
1100                         push @bumps, $b;
1101                         push @bumpmults, $$bumps{$b}{multiplier};
1102                     }
1103                 }
1104
1105                 if(scalar @bumps > 0 && scalar @{$node->only_positive_atoms} > 0) {
1106                     # Note: Previous rank function used search_normalize outright. Duplicating that here.
1107                     $node_rank .= "\n" . ${spc} x 5 . "* evergreen.rel_bump(('{' || quote_literal(search_normalize(";
1108                     $node_rank .= join(")) || ',' || quote_literal(search_normalize(",map { $self->QueryParser->quote_phrase_value($_->content) } @{$node->only_positive_atoms});
1109                     $node_rank .= ")) || '}')::TEXT[], " . $node->table_alias . ".value, '{" . join(",",@bumps) . "}'::TEXT[], '{" . join(",",@bumpmults) . "}'::NUMERIC[])";
1110                 }
1111
1112                 my $NOT = '';
1113                 $NOT = 'NOT ' if $node->negate;
1114
1115                 $where .= "$NOT(" . $talias . ".id IS NOT NULL";
1116                 if (@{$node->phrases}) {
1117                     $where .= ' AND ' . join(' AND ', map {
1118                         "${talias}.value ~* ".$self->QueryParser->quote_phrase_value($_, 1)
1119                     } @{$node->phrases});
1120                 } else {
1121                     for my $atom (@{$node->only_real_atoms}) {
1122                         next unless $atom->{content} && $atom->{content} =~ /(^\^|\$$)/;
1123                         $where .= " AND ${talias}.value ~* ".$self->QueryParser->quote_phrase_value($atom->{content});
1124                     }
1125                 }
1126                 $where .= ')';
1127
1128                 push @rank_list, $node_rank;
1129
1130             } elsif ($node->isa( 'QueryParser::query_plan::facet' )) {
1131
1132                 my $talias = $node->table_alias;
1133
1134                 my @field_ids;
1135                 if (@{$node->fields} > 0) {
1136                     push(@field_ids, $self->QueryParser->facet_field_ids_by_class( $node->classname, $_ )->[0]) for (@{$node->fields});
1137                 } else {
1138                     @field_ids = @{ $self->QueryParser->facet_field_ids_by_class( $node->classname ) };
1139                 }
1140
1141                 my $join_type = ($node->negate or !$self->top_plan) ? 'LEFT' : 'INNER';
1142                 $from .= "\n${spc}$join_type JOIN /* facet */ metabib.facet_entry $talias ON (\n"
1143                       . ${spc} x 2 . "m.source = ${talias}.source\n"
1144                       . ${spc} x 2 . "AND SUBSTRING(${talias}.value,1,1024) IN ("
1145                       . join(",", map { $self->QueryParser->quote_value($_) } @{$node->values}) . ")\n"
1146                       . ${spc} x 2 ."AND ${talias}.field IN (". join(',', @field_ids) . ")\n"
1147                       . "${spc})";
1148
1149                 if ($join_type ne 'INNER') {
1150                     my $NOT = $node->negate ? '' : ' NOT';
1151                     $where .= "${talias}.id IS$NOT NULL";
1152                 } elsif ($where ne '') {
1153                     # Strip extra joiner
1154                     $where =~ s/(\s|\n)+(AND|OR)\s$//;
1155                 }
1156
1157             } else {
1158                 my $subnode = $node->flatten;
1159
1160                 # strip the trailing bool from the previous loop if there is 
1161                 # nothing to add to the where within this loop.
1162                 if ($$subnode{where} eq '') {
1163                     $where =~ s/(\s|\n)+(AND|OR)\s$//;
1164                 }
1165
1166                 push(@rank_list, @{$$subnode{rank_list}});
1167                 $from .= $$subnode{from};
1168
1169                 my $NOT = '';
1170                 $NOT = 'NOT ' if $node->negate;
1171
1172                 if ($$subnode{where} ne '') {
1173                     $where .= "$NOT(\n"
1174                            . ${spc} x ($self->plan_level + 6) . $$subnode{where} . "\n"
1175                            . ${spc} x ($self->plan_level + 5) . ')';
1176                 }
1177
1178                 if ($$subnode{with}) {
1179                     $with .= ",\n     " if $with;
1180                     $with .= $$subnode{with};
1181                 }
1182
1183                 $uses_bre = $$subnode{uses_bre};
1184                 $uses_mrd = $$subnode{uses_mrd};
1185                 $uses_mrv = $$subnode{uses_mrv};
1186             }
1187         } else {
1188
1189             warn "flatten(): appending WHERE bool to: $where\n" if $self->QueryParser->debug;
1190
1191             if ($where ne '') {
1192                 $where .= "\n" . ${spc} x ( $self->plan_level + 5 ) . 'AND ' if ($node eq '&');
1193                 $where .= "\n" . ${spc} x ( $self->plan_level + 5 ) . 'OR ' if ($node eq '|');
1194             }
1195         }
1196     }
1197
1198     my $joiner = "\n" . ${spc} x ( $self->plan_level + 5 ) . ($self->joiner eq '&' ? 'AND ' : 'OR ');
1199
1200     my @dlist = ();
1201     my $common = 0;
1202     # for each dynamic filter, build more of the WHERE clause
1203     for my $filter (@{$self->filters}) {
1204         my $NOT = $filter->negate ? 'NOT ' : '';
1205         if (grep { $_ eq $filter->name } @{ $self->QueryParser->dynamic_filters }) {
1206
1207             my $fname = $filter->name;
1208             $fname = 'item_lang' if $fname eq 'language'; #XXX filter aliases 
1209
1210             warn "flatten(): processing dynamic filter ". $filter->name ."\n"
1211                 if $self->QueryParser->debug;
1212
1213             my $vlist_query;
1214             ($vlist_query, $common) = $self->dynamic_filter_compile( $fname, $filter->args, $filter->negate );
1215
1216             # bool joiner for intra-plan nodes/filters
1217             push(@dlist, $self->joiner) if @dlist;
1218             push(@dlist, $vlist_query);
1219             $uses_mrv = 1;
1220         } else {
1221             if ($filter->name eq 'before') {
1222                 if (@{$filter->args} == 1) {
1223                     $where .= $joiner if $where ne '';
1224                     $where .= "${NOT}COALESCE(pubdate_t.value <= "
1225                            . $self->QueryParser->quote_value($filter->args->[0])
1226                            . ", false)";
1227                 }
1228             } elsif ($filter->name eq 'after') {
1229                 if (@{$filter->args} == 1) {
1230                     $where .= $joiner if $where ne '';
1231                     $where .= "${NOT}COALESCE(pubdate_t.value >= "
1232                            . $self->QueryParser->quote_value($filter->args->[0])
1233                            . ", false)";
1234                 }
1235             } elsif ($filter->name eq 'during') {
1236                 if (@{$filter->args} == 1) {
1237                     $where .= $joiner if $where ne '';
1238                     $where .= "${NOT}COALESCE("
1239                            . $self->QueryParser->quote_value($filter->args->[0])
1240                            . " BETWEEN pubdate_t.value AND (mrd.attrs->'date2'), false)";
1241                     $uses_mrd = 1;
1242                 }
1243             } elsif ($filter->name eq 'between') {
1244                 if (@{$filter->args} == 2) {
1245                     $where .= $joiner if $where ne '';
1246                     $where .= "${NOT}COALESCE(pubdate_t.value BETWEEN "
1247                            . $self->QueryParser->quote_value($filter->args->[0])
1248                            . " AND "
1249                            . $self->QueryParser->quote_value($filter->args->[1])
1250                            . ", false)";
1251                 }
1252             } elsif ($filter->name eq 'container') {
1253                 if (@{$filter->args} >= 3) {
1254                     my ($class, $ctype, $cid, $token) = @{$filter->args};
1255                     my $perm_join = '';
1256                     my $rec_join = '';
1257                     my $rec_field = 'ci.target_biblio_record_entry';
1258                     if ($class eq 'bre') {
1259                         $class = 'biblio_record_entry';
1260                     } elsif ($class eq 'acn') {
1261                         $class = 'call_number';
1262                         $rec_field = 'cn.record';
1263                         $rec_join = 'JOIN asset.call_number cn ON (ci.target_call_number = cn.id)';
1264                     } elsif ($class eq 'acp') {
1265                         $class = 'copy';
1266                         $rec_field = 'cn.record';
1267                         $rec_join = 'JOIN asset.copy cp ON (ci.target_copy = cp.id) JOIN asset.call_number cn ON (cp.call_number = cn.id)';
1268                     } else {
1269                         $class = undef;
1270                     }
1271
1272                     if ($class) {
1273                         my ($u,$e) = $apputils->checksesperm($token) if ($token);
1274                         $perm_join = ' OR c.owner = ' . $u->id if ($u && !$e);
1275
1276                         my $filter_alias = "$filter";
1277                         $filter_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1278                         $filter_alias =~ s/\|/_/go;
1279
1280                         $with .= ",\n     " if $with;
1281                         $with .= "container_${filter_alias} AS (\n";
1282                         $with .= "       SELECT $rec_field AS record FROM container.${class}_bucket_item ci\n"
1283                                . "             JOIN container.${class}_bucket c ON (c.id = ci.bucket) $rec_join\n"
1284                                . "       WHERE c.btype = " . $self->QueryParser->quote_value($ctype) . "\n"
1285                                . "             AND c.id = " . $self->QueryParser->quote_value($cid) . "\n"
1286                                . "             AND (c.pub IS TRUE$perm_join)\n";
1287                         if ($class eq 'copy') {
1288                             $with .= "       UNION\n"
1289                                    . "       SELECT pr.peer_record AS record FROM container.copy_bucket_item ci\n"
1290                                    . "             JOIN container.copy_bucket c ON (c.id = ci.bucket)\n"
1291                                    . "             JOIN biblio.peer_bib_copy_map pr ON ci.target_copy = pr.target_copy\n"
1292                                    . "       WHERE c.btype = " . $self->QueryParser->quote_value($ctype) . "\n"
1293                                    . "             AND c.id = " . $self->QueryParser->quote_value($cid) . "\n"
1294                                    . "             AND (c.pub IS TRUE$perm_join)\n";
1295                         }
1296                         $with .= "     )";
1297
1298                         my $optimize_join = 1 if $self->top_plan and !$NOT;
1299                         $from .= "\n" . ${spc} x 3 . ( $optimize_join ? 'INNER' : 'LEFT') . " JOIN container_${filter_alias} ON container_${filter_alias}.record = m.source";
1300
1301                         if (!$optimize_join) {
1302                             $where .= $joiner if $where ne '';
1303                             $where .= "(container_${filter_alias} IS " . ( $NOT ? 'NULL)' : 'NOT NULL)');
1304                         }
1305                     }
1306                 }
1307             } elsif ($filter->name eq 'copy_tag') {
1308                 my $valid_copy_tag_search = 0;
1309                 my $copy_tag_type;
1310                 my $tag_value;
1311                 if (@{$filter->args} >= 2) { # must have at least two parts, tag (or *) and terms
1312                     my @fargs = @{$filter->args};
1313                     $copy_tag_type = shift(@fargs);
1314                     $tag_value = join(' ', @fargs);
1315                     $valid_copy_tag_search = 1;
1316                 }
1317                 if ($valid_copy_tag_search) {
1318                     my $norm_value = search_normalize($tag_value);
1319                     my @tokens = split /\s+/, $norm_value;
1320                     
1321                     my $filter_alias = "$filter";
1322                     $filter_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1323                     $filter_alias =~ s/\|/_/go;
1324
1325                     $with .= ",\n     " if $with;
1326                     $with .= "copy_tag_${filter_alias} AS (\n";
1327                     $with .= "       SELECT cn.record AS record FROM config.copy_tag_type cctt\n";
1328                     $with .= "             JOIN asset.copy_tag acpt ON (cctt.code = acpt.tag_type)\n";
1329                     $with .= "             JOIN asset.copy_tag_copy_map acptcm ON (acpt.id = acptcm.tag)\n";
1330                     $with .= "             JOIN asset.copy cp ON (acptcm.copy = cp.id)\n";
1331                     $with .= "             JOIN asset.call_number cn ON (cp.call_number = cn.id)\n";
1332                     $with .= "       WHERE 1 = 1 \n";
1333                     if ($copy_tag_type ne '*') {
1334                         $with .= "             AND cctt.code = " . $self->QueryParser->quote_value($copy_tag_type) . "\n";
1335                     }
1336                     if (@tokens) {
1337                         $with .= '             AND acpt.value @@ to_tsquery(' . $self->QueryParser->quote_value(join(' & ', @tokens)) . ")\n";
1338                     }
1339                     if (!$self->find_modifier('staff')) {
1340                         $with .= "             AND acpt.pub IS TRUE\n";
1341                     }
1342                     $with .= "     )";
1343
1344                     my $optimize_join = 1 if $self->top_plan and !$NOT;
1345                     $from .= "\n" . ${spc} x 3 . ( $optimize_join ? 'INNER' : 'LEFT') . " JOIN copy_tag_${filter_alias} ON copy_tag_${filter_alias}.record = m.source";
1346
1347                     if (!$optimize_join) {
1348                         $where .= $joiner if $where ne '';
1349                         $where .= "(copy_tag_${filter_alias} IS " . ( $NOT ? 'NULL)' : 'NOT NULL)');
1350                     }
1351                 }
1352             } elsif ($filter->name eq 'record_list') {
1353                 if (@{$filter->args} > 0) {
1354                     my $key = 'm.source';
1355                     $key = 'm.metarecord' if (grep {$_->name eq 'metarecord' or $_->name eq 'metabib'} @{$self->QueryParser->parse_tree->modifiers});
1356                     $where .= $joiner if $where ne '';
1357                     $where .= "$key ${NOT}IN (" . join(',', map { $self->QueryParser->quote_value($_) } @{$filter->args}) . ')';
1358                 }
1359
1360             } elsif ($filter->name eq 'has_browse_entry') {
1361                 if (@{$filter->args} >= 2) {
1362                     my $entry = int(shift @{$filter->args});
1363                     my $fields = join(",", map(int, @{$filter->args}));
1364                     $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);
1365                 }
1366             } elsif ($filter->name eq 'edit_date' or $filter->name eq 'create_date') {
1367                 # bre.create_date and bre.edit_date filtering
1368                 my $datefilter = $filter->name;
1369
1370                 $uses_bre = 1;
1371
1372                 if ($filter && $filter->args && scalar(@{$filter->args}) > 0 && scalar(@{$filter->args}) < 3) {
1373                     my ($cstart, $cend) = @{$filter->args};
1374         
1375                     if (!$cstart and !$cend) {
1376                         # useless use of filter
1377                     } elsif (!$cstart or $cstart eq '-infinity') { # no start supplied
1378                         if ($cend eq 'infinity') {
1379                             # useless use of filter
1380                         } else {
1381                             # "before $cend"
1382                             $cend = cleanse_ISO8601($cend);
1383                             $where .= $joiner if $where ne '';
1384                             $where .= "bre.$datefilter <= \$_$$\$$cend\$_$$\$";
1385                         }
1386             
1387                     } elsif (!$cend or $cend eq 'infinity') { # no end supplied
1388                         if ($cstart eq '-infinity') {
1389                             # useless use of filter
1390                         } else { # "after $cstart"
1391                             $cstart = cleanse_ISO8601($cstart);
1392                             $where .= $joiner if $where ne '';
1393                             $where .= "bre.$datefilter >= \$_$$\$$cstart\$_$$\$";
1394                         }
1395                     } else { # both supplied
1396                         # "between $cstart and $cend"
1397                         $cstart = cleanse_ISO8601($cstart);
1398                         $cend = cleanse_ISO8601($cend);
1399                         $where .= $joiner if $where ne '';
1400                         $where .= "bre.$datefilter BETWEEN \$_$$\$$cstart\$_$$\$ AND \$_$$\$$cend\$_$$\$";
1401                     }
1402                 }
1403             } elsif ($filter->name eq 'bib_source') {
1404                 $uses_bre = 1;
1405
1406                 if (@{$filter->args} > 0) {
1407                     $where .= $joiner if $where ne '';
1408                     $where .= "${NOT}COALESCE(bre.source IN ("
1409                            . join(',', map { $self->QueryParser->quote_value($_) } @{ $filter->args })
1410                            . "), false)";
1411                 }
1412             } elsif ($filter->name eq 'from_metarecord') {
1413                 if (@{$filter->args} > 0) {
1414                     my $key = 'm.metarecord';
1415                     $where .= $joiner if $where ne '';
1416                     $where .= "$key ${NOT}IN (" . join(',', map { $self->QueryParser->quote_value($_) } @{$filter->args}) . ')';
1417                 }
1418             }
1419         }
1420     }
1421
1422     if (@dlist) {
1423
1424         $where .= $joiner if $where ne '';
1425         if ($common) { # Use a function wrapper to inform PG of the non-rareness of one or more filter elements
1426             $where .= sprintf(
1427                 'evergreen.query_int_wrapper(mrv.vlist, \'%s\')',
1428                 join('', @dlist)
1429             );
1430         } else {
1431             $where .= sprintf(
1432                 'mrv.vlist @@ \'%s\'',
1433                 join('', @dlist)
1434             );
1435         }
1436     }
1437
1438     warn "flatten(): full filter where => $where\n" if $self->QueryParser->debug;
1439
1440     return {
1441         rank_list => \@rank_list,
1442         from => $from,
1443         where => $where,
1444         with => $with,
1445         uses_bre => $uses_bre,
1446         uses_mrv => $uses_mrv,
1447         uses_mrd => $uses_mrd
1448     };
1449 }
1450
1451
1452 #-------------------------------
1453 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::filter;
1454 use base 'QueryParser::query_plan::filter';
1455
1456 #-------------------------------
1457 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::facet;
1458 use base 'QueryParser::query_plan::facet';
1459
1460 sub classname {
1461     my $self = shift;
1462     my ($classname) = split '\|', $self->name;
1463     return $classname;
1464 }
1465
1466 sub fields {
1467     my $self = shift;
1468     my ($classname,@fields) = split '\|', $self->name;
1469     return \@fields;
1470 }
1471
1472 sub table_alias {
1473     my $self = shift;
1474
1475     my $table_alias = "$self";
1476     $table_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1477     $table_alias .= '_' . $self->name;
1478     $table_alias =~ s/\|/_/go;
1479
1480     return $table_alias;
1481 }
1482
1483
1484 #-------------------------------
1485 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::modifier;
1486 use base 'QueryParser::query_plan::modifier';
1487
1488 #-------------------------------
1489 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::node::atom;
1490 use base 'QueryParser::query_plan::node::atom';
1491
1492 sub sql {
1493     my $self = shift;
1494     my $sql = shift;
1495
1496     $self->{sql} = $sql if ($sql);
1497
1498     return $self->{sql} if ($self->{sql});
1499     return $self->buildSQL;
1500 }
1501
1502 sub buildSQL {
1503     my $self = shift;
1504
1505     my $classname = $self->node->classname;
1506
1507     return $self->sql("to_tsquery('$classname','')") if $self->{dummy};
1508
1509     my $normalizers = $self->node->plan->QueryParser->query_normalizers( $classname );
1510     my $fields = $self->node->fields;
1511
1512     my $lang;
1513     my $filter = $self->node->plan->find_filter('preferred_language');
1514     $lang ||= $filter->args->[0] if ($filter && $filter->args);
1515     $lang ||= $self->node->plan->QueryParser->default_preferred_language;
1516     my $ts_configs = [];
1517
1518     if (@{$self->node->phrases}) {
1519         # We assume we want 'simple' for phrases. Gives us less to match against later.
1520         $ts_configs = ['simple'];
1521     } else {
1522         if (!@$fields) {
1523             $ts_configs = $self->node->plan->QueryParser->class_ts_config($classname, $lang);
1524         } else {
1525             for my $field (@$fields) {
1526                 push @$ts_configs, @{$self->node->plan->QueryParser->field_ts_config($classname, $field, $lang)};
1527             }
1528         }
1529         $ts_configs = [keys %{{map { $_ => 1 } @$ts_configs}}];
1530     }
1531
1532     # Assume we want exact if none otherwise provided.
1533     # Because we can reasonably expect this to exist
1534     $ts_configs = ['simple'] unless (scalar @$ts_configs);
1535
1536     $fields = $self->node->plan->QueryParser->search_fields->{$classname} if (!@$fields);
1537
1538     my %norms;
1539     my $pos = 0;
1540     for my $field (@$fields) {
1541         for my $nfield (keys %$normalizers) {
1542             for my $nizer ( @{$$normalizers{$nfield}} ) {
1543                 if ($field eq $nfield) {
1544                     my $param_string = OpenSRF::Utils::JSON->perl2JSON($nizer->{params});
1545                     if (!exists($norms{$nizer->{function}.$param_string})) {
1546                         $norms{$nizer->{function}.$param_string} = {p=>$pos++,n=>$nizer};
1547                     }
1548                 }
1549             }
1550         }
1551     }
1552
1553     my $sql = $self->node->plan->QueryParser->quote_value($self->content);
1554
1555     for my $n ( map { $$_{n} } sort { $$a{p} <=> $$b{p} } values %norms ) {
1556         $sql = join(', ', $sql, map { $self->node->plan->QueryParser->quote_value($_) } @{ $n->{params} });
1557         $sql = $n->{function}."($sql)";
1558     }
1559
1560     my $prefix = $self->prefix || '';
1561     my $suffix = $self->suffix || '';
1562     my $joiner = ' || ';
1563     $joiner = ' && ' if $self->prefix eq '!'; # Negative atoms should be "none of the variants" instead of "any of the variants"
1564
1565     $prefix = "'$prefix' ||" if $prefix;
1566     my $suffix_op = '';
1567     my $suffix_after = '';
1568
1569     $suffix_op = ":$suffix" if $suffix;
1570     $suffix_after = "|| '$suffix_op'" if $suffix;
1571
1572     my @sql_set = ();
1573     for my $ts_config (@$ts_configs) {
1574         push @sql_set, "to_tsquery('$ts_config', COALESCE(NULLIF($prefix '(' || btrim(regexp_replace($sql,E'(?:\\\\s+|:)','$suffix_op&','g'),'&|') $suffix_after || ')', '()'), ''))";
1575     }
1576
1577     $sql = join($joiner, @sql_set);
1578     $sql = '(' . $sql . ')' if (scalar(@$ts_configs) > 1);
1579
1580     return $self->sql($sql);
1581 }
1582
1583 #-------------------------------
1584 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::node;
1585 use base 'QueryParser::query_plan::node';
1586
1587 sub only_atoms {
1588     my $self = shift;
1589
1590     $self->{dummy_count} = 0;
1591
1592     my $atoms = $self->query_atoms;
1593     my @only_atoms;
1594     for my $a (@$atoms) {
1595         push(@only_atoms, $a) if (ref($a) && $a->isa('QueryParser::query_plan::node::atom'));
1596         $self->{dummy_count}++ if (ref($a) && $a->{dummy});
1597     }
1598
1599     return \@only_atoms;
1600 }
1601
1602 sub only_real_atoms {
1603     my $self = shift;
1604
1605     my $atoms = $self->query_atoms;
1606     my @only_real_atoms;
1607     for my $a (@$atoms) {
1608         push(@only_real_atoms, $a) if (ref($a) && $a->isa('QueryParser::query_plan::node::atom') && !($a->{dummy}));
1609     }
1610
1611     return \@only_real_atoms;
1612 }
1613
1614 sub only_positive_atoms {
1615     my $self = shift;
1616
1617     my $atoms = $self->query_atoms;
1618     my @only_positive_atoms;
1619     for my $a (@$atoms) {
1620         push(@only_positive_atoms, $a) if (ref($a) && $a->isa('QueryParser::query_plan::node::atom') && !($a->{dummy}) && ($a->{prefix} ne '!'));
1621     }
1622
1623     return \@only_positive_atoms;
1624 }
1625
1626 sub dummy_count {
1627     my $self = shift;
1628     return $self->{dummy_count};
1629 }
1630
1631 sub table {
1632     my $self = shift;
1633     my $table = shift;
1634     $self->{table} = $table if ($table);
1635     return $self->{table} if $self->{table};
1636     return $self->table( 'metabib.' . $self->classname . '_field_entry' );
1637 }
1638
1639 sub combined_table {
1640     my $self = shift;
1641     my $ctable = shift;
1642     $self->{ctable} = $ctable if ($ctable);
1643     return $self->{ctable} if $self->{ctable};
1644     return $self->combined_table( 'metabib.combined_' . $self->classname . '_field_entry' );
1645 }
1646
1647 sub combined_search {
1648     my $self = shift;
1649     return $self->plan->QueryParser->search_class_combined($self->classname);
1650 }
1651
1652 sub table_alias {
1653     my $self = shift;
1654     my $table_alias = shift;
1655     $self->{table_alias} = $table_alias if ($table_alias);
1656     return $self->{table_alias} if ($self->{table_alias});
1657
1658     $table_alias = "$self";
1659     $table_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1660     $table_alias .= '_' . $self->requested_class;
1661     $table_alias =~ s/\|/_/go;
1662
1663     return $self->table_alias( $table_alias );
1664 }
1665
1666 sub tsquery {
1667     my $self = shift;
1668     return $self->{tsquery} if ($self->{tsquery});
1669
1670     for my $atom (@{$self->query_atoms}) {
1671         if (ref($atom)) {
1672             $self->{tsquery} .= "\n" . ${spc} x 3 . $atom->sql;
1673         } else {
1674             $self->{tsquery} .= $atom x 2;
1675         }
1676     }
1677
1678     return $self->{tsquery};
1679 }
1680
1681 sub tsquery_rank {
1682     my $self = shift;
1683     return $self->{tsquery_rank} if ($self->{tsquery_rank});
1684     my @atomlines;
1685
1686     for my $atom (@{$self->only_positive_atoms}) {
1687         push @atomlines, "\n" . ${spc} x 3 . $atom->sql;
1688     }
1689     $self->{tsquery_rank} = join(' ||', @atomlines);
1690     $self->{tsquery_rank} = 'NULL::tsquery' unless $self->{tsquery_rank};
1691     return $self->{tsquery_rank};
1692 }
1693
1694 sub rank {
1695     my $self = shift;
1696     return $self->{rank} if ($self->{rank});
1697
1698     my $rank_norm_map = $self->plan->QueryParser->custom_data->{rank_cd_weight_map};
1699
1700     my $cover_density = 0;
1701     for my $norm ( keys %$rank_norm_map) {
1702         $cover_density += $$rank_norm_map{$norm} if ($self->plan->QueryParser->parse_tree->find_modifier($norm));
1703     }
1704
1705     my $weights = join(', ', @{$self->plan->QueryParser->search_class_weights($self->classname)});
1706
1707     return $self->{rank} = "ts_rank_cd('{" . $weights . "}', " . $self->table_alias . '.index_vector, ' . $self->table_alias . ".tsq_rank, $cover_density)";
1708 }
1709
1710
1711 1;
1712