]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Storage/Driver/Pg/QueryParser.pm
941085133d0c62108999a8f8b130406b1accc626
[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 simple_plan {
140     my $self = shift;
141
142     return 0 unless $self->parse_tree;
143     return 0 if @{$self->parse_tree->filters};
144     return 0 if @{$self->parse_tree->modifiers};
145     for my $node ( @{ $self->parse_tree->query_nodes } ) {
146         return 0 if (!ref($node) && $node eq '|');
147         next unless (ref($node));
148         return 0 if ($node->isa('QueryParser::query_plan'));
149     }
150
151     return 1;
152 }
153
154 sub toSQL {
155     my $self = shift;
156     return $self->parse_tree->toSQL;
157 }
158
159 sub dynamic_filters {
160     my $self = shift;
161     my $new = shift;
162
163     $self->custom_data->{dynamic_filters} ||= [];
164     push(@{$self->custom_data->{dynamic_filters}}, $new) if ($new);
165     return $self->custom_data->{dynamic_filters};
166 }
167
168 sub dynamic_sorters {
169     my $self = shift;
170     my $new = shift;
171
172     $self->custom_data->{dynamic_sorters} ||= [];
173     push(@{$self->custom_data->{dynamic_sorters}}, $new) if ($new);
174     return $self->custom_data->{dynamic_sorters};
175 }
176
177 sub facet_field_id_map {
178     my $self = shift;
179     my $map = shift;
180
181     $self->custom_data->{facet_field_id_map} ||= {};
182     $self->custom_data->{facet_field_id_map} = $map if ($map);
183     return $self->custom_data->{facet_field_id_map};
184 }
185
186 sub add_facet_field_id_map {
187     my $self = shift;
188     my $class = shift;
189     my $field = shift;
190     my $id = shift;
191     my $weight = shift;
192
193     $self->add_facet_field( $class => $field );
194     $self->facet_field_id_map->{by_id}{$id} = { classname => $class, field => $field, weight => $weight };
195     $self->facet_field_id_map->{by_class}{$class}{$field} = $id;
196
197     return {
198         by_id => { $id => { classname => $class, field => $field, weight => $weight } },
199         by_class => { $class => { $field => $id } }
200     };
201 }
202
203 sub facet_field_class_by_id {
204     my $self = shift;
205     my $id = shift;
206
207     return $self->facet_field_id_map->{by_id}{$id};
208 }
209
210 sub facet_field_ids_by_class {
211     my $self = shift;
212     my $class = shift;
213     my $field = shift;
214
215     return undef unless ($class);
216
217     if ($field) {
218         return [$self->facet_field_id_map->{by_class}{$class}{$field}];
219     }
220
221     return [values( %{ $self->facet_field_id_map->{by_class}{$class} } )];
222 }
223
224 sub search_field_id_map {
225     my $self = shift;
226     my $map = shift;
227
228     $self->custom_data->{search_field_id_map} ||= {};
229     $self->custom_data->{search_field_id_map} = $map if ($map);
230     return $self->custom_data->{search_field_id_map};
231 }
232
233 sub search_field_virtual_map {
234     my $self = shift;
235     my $map = shift;
236
237     $self->custom_data->{search_field_virtual_map} ||= {};
238     $self->custom_data->{search_field_virtual_map} = $map if ($map);
239     return $self->custom_data->{search_field_virtual_map};
240 }
241
242 sub add_search_field_id_map {
243     my $self = shift;
244     my $class = shift;
245     my $field = shift;
246     my $id = shift;
247     my $weight = shift;
248     my $combined = shift;
249
250     $self->add_search_field( $class => $field );
251     $self->search_field_id_map->{by_id}{$id} = { classname => $class, field => $field, weight => $weight };
252     $self->search_field_id_map->{by_class}{$class}{$field} = $id;
253
254     return {
255         by_id => { $id => { classname => $class, field => $field, weight => $weight } },
256         by_class => { $class => { $field => $id } }
257     };
258 }
259
260 sub add_search_field_virtual_map {
261     my $self = shift;
262     my $realid = shift;
263     my $virtid = shift;
264     my $weight = shift;
265
266     $self->search_field_virtual_map->{by_virt}{$virtid} ||= [];
267     push @{$self->search_field_virtual_map->{by_virt}{$virtid}}, { real => $realid, weight => $weight };
268
269     $self->search_field_virtual_map->{by_real}{$realid} ||= [];
270     push @{$self->search_field_virtual_map->{by_real}{$realid}}, { virt => $virtid, weight => $weight };
271 }
272
273 sub search_field_class_by_id {
274     my $self = shift;
275     my $id = shift;
276
277     return $self->search_field_id_map->{by_id}{$id};
278 }
279
280 sub search_field_ids_by_class {
281     my $self = shift;
282     my $class = shift;
283     my $field = shift;
284
285     return undef unless ($class);
286
287     if ($field) {
288         return [$self->search_field_id_map->{by_class}{$class}{$field}];
289     }
290
291     return [values( %{ $self->search_field_id_map->{by_class}{$class} } )];
292 }
293
294 sub relevance_bumps {
295     my $self = shift;
296     my $bumps = shift;
297
298     $self->custom_data->{rel_bumps} ||= {};
299     $self->custom_data->{rel_bumps} = $bumps if ($bumps);
300     return $self->custom_data->{rel_bumps};
301 }
302
303 sub find_relevance_bumps {
304     my $self = shift;
305     my $class = shift;
306     my $field = shift;
307
308     return $self->relevance_bumps->{$class}{$field};
309 }
310
311 sub add_relevance_bump {
312     my $self = shift;
313     my $class = shift;
314     my $field = shift;
315     my $type = shift;
316     my $multiplier = shift;
317     my $active = shift;
318
319     if (defined($active) and $active eq 'f') {
320         $active = 0;
321     } else {
322         $active = 1;
323     }
324
325     $self->relevance_bumps->{$class}{$field}{$type} = { multiplier => $multiplier, active => $active };
326
327     return { $class => { $field => { $type => { multiplier => $multiplier, active => $active } } } };
328 }
329
330 sub search_class_weights {
331     my $self = shift;
332     my $class = shift;
333     my $a_weight = shift;
334     my $b_weight = shift;
335     my $c_weight = shift;
336     my $d_weight = shift;
337
338     $self->custom_data->{class_weights} ||= {};
339     # Note: This reverses the A-D order, putting D first, because that is how the call actually works in PG
340     $self->custom_data->{class_weights}->{$class} ||= [0.1, 0.2, 0.4, 1.0];
341     $self->custom_data->{class_weights}->{$class} = [$d_weight, $c_weight, $b_weight, $a_weight] if $a_weight;
342     return $self->custom_data->{class_weights}->{$class};
343 }
344
345 sub search_class_combined {
346     my $self = shift;
347     my $class = shift;
348     my $c = shift;
349
350     $self->custom_data->{class_combined} ||= {};
351     # Note: This reverses the A-D order, putting D first, because that is how the call actually works in PG
352     $self->custom_data->{class_combined}->{$class} ||= 0;
353     $self->custom_data->{class_combined}->{$class} = 1 if $c && $c =~ /^(?:t|y|1)/i;
354     return $self->custom_data->{class_combined}->{$class};
355 }
356
357 sub class_ts_config {
358     my $self = shift;
359     my $class = shift;
360     my $lang = shift || 'DEFAULT';
361     my $always = shift;
362     my $ts_config = shift;
363
364     $self->custom_data->{class_ts_config} ||= {};
365     $self->custom_data->{class_ts_config}->{$class} ||= {};
366     $self->custom_data->{class_ts_config}->{$class}->{$lang} ||= {};
367     $self->custom_data->{class_ts_config}->{$class}->{$lang}->{normal} ||= [];
368     $self->custom_data->{class_ts_config}->{$class}->{$lang}->{always} ||= [];
369     $self->custom_data->{class_ts_config}->{$class}->{'DEFAULT'} ||= {};
370     $self->custom_data->{class_ts_config}->{$class}->{'DEFAULT'}->{normal} ||= [];
371     $self->custom_data->{class_ts_config}->{$class}->{'DEFAULT'}->{always} ||= [];
372
373     if ($ts_config) {
374         push @{$self->custom_data->{class_ts_config}->{$class}->{$lang}->{normal}}, $ts_config unless $always;
375         push @{$self->custom_data->{class_ts_config}->{$class}->{$lang}->{always}}, $ts_config if $always;
376     }
377
378     my $return = [];
379     push @$return, @{$self->custom_data->{class_ts_config}->{$class}->{$lang}->{always}};
380     push @$return, @{$self->custom_data->{class_ts_config}->{$class}->{$lang}->{normal}} unless $always;
381     if($lang ne 'DEFAULT') {
382         push @$return, @{$self->custom_data->{class_ts_config}->{$class}->{'DEFAULT'}->{always}};
383         push @$return, @{$self->custom_data->{class_ts_config}->{$class}->{'DEFAULT'}->{normal}} unless $always;
384     }
385     return $return;
386 }
387
388 sub field_ts_config {
389     my $self = shift;
390     my $class = shift;
391     my $field = shift;
392     my $lang = shift || 'DEFAULT';
393     my $ts_config = shift;
394
395     $self->custom_data->{field_ts_config} ||= {};
396     $self->custom_data->{field_ts_config}->{$class} ||= {};
397     $self->custom_data->{field_ts_config}->{$class}->{$field} ||= {};
398     $self->custom_data->{field_ts_config}->{$class}->{$field}->{$lang} ||= [];
399     $self->custom_data->{field_ts_config}->{$class}->{$field}->{'DEFAULT'} ||= [];
400
401     if ($ts_config) {
402         push @{$self->custom_data->{field_ts_config}->{$class}->{$field}->{$lang}}, $ts_config;
403     }
404
405     my $return = [];
406     push @$return, @{$self->custom_data->{field_ts_config}->{$class}->{$field}->{$lang}};
407     if($lang ne 'DEFAULT') {
408         push @$return, @{$self->custom_data->{field_ts_config}->{$class}->{$field}->{'DEFAULT'}};
409     }
410     # Make it easy on us: Grab any "always" for the class here. If we have none we grab them all.
411     push @$return, @{$self->class_ts_config($class, $lang, scalar(@$return))};
412     return $return;
413 }
414
415 sub initialize_search_field_id_map {
416     my $self = shift;
417     my $cmf_list = shift;
418
419     for my $cmf (@$cmf_list) {
420         __PACKAGE__->add_search_field_id_map( $cmf->field_class, $cmf->name, $cmf->id, $cmf->weight ) if ($U->is_true($cmf->search_field));
421         __PACKAGE__->add_facet_field_id_map( $cmf->field_class, $cmf->name, $cmf->id, $cmf->weight ) if ($U->is_true($cmf->facet_field));
422     }
423
424     return $self->search_field_id_map;
425 }
426
427 sub initialize_search_field_virtual_map {
428     my $self = shift;
429     my $cmfvm_list = shift;
430
431     __PACKAGE__->add_search_field_virtual_map( $_->real, $_->virtual, $_->weight )
432         for (@$cmfvm_list);
433
434     $logger->debug('Virtual field map: ' . Dumper($self->search_field_virtual_map));
435     return $self->search_field_virtual_map;
436 }
437
438 sub initialize_aliases {
439     my $self = shift;
440     my $cmsa_list = shift;
441
442     for my $cmsa (@$cmsa_list) {
443         if (!$cmsa->field) {
444             __PACKAGE__->add_search_class_alias( $cmsa->field_class, $cmsa->alias );
445         } else {
446             my $c = $self->search_field_class_by_id( $cmsa->field );
447             __PACKAGE__->add_search_field_alias( $cmsa->field_class, $c->{field}, $cmsa->alias );
448         }
449     }
450 }
451
452 sub initialize_relevance_bumps {
453     my $self = shift;
454     my $sra_list = shift;
455
456     for my $sra (@$sra_list) {
457         my $c = $self->search_field_class_by_id( $sra->field );
458         __PACKAGE__->add_relevance_bump( $c->{classname}, $c->{field}, $sra->bump_type, $sra->multiplier, $sra->active );
459     }
460
461     return $self->relevance_bumps;
462 }
463
464 sub initialize_query_normalizers {
465     my $self = shift;
466     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" }] }
467
468     for my $cmfinm ( @$tree ) {
469         my $field_info = $self->search_field_class_by_id( $cmfinm->field );
470         next unless $field_info;
471         __PACKAGE__->add_query_normalizer( $field_info->{classname}, $field_info->{field}, $cmfinm->norm->func, OpenSRF::Utils::JSON->JSON2perl($cmfinm->params) );
472     }
473 }
474
475 sub initialize_dynamic_filters {
476     my $self = shift;
477     my $list = shift; # open-ils.cstore.direct.config.record_attr_definition.search.atomic { "id" : { "!=" : null } }
478
479     for my $crad ( @$list ) {
480         __PACKAGE__->dynamic_filters( __PACKAGE__->add_search_filter( $crad->name ) ) if ($U->is_true($crad->filter));
481         __PACKAGE__->dynamic_sorters( $crad->name ) if ($U->is_true($crad->sorter));
482     }
483 }
484
485 sub initialize_filter_normalizers {
486     my $self = shift;
487     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" }] }
488
489     for my $crainm ( @$tree ) {
490         __PACKAGE__->add_filter_normalizer( $crainm->attr, $crainm->norm->func, OpenSRF::Utils::JSON->JSON2perl($crainm->params) );
491     }
492 }
493
494 sub initialize_search_class_weights {
495     my $self = shift;
496     my $classes = shift;
497
498     for my $search_class (@$classes) {
499         __PACKAGE__->search_class_weights( $search_class->name, $search_class->a_weight, $search_class->b_weight, $search_class->c_weight, $search_class->d_weight );
500         __PACKAGE__->search_class_combined( $search_class->name, $search_class->combined );
501     }
502 }
503
504 sub initialize_class_ts_config {
505     my $self = shift;
506     my $class_entries = shift;
507
508     for my $search_class_entry (@$class_entries) {
509         __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);
510     }
511 }
512
513 sub initialize_field_ts_config {
514     my $self = shift;
515     my $field_entries = shift;
516     my $field_objects = shift;
517     my %field_hash = map { $_->id => $_ } @$field_objects;
518
519     for my $search_field_entry (@$field_entries) {
520         my $field_object = $field_hash{$search_field_entry->metabib_field};
521         __PACKAGE__->field_ts_config($field_object->field_class,$field_object->name,$search_field_entry->search_lang,$search_field_entry->ts_config);
522     }
523 }
524
525 our $_complete = 0;
526 sub initialization_complete {
527     return $_complete;
528 }
529
530 sub initialize {
531     my $self = shift;
532     my %args = @_;
533
534     return $_complete if ($_complete);
535
536     # tsearch rank normalization adjustments. see http://www.postgresql.org/docs/9.0/interactive/textsearch-controls.html#TEXTSEARCH-RANKING for details
537     $self->custom_data->{rank_cd_weight_map} = {
538         CD_logDocumentLength    => 1,
539         CD_documentLength       => 2,
540         CD_meanHarmonic         => 4,
541         CD_uniqueWords          => 8,
542         CD_logUniqueWords       => 16,
543         CD_selfPlusOne          => 32
544     };
545
546     $self->add_search_modifier( $_ ) for (keys %{ $self->custom_data->{rank_cd_weight_map} });
547
548     $self->initialize_search_field_id_map( $args{config_metabib_field} )
549         if ($args{config_metabib_field});
550
551     $self->initialize_search_field_virtual_map( $args{config_metabib_field_virtual_map} )
552         if ($args{config_metabib_field_virtual_map});
553
554     $self->initialize_aliases( $args{config_metabib_search_alias} )
555         if ($args{config_metabib_search_alias});
556
557     $self->initialize_relevance_bumps( $args{search_relevance_adjustment} )
558         if ($args{search_relevance_adjustment});
559
560     $self->initialize_query_normalizers( $args{config_metabib_field_index_norm_map} )
561         if ($args{config_metabib_field_index_norm_map});
562
563     $self->initialize_dynamic_filters( $args{config_record_attr_definition} )
564         if ($args{config_record_attr_definition});
565
566     $self->initialize_filter_normalizers( $args{config_record_attr_index_norm_map} )
567         if ($args{config_record_attr_index_norm_map});
568
569     $self->initialize_search_class_weights( $args{config_metabib_class} )
570         if ($args{config_metabib_class});
571
572     $self->initialize_class_ts_config( $args{config_metabib_class_ts_map} )
573         if ($args{config_metabib_class_ts_map});
574
575     $self->initialize_field_ts_config( $args{config_metabib_field_ts_map}, $args{config_metabib_field} )
576         if ($args{config_metabib_field_ts_map} && $args{config_metabib_field});
577
578     $_complete = 1 if (
579         $args{config_metabib_field_index_norm_map} &&
580         $args{search_relevance_adjustment} &&
581         $args{config_metabib_search_alias} &&
582         $args{config_metabib_field} &&
583         $args{config_record_attr_definition}
584     );
585
586     return $_complete;
587 }
588
589 sub TEST_SETUP {
590     
591     __PACKAGE__->allow_nested_modifiers(1);
592
593     __PACKAGE__->add_search_field_id_map( series => seriestitle => 1 => 1 );
594
595     __PACKAGE__->add_search_field_id_map( series => seriestitle => 1 => 1 );
596     __PACKAGE__->add_relevance_bump( series => seriestitle => first_word => 1.5 );
597     __PACKAGE__->add_relevance_bump( series => seriestitle => full_match => 20 );
598     
599     __PACKAGE__->add_search_field_id_map( title => abbreviated => 2 => 1 );
600     __PACKAGE__->add_relevance_bump( title => abbreviated => first_word => 1.5 );
601     __PACKAGE__->add_relevance_bump( title => abbreviated => full_match => 20 );
602     
603     __PACKAGE__->add_search_field_id_map( title => translated => 3 => 1 );
604     __PACKAGE__->add_relevance_bump( title => translated => first_word => 1.5 );
605     __PACKAGE__->add_relevance_bump( title => translated => full_match => 20 );
606     
607     __PACKAGE__->add_search_field_id_map( title => proper => 6 => 1 );
608     __PACKAGE__->add_query_normalizer( title => proper => 'search_normalize' );
609     __PACKAGE__->add_relevance_bump( title => proper => first_word => 1.5 );
610     __PACKAGE__->add_relevance_bump( title => proper => full_match => 20 );
611     __PACKAGE__->add_relevance_bump( title => proper => word_order => 10 );
612     
613     __PACKAGE__->add_search_field_id_map( author => corporate => 7 => 1 );
614     __PACKAGE__->add_relevance_bump( author => corporate => first_word => 1.5 );
615     __PACKAGE__->add_relevance_bump( author => corporate => full_match => 20 );
616     
617     __PACKAGE__->add_facet_field_id_map( author => personal => 8 => 1 );
618
619     __PACKAGE__->add_search_field_id_map( author => personal => 8 => 1 );
620     __PACKAGE__->add_relevance_bump( author => personal => first_word => 1.5 );
621     __PACKAGE__->add_relevance_bump( author => personal => full_match => 20 );
622     __PACKAGE__->add_query_normalizer( author => personal => 'search_normalize' );
623     __PACKAGE__->add_query_normalizer( author => personal => 'split_date_range' );
624     
625     __PACKAGE__->add_facet_field_id_map( subject => topic => 14 => 1 );
626
627     __PACKAGE__->add_search_field_id_map( subject => topic => 14 => 1 );
628     __PACKAGE__->add_relevance_bump( subject => topic => first_word => 1 );
629     __PACKAGE__->add_relevance_bump( subject => topic => full_match => 1 );
630     
631     __PACKAGE__->add_search_field_id_map( subject => complete => 16 => 1 );
632     __PACKAGE__->add_relevance_bump( subject => complete => first_word => 1 );
633     __PACKAGE__->add_relevance_bump( subject => complete => full_match => 1 );
634     
635     __PACKAGE__->add_search_field_id_map( keyword => keyword => 15 => 1 );
636     __PACKAGE__->add_relevance_bump( keyword => keyword => first_word => 1 );
637     __PACKAGE__->add_relevance_bump( keyword => keyword => full_match => 1 );
638     
639     __PACKAGE__->add_search_field_virtual_map( 6 => 15 => 5 );
640
641     __PACKAGE__->class_ts_config( 'series', undef, 1, 'english_nostop' );
642     __PACKAGE__->class_ts_config( 'title', undef, 1, 'english_nostop' );
643     __PACKAGE__->class_ts_config( 'author', undef, 1, 'english_nostop' );
644     __PACKAGE__->class_ts_config( 'subject', undef, 1, 'english_nostop' );
645     __PACKAGE__->class_ts_config( 'keyword', undef, 1, 'english_nostop' );
646     __PACKAGE__->class_ts_config( 'series', undef, 1, 'simple' );
647     __PACKAGE__->class_ts_config( 'title', undef, 1, 'simple' );
648     __PACKAGE__->class_ts_config( 'author', undef, 1, 'simple' );
649     __PACKAGE__->class_ts_config( 'subject', undef, 1, 'simple' );
650     __PACKAGE__->class_ts_config( 'keyword', undef, 1, 'simple' );
651
652     # French! To test language limiters
653     __PACKAGE__->class_ts_config( 'series', 'fre', 1, 'french_nostop' );
654     __PACKAGE__->class_ts_config( 'title', 'fre', 1, 'french_nostop' );
655     __PACKAGE__->class_ts_config( 'author', 'fre', 1, 'french_nostop' );
656     __PACKAGE__->class_ts_config( 'subject', 'fre', 1, 'french_nostop' );
657     __PACKAGE__->class_ts_config( 'keyword', 'fre', 1, 'french_nostop' );
658
659     # Not a default config by any means, but good for some testing
660     __PACKAGE__->field_ts_config( 'author', 'personal', 'eng', 'english' );
661     __PACKAGE__->field_ts_config( 'author', 'personal', 'fre', 'french' );
662     
663     __PACKAGE__->add_search_class_alias( keyword => 'kw' );
664     __PACKAGE__->add_search_class_alias( title => 'ti' );
665     __PACKAGE__->add_search_class_alias( author => 'au' );
666     __PACKAGE__->add_search_class_alias( author => 'name' );
667     __PACKAGE__->add_search_class_alias( author => 'dc.contributor' );
668     __PACKAGE__->add_search_class_alias( subject => 'su' );
669     __PACKAGE__->add_search_class_alias( subject => 'bib.subject(?:Title|Place|Occupation)' );
670     __PACKAGE__->add_search_class_alias( series => 'se' );
671     __PACKAGE__->add_search_class_alias( keyword => 'dc.identifier' );
672     
673     __PACKAGE__->add_query_normalizer( author => corporate => 'search_normalize' );
674     __PACKAGE__->add_query_normalizer( keyword => keyword => 'search_normalize' );
675     
676     __PACKAGE__->add_search_field_alias( subject => name => 'bib.subjectName' );
677     
678     #__PACKAGE__->search_class_combined( keyword => 1 );
679     __PACKAGE__->search_class_combined( author => 1 );
680 }
681
682 __PACKAGE__->default_search_class( 'keyword' );
683
684 # implements EG-specific stored subqueries
685 __PACKAGE__->add_search_filter( 'saved_query', sub { return __PACKAGE__->subquery_callback(@_) } );
686 __PACKAGE__->add_search_filter( 'filter_group_entry', sub { return __PACKAGE__->filter_group_entry_callback(@_) } );
687
688 # will be retained simply for back-compat
689 __PACKAGE__->add_search_filter( 'format', sub { return __PACKAGE__->format_callback(@_) } );
690
691 # grumble grumble, special cases against date1 and date2
692 __PACKAGE__->add_search_filter( 'before' );
693 __PACKAGE__->add_search_filter( 'after' );
694 __PACKAGE__->add_search_filter( 'between' );
695 __PACKAGE__->add_search_filter( 'during' );
696
697 # various filters for limiting in various ways
698 __PACKAGE__->add_search_filter( 'edit_date' );
699 __PACKAGE__->add_search_filter( 'create_date' );
700 __PACKAGE__->add_search_filter( 'statuses' );
701 __PACKAGE__->add_search_filter( 'locations' );
702 __PACKAGE__->add_search_filter( 'location_groups' );
703 __PACKAGE__->add_search_filter( 'bib_source' );
704 __PACKAGE__->add_search_filter( 'badge_orgs' );
705 __PACKAGE__->add_search_filter( 'badges' );
706 __PACKAGE__->add_search_filter( 'site' );
707 __PACKAGE__->add_search_filter( 'pref_ou' );
708 __PACKAGE__->add_search_filter( 'lasso' );
709 __PACKAGE__->add_search_filter( 'my_lasso' );
710 __PACKAGE__->add_search_filter( 'depth' );
711 __PACKAGE__->add_search_filter( 'language' );
712 __PACKAGE__->add_search_filter( 'offset' );
713 __PACKAGE__->add_search_filter( 'limit' );
714 __PACKAGE__->add_search_filter( 'check_limit' );
715 __PACKAGE__->add_search_filter( 'skip_check' );
716 __PACKAGE__->add_search_filter( 'superpage' );
717 __PACKAGE__->add_search_filter( 'superpage_size' );
718 __PACKAGE__->add_search_filter( 'estimation_strategy' );
719 __PACKAGE__->add_search_filter( 'from_metarecord' );
720 __PACKAGE__->add_search_modifier( 'available' );
721 __PACKAGE__->add_search_modifier( 'staff' );
722 __PACKAGE__->add_search_modifier( 'deleted' );
723 __PACKAGE__->add_search_modifier( 'lucky' );
724
725 # Start from container data (bre, acn, acp): container(bre,bookbag,123,deadb33fdeadb33fdeadb33fdeadb33f)
726 __PACKAGE__->add_search_filter( 'container' );
727
728 # Start from a list of record ids, either bre or metarecords, depending on the #metabib modifier
729 __PACKAGE__->add_search_filter( 'record_list' );
730
731 __PACKAGE__->add_search_filter( 'has_browse_entry' );
732
733 # copy_tag(copy_tag_code,copy_tag_search)
734 __PACKAGE__->add_search_filter( 'copy_tag' );
735
736 # used internally, but generally not user-settable
737 __PACKAGE__->add_search_filter( 'preferred_language' );
738 __PACKAGE__->add_search_filter( 'preferred_language_weight' );
739 __PACKAGE__->add_search_filter( 'preferred_language_multiplier' );
740 __PACKAGE__->add_search_filter( 'core_limit' );
741
742 # XXX Valid values to be supplied by SVF
743 __PACKAGE__->add_search_filter( 'sort' );
744
745 # modifies core query, not configurable
746 __PACKAGE__->add_search_modifier( 'descending' );
747 __PACKAGE__->add_search_modifier( 'ascending' );
748 __PACKAGE__->add_search_modifier( 'nullsfirst' );
749 __PACKAGE__->add_search_modifier( 'nullslast' );
750 __PACKAGE__->add_search_modifier( 'metarecord' );
751 __PACKAGE__->add_search_modifier( 'metabib' );
752
753
754 #-------------------------------
755 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan;
756 use base 'QueryParser::query_plan';
757 use OpenSRF::Utils::Logger qw($logger);
758 use OpenILS::Utils::DateTime qw/:datetime/;
759 use Data::Dumper;
760 use OpenILS::Application::AppUtils;
761 use OpenILS::Utils::Normalize qw/search_normalize/;
762 my $apputils = "OpenILS::Application::AppUtils";
763
764 our %_dfilter_controlled_cache = ();
765 our %_dfilter_stats_cache = ();
766 our $_pg_version = 0;
767
768 sub dynamic_filter_compile {
769     my ($self, $filter, $params, $negate) = @_;
770     my $e = OpenILS::Utils::CStoreEditor->new;
771
772     $negate = $negate ? '!' : '';
773
774     if (!$_pg_version) {
775         ($_pg_version = $e->json_query({from => ['version']})->[0]->{version}) =~ s/^.+?(\d\.\d).+$/$1/;
776     }
777
778     my $common = 0;
779     if ($_pg_version >= 9.2) {
780         if (!scalar keys %_dfilter_stats_cache) {
781             my $data = $e->json_query({from => ['evergreen.pg_statistics', 'record_attr_vector_list', 'vlist']});
782             %_dfilter_stats_cache = map {
783                 ( $_->{element}, $_->{frequency} )
784             } grep { $_->{frequency} > 5 } @$data; # Pin floor to 5% of the table
785         }
786     } else {
787         $common = 1; # Assume it's expensive
788     }
789
790     if (!exists($_dfilter_controlled_cache{$filter})) {
791         my $crad = $e->retrieve_config_record_attr_definition($filter);
792         my $ccvm_list = $e->search_config_coded_value_map({ctype =>$filter});
793
794         $_dfilter_controlled_cache{$filter} = $crad->to_bare_hash;
795         $_dfilter_controlled_cache{$filter}{controlled} = scalar @$ccvm_list;
796     }
797
798     my $method = $_dfilter_controlled_cache{$filter}{controlled} ?
799         'search_config_coded_value_map' : 'search_metabib_uncontrolled_record_attr_value';
800     my $attr_field = $_dfilter_controlled_cache{$filter}{controlled} ?
801         'ctype' : 'attr';
802     my $value_field = $_dfilter_controlled_cache{$filter}{controlled} ?
803         'code' : 'value';
804
805     my $attr_objects = $e->$method({ $attr_field => $filter, $value_field => $params });
806     $common = scalar(grep { exists($_dfilter_stats_cache{$_->id}) } @$attr_objects) unless $common;
807     
808     return (sprintf('%s(%s)', $negate,
809         join(
810             '|', 
811             map { $_->id } @$attr_objects
812         )
813     ), $common);
814 }
815
816 sub toSQL {
817     my $self = shift;
818
819     my %filters;
820
821     for my $f ( qw/preferred_language preferred_language_multiplier preferred_language_weight core_limit check_limit skip_check superpage superpage_size/ ) {
822         my $col = $f;
823         $col = 'preferred_language_multiplier' if ($f eq 'preferred_language_weight');
824         my ($filter) = $self->find_filter($f);
825         if ($filter and @{$filter->args}) {
826             $filters{$col} = $filter->args->[0];
827         }
828     }
829
830     $self->QueryParser->superpage($filters{superpage}) if ($filters{superpage});
831     $self->QueryParser->superpage_size($filters{superpage_size}) if ($filters{superpage_size});
832     $self->QueryParser->core_limit($filters{core_limit}) if ($filters{core_limit});
833
834     $logger->debug("Query plan:\n".Dumper($self));
835
836     my $flat_plan = $self->flatten;
837
838     # generate the relevance ranking
839     my $rel = '1'; # Default to something simple in case rank_list is empty.
840     if (@{$$flat_plan{rank_list}}) {
841         $rel = "AVG(\n"
842              . ${spc} x 5 ."("
843              . join(")\n" . ${spc} x 5 . "+ (", @{$$flat_plan{rank_list}})
844              . ")\n"
845              . ${spc} x 4 . ")+1";
846     }
847
848     # find any supplied sort option
849     my ($sort_filter) = $self->find_filter('sort');
850     if ($sort_filter) {
851         $sort_filter = $sort_filter->args->[0];
852     } else {
853         $sort_filter = 'rel';
854     }
855
856     my $lang_join = '';
857     if (($filters{preferred_language} || $self->QueryParser->default_preferred_language) && ($filters{preferred_language_multiplier} || $self->QueryParser->default_preferred_language_multiplier)) {
858     
859         my $pl = $self->QueryParser->quote_value( $filters{preferred_language} ? $filters{preferred_language} : $self->QueryParser->default_preferred_language );
860         $$flat_plan{with} .= ',' if $$flat_plan{with};
861         $$flat_plan{with} .= "lang_with AS (SELECT id FROM config.coded_value_map WHERE ctype = 'item_lang' AND code = $pl)";
862         $lang_join = ",lang_with";
863
864         my $plw = $filters{preferred_language_multiplier} ? $filters{preferred_language_multiplier} : $self->QueryParser->default_preferred_language_multiplier;
865         $rel = "($rel * COALESCE( NULLIF( FIRST(mrv.vlist \@> ARRAY[lang_with.id]), FALSE )::INT * $plw, 1))";
866         $$flat_plan{uses_mrv} = 1;
867     }
868
869     my $mrv_join = '';
870     if ($$flat_plan{uses_mrv}) {
871         $mrv_join = 'INNER JOIN metabib.record_attr_vector_list mrv ON m.source = mrv.source';
872     }
873
874     my $mra_join = '';
875     if ($$flat_plan{uses_mrd}) {
876         $mra_join = 'INNER JOIN metabib.record_attr mrd ON m.source = mrd.id';
877     }
878
879     my $pubdate_join = "LEFT JOIN metabib.record_sorter pubdate_t ON m.source = pubdate_t.source AND attr = 'pubdate'";
880
881     my $bre_join = '';
882     if ($self->find_modifier('deleted')) {
883         $bre_join = 'INNER JOIN biblio.record_entry bre ON m.source = bre.id AND bre.deleted';
884         # The above suffices for filters too when the #deleted modifier
885         # is in use.
886     } else {
887         $bre_join = 'INNER JOIN biblio.record_entry bre ON m.source = bre.id AND NOT bre.deleted';
888     }
889
890     my $desc = 'ASC';
891     $desc = 'DESC' if ($self->find_modifier('descending'));
892
893     my $nullpos = 'NULLS LAST';
894     $nullpos = 'NULLS FIRST' if ($self->find_modifier('nullsfirst'));
895
896     # Do we have a badges() filter?
897     my $badges = '';
898     my ($badge_filter) = $self->find_filter('badges');
899     if ($badge_filter && @{$badge_filter->args}) {
900         $badges = join (',', grep /^\d+$/, @{$badge_filter->args});
901     }
902
903     # Do we have a badge_orgs() filter? (used for calculating popularity)
904     my $borgs = '';
905     my ($bo_filter) = $self->find_filter('badge_orgs');
906     if ($bo_filter && @{$bo_filter->args}) {
907         $borgs = join (',', grep /^\d+$/, @{$bo_filter->args});
908     }
909
910     # Build the badge-ish WITH query
911     my $pop_with = <<'    WITH';
912         pop_with AS (
913             SELECT  record,
914                     ARRAY_AGG(badge) AS badges,
915                     SUM(s.score::NUMERIC*b.weight::NUMERIC)/SUM(b.weight::NUMERIC) AS total_score
916               FROM  rating.record_badge_score s
917                     JOIN rating.badge b ON (
918                         b.id = s.badge
919     WITH
920
921     $pop_with .= " AND b.id = ANY ('{$badges}')" if ($badges);
922     $pop_with .= " AND b.scope = ANY ('{$borgs}')" if ($borgs);
923     $pop_with .= ') GROUP BY 1)'; 
924
925     my $pop_join = $badges ? # inner join if we are restricting via badges()
926         'INNER JOIN pop_with ON ( m.source = pop_with.record )' : 
927         'LEFT JOIN pop_with ON ( m.source = pop_with.record )';
928
929     $$flat_plan{with} .= ',' if $$flat_plan{with};
930     $$flat_plan{with} .= $pop_with;
931
932
933     my $rank;
934     my $pop_extra_sort = '';
935     if (grep {$_ eq $sort_filter} @{$self->QueryParser->dynamic_sorters}) {
936         $rank = "FIRST((SELECT value FROM metabib.record_sorter rbr WHERE rbr.source = m.source and attr = '$sort_filter'))"
937     } elsif ($sort_filter eq 'create_date') {
938         $rank = "FIRST((SELECT create_date FROM biblio.record_entry rbr WHERE rbr.id = m.source))";
939     } elsif ($sort_filter eq 'edit_date') {
940         $rank = "FIRST((SELECT edit_date FROM biblio.record_entry rbr WHERE rbr.id = m.source))";
941     } elsif ($sort_filter eq 'poprel') {
942         my $max_mult = $self->QueryParser->max_popularity_importance_multiplier() // 2.0;
943         $max_mult = 0.1 if $max_mult < 0.1; # keep it within reasonable bounds,
944                                             # and avoid the division-by-zero error
945                                             # you'd get if you allowed it to be
946                                             # zero
947
948         if ( $max_mult == 1.0 ) { # no adjustment requested by the configuration
949             $rank = "1.0/($rel)::NUMERIC";
950         } else { # calculate adjustment
951
952             # Scale the 0-5 effect of popularity badges by providing a multiplier
953             # for the badge average based on the overall maximum
954             # multiplier.  Two examples, comparing the effect to the default
955             # $max_mult value of 2.0, which causes a $adjusted_scale value
956             # of 0.2:
957             #
958             #  * Given the default $max_mult of 2.0, the value of
959             #    $adjusted_scale will be 0.2 [($max_mult - 1.0) / 5.0].
960             #    For a record whose average badge score is the maximum
961             #    of 5.0, that would make the relevance multiplier be
962             #    2.0:
963             #       1.0 + (5.0 [average score] * 0.2 [ $adjusted_scale ],
964             #    This would have the effect of doubling the effective
965             #    relevance of highly popular items.
966             #
967             #  * Given a $max_mult of 1.1, the value of $adjusted_scale
968             #    will be 0.02, meaning that the average badge value will be
969             #    multiplied by 0.02 rather than 0.2, then added to 1.0 and
970             #    used as a multiplier against the base relevance.  Thus a
971             #    change of at most 10% to the base relevance for a record
972             #    with a 5.0 average badge score. This will allow records
973             #    that are naturally very relevant to avoid being pushed
974             #    below badge-heavy records.
975             #
976             #  * Given a $max_mult of 3.0, the value of $adjusted_scale
977             #    will be 0.4, meaning that the average badge value will be
978             #    multiplied by 0.4 rather than 0.2, then added to 1.0 and
979             #    used as a multiplier against the base relevance. Thus a
980             #    change of as much as 200% to (or three times the size of)
981             #    the base relevance for a record with a 5.0 average badge
982             #    score.  This in turn will cause badges to outweigh
983             #    relevance to a very large degree.
984             #
985             # The maximum badge multiplier can be set to a value less than
986             # 1.0; this would have the effect of making less popular items
987             # show up higher in the results.  While this is not a likely
988             # option for production use, it could be useful for identifying
989             # interesting long-tail hits, particularly in a database
990             # where enough badges are configured so that very few records
991             # have an overage badge score of zero.
992
993             my $adjusted_scale = ( $max_mult - 1.0 ) / 5.0;
994             $rank = "1.0/(( $rel ) * (1.0 + (AVG(COALESCE(pop_with.total_score::NUMERIC,0.0::NUMERIC)) * ${adjusted_scale}::NUMERIC)))::NUMERIC";
995         }
996     } elsif ($sort_filter =~ /^pop/) {
997         $rank = '1.0/(AVG(COALESCE(pop_with.total_score::NUMERIC,0.0::NUMERIC)) + 5.0::NUMERIC)::NUMERIC';
998         my $pop_desc = $desc eq 'ASC' ? 'DESC' : 'ASC';
999         $pop_extra_sort = "3 $pop_desc $nullpos,";
1000     } else {
1001         # default to rel ranking
1002         $rank = "1.0/($rel)::NUMERIC";
1003     }
1004
1005     my $key = 'm.source';
1006     $key = 'm.metarecord' if (grep {$_->name eq 'metarecord' or $_->name eq 'metabib'} @{$self->modifiers});
1007
1008     my $core_limit = $self->QueryParser->core_limit || 'NULL';
1009     if ($self->find_modifier('lucky')) {
1010         $filters{check_limit} = 1;
1011         $filters{skip_check} = 0;
1012         $core_limit = 1;
1013     }
1014
1015
1016     my $flat_where = $$flat_plan{where};
1017     if ($flat_where ne '') {
1018         $flat_where = "AND (\n" . ${spc} x 5 . $flat_where . "\n" . ${spc} x 4 . ")";
1019     }
1020
1021     my $final_c_attr_test;
1022     my $c_attr_join = '';
1023     my $c_vis_test = '';
1024     my $pc_vis_test = '';
1025
1026     # copy visibility testing
1027     if (!$self->find_modifier('staff')) {
1028         $pc_vis_test = "c_attrs";
1029         $c_attr_join = ",c_attr"
1030     }
1031
1032     if ($self->find_modifier('available')) {
1033         push @{$$flat_plan{vis_filter}{'c_attr'}},
1034             "search.calculate_visibility_attribute_test('status','{0,7,12}')";
1035     }
1036
1037     if (@{$$flat_plan{vis_filter}{c_attr}}) {
1038         $c_vis_test = join(",",@{$$flat_plan{vis_filter}{c_attr}});
1039         $c_attr_join = ',c_attr';
1040     }
1041
1042     if ($c_vis_test or $pc_vis_test) {
1043         my $vis_test = '';
1044
1045         if ($c_vis_test and $pc_vis_test) {
1046             $vis_test = $pc_vis_test . ",". $c_vis_test;
1047         } elsif ($pc_vis_test) {
1048             $vis_test = $pc_vis_test;
1049         } else {
1050             $vis_test = $c_vis_test;
1051         }
1052
1053         # WITH-clause just generates vis test
1054         $$flat_plan{with} .= "\n," if $$flat_plan{with};
1055         $$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)";
1056
1057         $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)';
1058     }
1059  
1060     if ($self->find_modifier('staff')) { # staff search
1061         $final_c_attr_test ||= 'FALSE';
1062         $final_c_attr_test = '(' . $final_c_attr_test . " OR (" .
1063                 "NOT EXISTS (SELECT 1 FROM asset.copy_vis_attr_cache WHERE record = m.source) " .
1064                 "AND (bre.vis_attr_vector IS NULL OR NOT ( int4range(0,268435455,'[]') @> ANY(bre.vis_attr_vector) ))".
1065             "))";
1066         # We need bre here, regardless
1067         $bre_join ||= 'INNER JOIN biblio.record_entry bre ON m.source = bre.id AND NOT bre.deleted';
1068     }
1069
1070     my $final_b_attr_test;
1071     my $b_attr_join = '';
1072     my $b_vis_test = '';
1073     my $pb_vis_test = '';
1074
1075     # bib visibility testing
1076     if (!$self->find_modifier('staff')) {
1077         $pb_vis_test = "b_attrs";
1078         $b_attr_join = ",b_attr"
1079     }
1080
1081     if (@{$$flat_plan{vis_filter}{b_attr}}) {
1082         $b_attr_join = ',b_attr ';
1083         $b_vis_test = join("||'&'||",@{$$flat_plan{vis_filter}{b_attr}});
1084     }
1085
1086     # bib vis tests are handled a little bit differently, as they're simpler but need special handling
1087     if ($b_vis_test or $pb_vis_test) {
1088         my $vis_test = '';
1089
1090         if ($b_vis_test and $pb_vis_test) { # $pb_vis_test supplies a query_int operator at its end
1091             $vis_test = $pb_vis_test . '||'. $b_vis_test;
1092         } elsif ($pb_vis_test) { # here we want to remove it
1093             $vis_test = "RTRIM($pb_vis_test,'|&')";
1094         } else {
1095             $vis_test = $b_vis_test;
1096         }
1097
1098         # WITH-clause just generates vis test
1099         $$flat_plan{with} .= "\n," if $$flat_plan{with};
1100         $$flat_plan{with} .= "b_attr AS (SELECT ($vis_test)::query_int AS vis_test FROM asset.patron_default_visibility_mask() x)";
1101
1102         # These are magic numbers... see: search.calculate_visibility_attribute() UDF
1103         $final_b_attr_test = '(b_attr.vis_test IS NULL OR bre.vis_attr_vector @@ b_attr.vis_test)';
1104     }
1105
1106     if ($final_c_attr_test or $final_b_attr_test) { # something...
1107         if ($final_c_attr_test and $final_b_attr_test) { # both!
1108             my $plan = "($final_c_attr_test) OR ($final_b_attr_test)";
1109             $flat_where .= "\n" . ${spc} x 4 . "AND (\n" . ${spc} x 5 .  $plan .  "\n" . ${spc} x 4 . ")";
1110         } elsif ($final_c_attr_test) { # just copies...
1111             $flat_where .= "\n" . ${spc} x 4 . "AND (\n" . ${spc} x 5 .  $final_c_attr_test .  "\n" . ${spc} x 4 . ")";
1112         } else { # just bibs...
1113             $flat_where .= "\n" . ${spc} x 4 . "AND (\n" . ${spc} x 5 .  $final_b_attr_test .  "\n" . ${spc} x 4 . ")";
1114         }
1115     }
1116
1117     my $with = $$flat_plan{with};
1118     $with= "\nWITH $with" if $with;
1119
1120     # Need an array for query parser db function; this gives a better plan
1121     # than the ARRAY_AGG(DISTINCT m.source) option as of PostgreSQL 9.1
1122     my $agg_records = 'ARRAY[m.source] AS records';
1123     if ($key =~ /metarecord/) {
1124         # metarecord searches still require the ARRAY_AGG approach
1125         $agg_records = 'ARRAY_AGG(DISTINCT m.source) AS records';
1126     }
1127
1128     my $sql = <<SQL;
1129 WITH w AS (
1130
1131 $with
1132 SELECT  id,
1133         rel,
1134         CASE WHEN cardinality(records) = 1 THEN records[1] ELSE NULL END AS record,
1135         NULL::INT AS total,
1136         NULL::INT AS checked,
1137         NULL::INT AS visible,
1138         NULL::INT AS deleted,
1139         NULL::INT AS excluded,
1140         badges,
1141         popularity
1142   FROM  (SELECT $key AS id,
1143                 $agg_records,
1144                 ${rel}::NUMERIC AS rel,
1145                 $rank AS rank, 
1146                 FIRST(pubdate_t.value) AS tie_break,
1147                 STRING_AGG(ARRAY_TO_STRING(pop_with.badges,','),',') AS badges,
1148                 AVG(COALESCE(pop_with.total_score::NUMERIC,0.0::NUMERIC))::NUMERIC(2,1) AS popularity
1149           FROM  metabib.metarecord_source_map m
1150                 $$flat_plan{from}
1151                 $mra_join
1152                 $mrv_join
1153                 $bre_join
1154                 $pop_join
1155                 $pubdate_join
1156                 $lang_join
1157                 $c_attr_join
1158                 $b_attr_join
1159           WHERE 1=1
1160                 $flat_where
1161           GROUP BY 1
1162           ORDER BY 4 $desc $nullpos, $pop_extra_sort 5 DESC $nullpos, 3 DESC
1163           LIMIT $core_limit
1164         ) AS core_query
1165 ) (SELECT * FROM w LIMIT $filters{check_limit} OFFSET $filters{skip_check})
1166         UNION ALL
1167   SELECT NULL,NULL,NULL,COUNT(*),COUNT(*),COUNT(*),0,0,NULL,NULL FROM w;
1168 SQL
1169
1170     warn $sql if $self->QueryParser->debug;
1171     return $sql;
1172
1173 }
1174
1175 sub is_org_visible {
1176     my $org = shift;
1177     return 0 if (!$U->is_true($org->opac_visible));
1178
1179     my $non_inherited_vis_gf = shift || $U->get_global_flag('opac.org_unit.non_inherited_visibility');
1180     return 1 if ($U->is_true($non_inherited_vis_gf->enabled));
1181
1182     my $ot = $U->get_org_tree;
1183     while ($org = $U->find_org($ot,$org->parent_ou)) {
1184         return 0 if (!$U->is_true($org->opac_visible));
1185     }
1186     return 1;
1187 }
1188
1189 sub flatten {
1190     my $self = shift;
1191
1192     die 'ERROR: nesting too deep or boolean list too long' if ($self->plan_level > 40);
1193
1194     my $from = shift || '';
1195     my $where = shift || '';
1196     my $with = '';
1197     my %vis_filter = ( c_attr => [], b_attr => [] );
1198     my $uses_bre = 0;
1199     my $uses_mrd = 0;
1200     my $uses_mrv = 0;
1201
1202     my @rank_list;
1203     for my $node ( @{$self->query_nodes} ) {
1204
1205         if (ref($node)) {
1206             if ($node->isa( 'QueryParser::query_plan::node' )) {
1207
1208                 unless (@{$node->only_atoms}) {
1209                     push @rank_list, '1';
1210                     $where .= 'TRUE';
1211                     next;
1212                 }
1213
1214                 my @bump_fields;
1215                 my @field_ids;
1216                 if (@{$node->fields} > 0) {
1217                     @bump_fields = @{$node->fields};
1218
1219                     @field_ids = grep defined, (
1220                         map {
1221                             $self->QueryParser->search_field_ids_by_class(
1222                                 $node->classname, $_
1223                             )->[0]
1224                         } @bump_fields
1225                     );
1226                 } else {
1227                     @bump_fields = @{$self->QueryParser->search_fields->{$node->classname}};
1228                 }
1229
1230                 # use search_field_list to handle virtual index defs
1231                 my $search_field_list = $self->QueryParser->search_field_ids_by_class($node->classname);
1232                 $search_field_list = [@field_ids] if (@field_ids);
1233
1234                 my $table = $node->table;
1235                 my $ctable = $node->combined_table;
1236                 my $talias = $node->table_alias;
1237
1238                 my $node_rank = 'COALESCE(' . $node->rank . " * ${talias}.weight * 1000, 0.0)";
1239
1240                 $from .= "\n" . ${spc} x 4 ."LEFT JOIN (\n"
1241                       . ${spc} x 5 . "SELECT fe.*, fe_weight.weight, ${talias}_xq.tsq, ${talias}_xq.tsq_rank /* search */\n"
1242                       . ${spc} x 6 . "FROM  $table AS fe\n"
1243                       . ${spc} x 7 . "JOIN config.metabib_field AS fe_weight ON (fe_weight.id = fe.field)";
1244
1245                 if ($node->dummy_count < @{$node->only_atoms} ) {
1246                     $with .= ",\n     " if $with;
1247                     $with .= "${talias}_xq AS (SELECT ". $node->tsquery ." AS tsq,". $node->tsquery_rank ." AS tsq_rank )";
1248                     if ($node->combined_search) {
1249                         $from .= "\n" . ${spc} x 7 . "JOIN $ctable AS com ON (com.record = fe.source";
1250                         if (@field_ids) {
1251                             $from .= " AND com.metabib_field IN (" . join(',',@field_ids) . "))";
1252                         } else {
1253                             $from .= " AND com.metabib_field IS NULL)";
1254                         }
1255                         $from .= "\n" . ${spc} x 7 . "JOIN ${talias}_xq ON (com.index_vector @@ ${talias}_xq.tsq)";
1256                     } else {
1257                         $from .= "\n" . ${spc} x 7 . "JOIN ${talias}_xq ON (fe.index_vector @@ ${talias}_xq.tsq)";
1258                     }
1259                 } else {
1260                     $from .= "\n" . ${spc} x 7 . ", (SELECT NULL::tsquery AS tsq, NULL::tsquery AS tsq_rank ) AS ${talias}_xq";
1261                 }
1262
1263                 if (@field_ids) {
1264                     $from .= "\n" . ${spc} x 6 . "WHERE fe_weight.id IN  (" .
1265                         join(',', @field_ids) . ")";
1266                 }
1267
1268                 # Even though virtual fields have all the real field data in
1269                 # their combined version, and thus a search against the real
1270                 # fields is not necessary to match records, we still want to
1271                 # UNION them in so we can get their virtual weight if they
1272                 # would match a search directly against them.
1273                 if ($node->dummy_count < @{$node->only_atoms} ) { # no point in searching real fields with no search terms
1274                     for my $possible_vfield (@$search_field_list) {
1275                         my $real_fields = $self->QueryParser->search_field_virtual_map->{by_virt}->{$possible_vfield};
1276                         if ($real_fields and @$real_fields) { # this is a virt field
1277                             my %vtable_field_map;
1278
1279                             # UNION in the others ... group by class
1280                             for my $real_field (@$real_fields) {
1281                                 my $natural_field = $self->QueryParser->search_field_id_map->{by_id}{$$real_field{real}};
1282
1283                                 $node->add_vfield($$real_field{real});
1284                                 $logger->debug("Looking up virtual field for real field $$real_field{real}");
1285                                 my $vtable = $node->table(
1286                                     $self->QueryParser
1287                                         ->search_field_class_by_id($$real_field{real})
1288                                         ->{classname}
1289                                 );
1290                                 $vtable_field_map{$vtable} ||= [];
1291                                 push(@{$vtable_field_map{$vtable}}, $$real_field{real})
1292                                     if ($$real_field{weight} != $$natural_field{weight});
1293                             }
1294
1295                             for my $vtable (keys %vtable_field_map) {
1296                                 my $rfields = $vtable_field_map{$vtable};
1297                                 next unless (@$rfields);
1298
1299                                 # NOTE: only real fields that match the (component) tsquery will
1300                                 #       get to contribute to and increased rank for the record.
1301                                 $from .= "\n" . ${spc} x 8 . "UNION ALL\n"
1302                                       . ${spc} x 5 . "SELECT fe.id, fe.source, fe.field, fe.value, fe.index_vector, "
1303                                       . "fe_weight.weight, ${talias}_xq.tsq, ${talias}_xq.tsq_rank /* virtual field addition */\n"
1304                                       . ${spc} x 6 . "FROM  $vtable AS fe\n"
1305                                       . ${spc} x 7 . "JOIN config.metabib_field_virtual_map AS fe_weight ON ("
1306                                             ."fe_weight.virtual = $possible_vfield AND "
1307                                             ."fe_weight.real IN (".join(',',@$rfields).") AND "
1308                                             ."fe_weight.real = fe.field)\n"
1309                                       . ${spc} x 7 . "JOIN ${talias}_xq ON (fe.index_vector @@ ${talias}_xq.tsq)"
1310                                 ;
1311                             }
1312                         }
1313                     }
1314                 }
1315
1316                 $from .= "\n" . ${spc} x 4 . ") AS $talias ON (m.source = ${talias}.source)";
1317
1318                 my %used_bumps;
1319                 my @bumps;
1320                 my @bumpmults;
1321                 for my $field ( @bump_fields ) {
1322                     my $bumps = $self->QueryParser->find_relevance_bumps( $node->classname => $field );
1323                     for my $b (keys %$bumps) {
1324                         next if (!$$bumps{$b}{active});
1325                         next if ($used_bumps{$b});
1326                         $used_bumps{$b} = 1;
1327
1328                         next if ($$bumps{$b}{multiplier} == 1); # optimization to remove unneeded bumps
1329                         push @bumps, $b;
1330                         push @bumpmults, $$bumps{$b}{multiplier};
1331                     }
1332                 }
1333
1334                 if(scalar @bumps > 0 && scalar @{$node->only_positive_atoms} > 0) {
1335                     # Note: Previous rank function used search_normalize outright. Duplicating that here.
1336                     $node_rank .= "\n" . ${spc} x 5 . "* COALESCE(evergreen.rel_bump(('{' || quote_literal(search_normalize(";
1337                     $node_rank .= join(")) || ',' || quote_literal(search_normalize(",map { $self->QueryParser->quote_phrase_value($_->content) } @{$node->only_positive_atoms});
1338                     $node_rank .= ")) || '}')::TEXT[], " . $node->table_alias . ".value, '{" . join(",",@bumps) . "}'::TEXT[], '{" . join(",",@bumpmults) . "}'::NUMERIC[]),1.0)";
1339                 }
1340
1341                 my $NOT = '';
1342                 $NOT = 'NOT ' if $node->negate;
1343
1344                 $where .= "$NOT(" . $talias . ".id IS NOT NULL";
1345                 if (@{$node->phrases}) {
1346                     $where .= ' AND ' . join(' AND ', map {
1347                         "${talias}.value ~* ".$self->QueryParser->quote_phrase_value($_, 1)
1348                     } @{$node->phrases});
1349                 } else {
1350                     for my $atom (@{$node->only_real_atoms}) {
1351                         next unless $atom->{content} && $atom->{content} =~ /(^\^|\$$)/;
1352                         $where .= " AND ${talias}.value ~* ".$self->QueryParser->quote_phrase_value($atom->{content});
1353                     }
1354                 }
1355                 $where .= ')';
1356
1357                 push @rank_list, $node_rank;
1358
1359             } elsif ($node->isa( 'QueryParser::query_plan::facet' )) {
1360
1361                 my $talias = $node->table_alias;
1362
1363                 my @field_ids;
1364                 if (@{$node->fields} > 0) {
1365                     push(@field_ids, $self->QueryParser->facet_field_ids_by_class( $node->classname, $_ )->[0]) for (@{$node->fields});
1366                 } else {
1367                     @field_ids = @{ $self->QueryParser->facet_field_ids_by_class( $node->classname ) };
1368                 }
1369
1370                 my $join_type = ($node->negate or !$self->top_plan) ? 'LEFT' : 'INNER';
1371                 $from .= "\n${spc}$join_type JOIN /* facet */ metabib.facet_entry $talias ON (\n"
1372                       . ${spc} x 2 . "m.source = ${talias}.source\n"
1373                       . ${spc} x 2 . "AND SUBSTRING(${talias}.value,1,1024) IN ("
1374                       . join(",", map { $self->QueryParser->quote_value($_) } @{$node->values}) . ")\n"
1375                       . ${spc} x 2 ."AND ${talias}.field IN (". join(',', @field_ids) . ")\n"
1376                       . "${spc})";
1377
1378                 if ($join_type ne 'INNER') {
1379                     my $NOT = $node->negate ? '' : ' NOT';
1380                     $where .= "${talias}.id IS$NOT NULL";
1381                 } elsif ($where ne '') {
1382                     # Strip extra joiner
1383                     $where =~ s/(\s|\n)+(AND|OR)\s$//;
1384                 }
1385
1386             } else {
1387                 my $subnode = $node->flatten;
1388
1389                 # strip the trailing bool from the previous loop if there is 
1390                 # nothing to add to the where within this loop.
1391                 if ($$subnode{where} eq '') {
1392                     $where =~ s/(\s|\n)+(AND|OR)\s$//;
1393                 }
1394
1395                 push(@rank_list, @{$$subnode{rank_list}});
1396                 $from .= $$subnode{from};
1397
1398                 my $NOT = '';
1399                 $NOT = 'NOT ' if $node->negate;
1400
1401                 if ($$subnode{where} ne '') {
1402                     $where .= "$NOT(\n"
1403                            . ${spc} x ($self->plan_level + 6) . $$subnode{where} . "\n"
1404                            . ${spc} x ($self->plan_level + 5) . ')';
1405                 }
1406
1407                 if ($$subnode{with}) {
1408                     $with .= ",\n     " if $with;
1409                     $with .= $$subnode{with};
1410                 }
1411
1412                 $uses_bre = $$subnode{uses_bre};
1413                 $uses_mrd = $$subnode{uses_mrd};
1414                 $uses_mrv = $$subnode{uses_mrv};
1415             }
1416         } else {
1417
1418             warn "flatten(): appending WHERE bool to: $where\n" if $self->QueryParser->debug;
1419
1420             if ($where ne '') {
1421                 $where .= "\n" . ${spc} x ( $self->plan_level + 5 ) . 'AND ' if ($node eq '&');
1422                 $where .= "\n" . ${spc} x ( $self->plan_level + 5 ) . 'OR ' if ($node eq '|');
1423             }
1424         }
1425     }
1426
1427     my $joiner = "\n" . ${spc} x ( $self->plan_level + 5 ) . ($self->joiner eq '&' ? 'AND ' : 'OR ');
1428
1429     my ($depth_filter) = grep { $_->name eq 'depth' } @{$self->filters};
1430     if ($depth_filter and @{$depth_filter->args} == 1) {
1431         $depth_filter = $depth_filter->args->[0];
1432     }
1433
1434     my $ot = $U->get_org_tree;
1435     my $site_org = $ot;
1436     my $negate = 'FALSE';
1437
1438     my ($site_filter) = grep { $_->name eq 'site' } @{$self->filters};
1439     if ($site_filter and @{$site_filter->args} == 1) {
1440        $negate = $site_filter->negate ? 'TRUE' : 'FALSE';
1441
1442        my $sitename = $site_filter->args->[0];
1443        $site_org = $U->find_org_by_shortname($ot, $sitename) || $ot;
1444     }
1445
1446     my $dorgs = $U->get_org_descendants($site_org->id, $depth_filter);
1447     my $aorgs = $U->get_org_ancestors($site_org->id);
1448
1449     if (!$self->find_modifier('staff')) {
1450         my $non_inherited_vis_gf = $U->get_global_flag('opac.org_unit.non_inherited_visibility');
1451         $dorgs = [ grep { is_org_visible($U->find_org($ot,$_), $non_inherited_vis_gf) } @$dorgs ];
1452         $aorgs = [ grep { is_org_visible($U->find_org($ot,$_), $non_inherited_vis_gf) } @$aorgs ];
1453     }
1454
1455     push @{$vis_filter{'c_attr'}},
1456         "search.calculate_visibility_attribute_test('circ_lib','{".join(',', @$dorgs)."}',$negate)";
1457
1458     if (!$self->find_filter('locations') && !$self->find_filter('location_groups')) {
1459         my $lorgs = [@$aorgs];
1460         my $luri_as_copy_gf = $U->get_global_flag('opac.located_uri.act_as_copy');
1461         push @$lorgs, @$dorgs if ($luri_as_copy_gf and $U->is_true($luri_as_copy_gf->enabled));
1462
1463         $uses_bre = 1;
1464         push @{$vis_filter{'b_attr'}},
1465             "search.calculate_visibility_attribute_test('luri_org','{".join(',', @$lorgs)."}',$negate)";
1466     }
1467
1468     my @dlist = ();
1469     my $common = 0;
1470     # for each dynamic filter, build more of the WHERE clause
1471     for my $filter (@{$self->filters}) {
1472         my $NOT = $filter->negate ? 'NOT ' : '';
1473         if (grep { $_ eq $filter->name } @{ $self->QueryParser->dynamic_filters }) {
1474
1475             my $fname = $filter->name;
1476             $fname = 'item_lang' if $fname eq 'language'; #XXX filter aliases 
1477
1478             warn "flatten(): processing dynamic filter ". $filter->name ."\n"
1479                 if $self->QueryParser->debug;
1480
1481             my $vlist_query;
1482             ($vlist_query, $common) = $self->dynamic_filter_compile( $fname, $filter->args, $filter->negate );
1483
1484             # bool joiner for intra-plan nodes/filters
1485             push(@dlist, $self->joiner) if @dlist;
1486             push(@dlist, $vlist_query);
1487             $uses_mrv = 1;
1488         } else {
1489             if ($filter->name eq 'before') {
1490                 if (@{$filter->args} == 1) {
1491                     $where .= $joiner if $where ne '';
1492                     $where .= "${NOT}COALESCE(pubdate_t.value <= "
1493                            . $self->QueryParser->quote_value($filter->args->[0])
1494                            . ", false)";
1495                 }
1496             } elsif ($filter->name eq 'after') {
1497                 if (@{$filter->args} == 1) {
1498                     $where .= $joiner if $where ne '';
1499                     $where .= "${NOT}COALESCE(pubdate_t.value >= "
1500                            . $self->QueryParser->quote_value($filter->args->[0])
1501                            . ", false)";
1502                 }
1503             } elsif ($filter->name eq 'during') {
1504                 if (@{$filter->args} == 1) {
1505                     $where .= $joiner if $where ne '';
1506                     $where .= "${NOT}COALESCE("
1507                            . $self->QueryParser->quote_value($filter->args->[0])
1508                            . " BETWEEN pubdate_t.value AND (mrd.attrs->'date2'), false)";
1509                     $uses_mrd = 1;
1510                 }
1511             } elsif ($filter->name eq 'between') {
1512                 if (@{$filter->args} == 2) {
1513                     $where .= $joiner if $where ne '';
1514                     $where .= "${NOT}COALESCE(pubdate_t.value BETWEEN "
1515                            . $self->QueryParser->quote_value($filter->args->[0])
1516                            . " AND "
1517                            . $self->QueryParser->quote_value($filter->args->[1])
1518                            . ", false)";
1519                 }
1520             } elsif ($filter->name eq 'container') {
1521                 if (@{$filter->args} >= 3) {
1522                     my ($class, $ctype, $cid, $token) = @{$filter->args};
1523                     my $perm_join = '';
1524                     my $rec_join = '';
1525                     my $rec_field = 'ci.target_biblio_record_entry';
1526                     if ($class eq 'bre') {
1527                         $class = 'biblio_record_entry';
1528                     } elsif ($class eq 'acn') {
1529                         $class = 'call_number';
1530                         $rec_field = 'cn.record';
1531                         $rec_join = 'JOIN asset.call_number cn ON (ci.target_call_number = cn.id)';
1532                     } elsif ($class eq 'acp') {
1533                         $class = 'copy';
1534                         $rec_field = 'cn.record';
1535                         $rec_join = 'JOIN asset.copy cp ON (ci.target_copy = cp.id) JOIN asset.call_number cn ON (cp.call_number = cn.id)';
1536                     } else {
1537                         $class = undef;
1538                     }
1539
1540                     if ($class) {
1541                         my ($u,$e) = $apputils->checksesperm($token) if ($token);
1542                         $perm_join = ' OR c.owner = ' . $u->id if ($u && !$e);
1543
1544                         my $filter_alias = "$filter";
1545                         $filter_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1546                         $filter_alias =~ s/\|/_/go;
1547
1548                         $with .= ",\n     " if $with;
1549                         $with .= "container_${filter_alias} AS (\n";
1550                         $with .= "       SELECT $rec_field AS record FROM container.${class}_bucket_item ci\n"
1551                                . "             JOIN container.${class}_bucket c ON (c.id = ci.bucket) $rec_join\n"
1552                                . "       WHERE c.btype = " . $self->QueryParser->quote_value($ctype) . "\n"
1553                                . "             AND c.id = " . $self->QueryParser->quote_value($cid) . "\n"
1554                                . "             AND (c.pub IS TRUE$perm_join)\n";
1555                         if ($class eq 'copy') {
1556                             $with .= "       UNION\n"
1557                                    . "       SELECT pr.peer_record AS record FROM container.copy_bucket_item ci\n"
1558                                    . "             JOIN container.copy_bucket c ON (c.id = ci.bucket)\n"
1559                                    . "             JOIN biblio.peer_bib_copy_map pr ON ci.target_copy = pr.target_copy\n"
1560                                    . "       WHERE c.btype = " . $self->QueryParser->quote_value($ctype) . "\n"
1561                                    . "             AND c.id = " . $self->QueryParser->quote_value($cid) . "\n"
1562                                    . "             AND (c.pub IS TRUE$perm_join)\n";
1563                         }
1564                         $with .= "     )";
1565
1566                         my $optimize_join = 1 if $self->top_plan and !$NOT;
1567                         $from .= "\n" . ${spc} x 3 . ( $optimize_join ? 'INNER' : 'LEFT') . " JOIN container_${filter_alias} ON container_${filter_alias}.record = m.source";
1568
1569                         if (!$optimize_join) {
1570                             $where .= $joiner if $where ne '';
1571                             $where .= "(container_${filter_alias} IS " . ( $NOT ? 'NULL)' : 'NOT NULL)');
1572                         }
1573                     }
1574                 }
1575             } elsif ($filter->name eq 'copy_tag') {
1576                 my $valid_copy_tag_search = 0;
1577                 my $copy_tag_type;
1578                 my $tag_value;
1579                 if (@{$filter->args} >= 2) { # must have at least two parts, tag (or *) and terms
1580                     my @fargs = @{$filter->args};
1581                     $copy_tag_type = shift(@fargs);
1582                     $tag_value = join(' ', @fargs);
1583                     $valid_copy_tag_search = 1;
1584                 }
1585                 if ($valid_copy_tag_search) {
1586                     my $norm_value = search_normalize($tag_value);
1587                     my @tokens = split /\s+/, $norm_value;
1588                     
1589                     my $filter_alias = "$filter";
1590                     $filter_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1591                     $filter_alias =~ s/\|/_/go;
1592
1593                     $with .= ",\n     " if $with;
1594                     $with .= "copy_tag_${filter_alias} AS (\n";
1595                     $with .= "       SELECT cn.record AS record FROM config.copy_tag_type cctt\n";
1596                     $with .= "             JOIN asset.copy_tag acpt ON (cctt.code = acpt.tag_type)\n";
1597                     $with .= "             JOIN asset.copy_tag_copy_map acptcm ON (acpt.id = acptcm.tag)\n";
1598                     $with .= "             JOIN asset.copy cp ON (acptcm.copy = cp.id)\n";
1599                     $with .= "             JOIN asset.call_number cn ON (cp.call_number = cn.id)\n";
1600                     $with .= "       WHERE 1 = 1 \n";
1601                     $with .= "       AND cp.circ_lib IN (" . join(',', @$dorgs) . ")\n";
1602                     if ($copy_tag_type ne '*') {
1603                         $with .= "             AND cctt.code = " . $self->QueryParser->quote_value($copy_tag_type) . "\n";
1604                     }
1605                     if (@tokens) {
1606                         $with .= '             AND acpt.value @@ to_tsquery(' . $self->QueryParser->quote_value(join(' & ', @tokens)) . ")\n";
1607                     }
1608                     if (!$self->find_modifier('staff')) {
1609                         $with .= "             AND acpt.pub IS TRUE\n";
1610                     }
1611                     $with .= "     )";
1612
1613                     my $optimize_join = 1 if $self->top_plan and !$NOT;
1614                     $from .= "\n" . ${spc} x 3 . ( $optimize_join ? 'INNER' : 'LEFT') . " JOIN copy_tag_${filter_alias} ON copy_tag_${filter_alias}.record = m.source";
1615
1616                     if (!$optimize_join) {
1617                         $where .= $joiner if $where ne '';
1618                         $where .= "(copy_tag_${filter_alias} IS " . ( $NOT ? 'NULL)' : 'NOT NULL)');
1619                     }
1620                 }
1621             } elsif ($filter->name eq 'record_list') {
1622                 if (@{$filter->args} > 0) {
1623                     my $key = 'm.source';
1624                     $key = 'm.metarecord' if (grep {$_->name eq 'metarecord' or $_->name eq 'metabib'} @{$self->QueryParser->parse_tree->modifiers});
1625                     $where .= $joiner if $where ne '';
1626                     $where .= "$key ${NOT}IN (" . join(',', map { $self->QueryParser->quote_value($_) } @{$filter->args}) . ')';
1627                 }
1628
1629             } elsif ($filter->name eq 'locations') {
1630                 if (@{$filter->args} > 0) {
1631                     my $negate = $filter->negate ? 'TRUE' : 'FALSE';
1632                     my $filter_args = join(",", map(int, @{$filter->args}));
1633                     push @{$vis_filter{'c_attr'}},
1634                         "search.calculate_visibility_attribute_test('location','{$filter_args}',$negate)";
1635                 }
1636
1637             } elsif ($filter->name eq 'location_groups') {
1638                 if (@{$filter->args} > 0) {
1639                     my $negate = $filter->negate ? 'TRUE' : 'FALSE';
1640                     my $filter_args = join(",", map(int, @{$filter->args}));
1641                     push @{$vis_filter{'c_attr'}},
1642                         "search.calculate_visibility_attribute_test('location',(SELECT ARRAY_AGG(location) FROM asset.copy_location_group_map WHERE lgroup IN ($filter_args)),$negate)";
1643                 }
1644
1645             } elsif ($filter->name eq 'statuses') {
1646                 if (@{$filter->args} > 0) {
1647                     my $negate = $filter->negate ? 'TRUE' : 'FALSE';
1648                     push @{$vis_filter{'c_attr'}},
1649                         "search.calculate_visibility_attribute_test('status','{".join(',', @{$filter->args})."}',$negate)";
1650                 }
1651
1652             } elsif ($filter->name eq 'has_browse_entry') {
1653                 if (@{$filter->args} >= 2) {
1654                     my $entry = int(shift @{$filter->args});
1655                     my $fields = join(",", map(int, @{$filter->args}));
1656                     $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);
1657                 }
1658             } elsif ($filter->name eq 'edit_date' or $filter->name eq 'create_date') {
1659                 # bre.create_date and bre.edit_date filtering
1660                 my $datefilter = $filter->name;
1661
1662                 $uses_bre = 1;
1663
1664                 if ($filter && $filter->args && scalar(@{$filter->args}) > 0 && scalar(@{$filter->args}) < 3) {
1665                     my ($cstart, $cend) = @{$filter->args};
1666         
1667                     if (!$cstart and !$cend) {
1668                         # useless use of filter
1669                     } elsif (!$cstart or $cstart eq '-infinity') { # no start supplied
1670                         if ($cend eq 'infinity') {
1671                             # useless use of filter
1672                         } else {
1673                             # "before $cend"
1674                             $cend = clean_ISO8601($cend);
1675                             $where .= $joiner if $where ne '';
1676                             $where .= "bre.$datefilter <= \$_$$\$$cend\$_$$\$";
1677                         }
1678             
1679                     } elsif (!$cend or $cend eq 'infinity') { # no end supplied
1680                         if ($cstart eq '-infinity') {
1681                             # useless use of filter
1682                         } else { # "after $cstart"
1683                             $cstart = clean_ISO8601($cstart);
1684                             $where .= $joiner if $where ne '';
1685                             $where .= "bre.$datefilter >= \$_$$\$$cstart\$_$$\$";
1686                         }
1687                     } else { # both supplied
1688                         # "between $cstart and $cend"
1689                         $cstart = clean_ISO8601($cstart);
1690                         $cend = clean_ISO8601($cend);
1691                         $where .= $joiner if $where ne '';
1692                         $where .= "bre.$datefilter BETWEEN \$_$$\$$cstart\$_$$\$ AND \$_$$\$$cend\$_$$\$";
1693                     }
1694                 }
1695             } elsif ($filter->name eq 'bib_source') {
1696                 if (@{$filter->args} > 0) {
1697                     $uses_bre = 1;
1698                     my $negate = $filter->negate ? 'TRUE' : 'FALSE';
1699                     push @{$vis_filter{'b_attr'}},
1700                         "search.calculate_visibility_attribute_test('source','{".join(',', @{$filter->args})."}',$negate)";
1701                 }
1702             } elsif ($filter->name eq 'from_metarecord') {
1703                 if (@{$filter->args} > 0) {
1704                     my $key = 'm.metarecord';
1705                     $where .= $joiner if $where ne '';
1706                     $where .= "$key ${NOT}IN (" . join(',', map { $self->QueryParser->quote_value($_) } @{$filter->args}) . ')';
1707                 }
1708             }
1709         }
1710     }
1711
1712     if (@dlist) {
1713
1714         $where .= $joiner if $where ne '';
1715         if ($common) { # Use a function wrapper to inform PG of the non-rareness of one or more filter elements
1716             $where .= sprintf(
1717                 'evergreen.query_int_wrapper(mrv.vlist, \'%s\')',
1718                 join('', @dlist)
1719             );
1720         } else {
1721             $where .= sprintf(
1722                 'mrv.vlist @@ \'%s\'',
1723                 join('', @dlist)
1724             );
1725         }
1726     }
1727
1728     warn "flatten(): full filter where => $where\n" if $self->QueryParser->debug;
1729
1730     return {
1731         rank_list => \@rank_list,
1732         from => $from,
1733         where => $where,
1734         with => $with,
1735         vis_filter => \%vis_filter,
1736         uses_bre => $uses_bre,
1737         uses_mrv => $uses_mrv,
1738         uses_mrd => $uses_mrd
1739     };
1740 }
1741
1742
1743 #-------------------------------
1744 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::filter;
1745 use base 'QueryParser::query_plan::filter';
1746
1747 #-------------------------------
1748 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::facet;
1749 use base 'QueryParser::query_plan::facet';
1750
1751 sub classname {
1752     my $self = shift;
1753     my ($classname) = split '\|', $self->name;
1754     return $classname;
1755 }
1756
1757 sub fields {
1758     my $self = shift;
1759     my ($classname,@fields) = split '\|', $self->name;
1760     return \@fields;
1761 }
1762
1763 sub table_alias {
1764     my $self = shift;
1765     my $suffix = shift;
1766
1767     my $table_alias = "$self";
1768     $table_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1769     $table_alias .= '_' . $self->name;
1770     $table_alias =~ s/\|/_/go;
1771     $table_alias .= "_$suffix" if ($suffix);
1772
1773     return $table_alias;
1774 }
1775
1776
1777 #-------------------------------
1778 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::modifier;
1779 use base 'QueryParser::query_plan::modifier';
1780
1781 #-------------------------------
1782 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::node::atom;
1783 use base 'QueryParser::query_plan::node::atom';
1784
1785 sub sql {
1786     my $self = shift;
1787     my $sql = shift;
1788
1789     $self->{sql} = $sql if ($sql);
1790
1791     return $self->{sql} if ($self->{sql});
1792     return $self->buildSQL;
1793 }
1794
1795 sub buildSQL {
1796     my $self = shift;
1797
1798     my $classname = $self->node->classname;
1799
1800     return $self->sql("to_tsquery('$classname','')") if $self->{dummy};
1801
1802     my $normalizers = $self->node->plan->QueryParser->query_normalizers( $classname );
1803     my $fields = $self->node->fields;
1804
1805     my $lang;
1806     my $filter = $self->node->plan->find_filter('preferred_language');
1807     $lang ||= $filter->args->[0] if ($filter && $filter->args);
1808     $lang ||= $self->node->plan->QueryParser->default_preferred_language;
1809     my $ts_configs = [];
1810
1811     if (!@$fields) {
1812         $ts_configs = $self->node->plan->QueryParser->class_ts_config($classname, $lang);
1813     } else {
1814         for my $field (@$fields) {
1815             push @$ts_configs, @{$self->node->plan->QueryParser->field_ts_config($classname, $field, $lang)};
1816         }
1817     }
1818     $ts_configs = [keys %{{map { $_ => 1 } @$ts_configs}}];
1819
1820     # Assume we want exact if none otherwise provided.
1821     # Because we can reasonably expect this to exist
1822     $ts_configs = ['simple'] unless (scalar @$ts_configs);
1823
1824     $fields = $self->node->plan->QueryParser->search_fields->{$classname} if (!@$fields);
1825
1826     my %norms;
1827     my $pos = 0;
1828     for my $field (@$fields) {
1829         for my $nfield (keys %$normalizers) {
1830             for my $nizer ( @{$$normalizers{$nfield}} ) {
1831                 if ($field eq $nfield) {
1832                     my $param_string = OpenSRF::Utils::JSON->perl2JSON($nizer->{params});
1833                     if (!exists($norms{$nizer->{function}.$param_string})) {
1834                         $norms{$nizer->{function}.$param_string} = {p=>$pos++,n=>$nizer};
1835                     }
1836                 }
1837             }
1838         }
1839     }
1840
1841     my $sql = $self->node->plan->QueryParser->quote_value($self->content);
1842
1843     for my $n ( map { $$_{n} } sort { $$a{p} <=> $$b{p} } values %norms ) {
1844         $sql = join(', ', $sql, map { $self->node->plan->QueryParser->quote_value($_) } @{ $n->{params} });
1845         $sql = $n->{function}."($sql)";
1846     }
1847
1848     my $prefix = $self->prefix || '';
1849     my $suffix = $self->suffix || '';
1850     my $joiner = ' || ';
1851     $joiner = ' && ' if $self->prefix eq '!'; # Negative atoms should be "none of the variants" instead of "any of the variants"
1852
1853     $prefix = "'$prefix' ||" if $prefix;
1854     my $suffix_op = '';
1855     my $suffix_after = '';
1856
1857     $suffix_op = ":$suffix" if $suffix;
1858     $suffix_after = "|| '$suffix_op'" if $suffix;
1859
1860     my @sql_set = ();
1861     for my $ts_config (@$ts_configs) {
1862         push @sql_set, "to_tsquery('$ts_config', COALESCE(NULLIF($prefix '(' || btrim(regexp_replace($sql,E'(?:\\\\s+|:)','$suffix_op&','g'),'&|') $suffix_after || ')', '()'), ''))";
1863     }
1864
1865     $sql = join($joiner, @sql_set);
1866     $sql = '(' . $sql . ')' if (scalar(@$ts_configs) > 1);
1867
1868     return $self->sql($sql);
1869 }
1870
1871 #-------------------------------
1872 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::node;
1873 use base 'QueryParser::query_plan::node';
1874 use List::MoreUtils qw/uniq/;
1875 use Data::Dumper;
1876
1877 sub abstract_node_additions {
1878     my $self = shift;
1879     my $aq = shift;
1880
1881     my $hm = $self->plan
1882                 ->QueryParser
1883                 ->parse_tree
1884                 ->get_abstract_data('highlight_map') || {};
1885
1886     my $field_set = $self->fields;
1887     $field_set = $self->plan->QueryParser->search_fields->{$self->classname}
1888         if (!@$field_set);
1889
1890     my @field_ids = grep defined, (
1891         map {
1892             $self->plan->QueryParser->search_field_ids_by_class(
1893                 $self->classname, $_
1894             )->[0]
1895         } @$field_set
1896     );
1897
1898     push @field_ids, @{$self->{vfields}} if $self->{vfields};
1899
1900     my $ts_query = $self->tsquery_rank;
1901
1902     # We need to rework the hash so fields are only ever pointed at once.
1903     # That means if a field is already being looked at elsewhere then we'll
1904     # need to separate it out and combine its preexisting tsqueries.  This
1905     # will be fairly brute-force, and could be improved later, likely, with
1906     # a clever algorithm.
1907
1908     my %inverted_hm;
1909     for my $t (keys %$hm) {
1910         for my $f (@{$$hm{$t}}) {
1911             $inverted_hm{$f} = $t;
1912         }
1913     }
1914
1915     # Then, loop over new fields and put them in the inverted hash.
1916     my @existing_fields = keys %inverted_hm;
1917
1918     for my $f (@field_ids) {
1919         if (grep { $f == $_ } @existing_fields) { # We've seen the field, should we combine?
1920             my $t = $inverted_hm{$f};
1921             if ($t ne $ts_query) { # Different tsquery, do it!
1922                 $t .= ' || '. $ts_query;
1923                 $inverted_hm{$f} = $t;
1924             }
1925         } else { # New field
1926             $inverted_hm{$f} = $ts_query;
1927         }
1928     }
1929
1930     # Now, flip it back over.
1931     $hm = {};
1932     for my $f (keys %inverted_hm) {
1933         my $t = $inverted_hm{$f};
1934         if ($$hm{$t}) {
1935             push @{$$hm{$t}}, $f;
1936         } else {
1937             $$hm{$t} = [$f];
1938         }
1939     }
1940
1941     $self->plan
1942         ->QueryParser
1943         ->parse_tree
1944         ->set_abstract_data('highlight_map', $hm);
1945 }
1946
1947 sub add_vfield {
1948     my $self = shift;
1949     my $vfield = shift;
1950
1951     $self->{vfields} ||= [];
1952     push @{$self->{vfields}}, $vfield;
1953 }
1954
1955 sub only_atoms {
1956     my $self = shift;
1957
1958     $self->{dummy_count} = 0;
1959
1960     my $atoms = $self->query_atoms;
1961     my @only_atoms;
1962     for my $a (@$atoms) {
1963         push(@only_atoms, $a) if (ref($a) && $a->isa('QueryParser::query_plan::node::atom'));
1964         $self->{dummy_count}++ if (ref($a) && $a->{dummy});
1965     }
1966
1967     return \@only_atoms;
1968 }
1969
1970 sub only_real_atoms {
1971     my $self = shift;
1972
1973     my $atoms = $self->query_atoms;
1974     my @only_real_atoms;
1975     for my $a (@$atoms) {
1976         push(@only_real_atoms, $a) if (ref($a) && $a->isa('QueryParser::query_plan::node::atom') && !($a->{dummy}));
1977     }
1978
1979     return \@only_real_atoms;
1980 }
1981
1982 sub only_positive_atoms {
1983     my $self = shift;
1984
1985     my $atoms = $self->query_atoms;
1986     my @only_positive_atoms;
1987     for my $a (@$atoms) {
1988         push(@only_positive_atoms, $a) if (ref($a) && $a->isa('QueryParser::query_plan::node::atom') && !($a->{dummy}) && ($a->{prefix} ne '!'));
1989     }
1990
1991     return \@only_positive_atoms;
1992 }
1993
1994 sub dummy_count {
1995     my $self = shift;
1996     return $self->{dummy_count};
1997 }
1998
1999 sub table {
2000     my $self = shift;
2001     my $classname = shift || $self->classname;
2002     return 'metabib.' . $classname . '_field_entry';
2003 }
2004
2005 sub combined_table {
2006     my $self = shift;
2007     my $classname = shift || $self->classname;
2008     return 'metabib.combined_' . $classname . '_field_entry';
2009 }
2010
2011 sub combined_search {
2012     my $self = shift;
2013     return $self->plan->QueryParser->search_class_combined($self->classname);
2014 }
2015
2016 sub table_alias {
2017     my $self = shift;
2018     my $suffix = shift;
2019
2020     my $table_alias = "$self";
2021     $table_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
2022     $table_alias .= '_' . $self->requested_class;
2023     $table_alias =~ s/\|/_/go;
2024     $table_alias .= "_$suffix" if ($suffix);
2025
2026     return $table_alias;
2027 }
2028
2029 sub tsquery {
2030     my $self = shift;
2031     return $self->{tsquery} if ($self->{tsquery});
2032
2033     for my $atom (@{$self->query_atoms}) {
2034         if (ref($atom)) {
2035             $self->{tsquery} .= "\n" . ${spc} x 3 . $atom->sql;
2036         } else {
2037             $self->{tsquery} .= $atom x 2;
2038         }
2039     }
2040
2041     return $self->{tsquery};
2042 }
2043
2044 sub tsquery_rank {
2045     my $self = shift;
2046     return $self->{tsquery_rank} if ($self->{tsquery_rank});
2047     my @atomlines;
2048
2049     for my $atom (@{$self->only_positive_atoms}) {
2050         push @atomlines, "\n" . ${spc} x 3 . $atom->sql;
2051     }
2052     $self->{tsquery_rank} = join(' ||', @atomlines);
2053     $self->{tsquery_rank} = "''::tsquery" unless $self->{tsquery_rank};
2054     return $self->{tsquery_rank};
2055 }
2056
2057 sub rank {
2058     my $self = shift;
2059     return $self->{rank} if ($self->{rank});
2060
2061     my $rank_norm_map = $self->plan->QueryParser->custom_data->{rank_cd_weight_map};
2062
2063     my $cover_density = 0;
2064     for my $norm ( keys %$rank_norm_map) {
2065         $cover_density += $$rank_norm_map{$norm} if ($self->plan->QueryParser->parse_tree->find_modifier($norm));
2066     }
2067
2068     my $weights = join(', ', @{$self->plan->QueryParser->search_class_weights($self->classname)});
2069
2070     return $self->{rank} = "ts_rank_cd('{" . $weights . "}', " . $self->table_alias . '.index_vector, ' . $self->table_alias . ".tsq_rank, $cover_density)";
2071 }
2072
2073
2074 1;
2075