]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Storage/Driver/Pg/QueryParser.pm
QueryParser Driver: Remove Switch usage
[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::JSON;
8 use OpenILS::Application::AppUtils;
9 use OpenILS::Utils::CStoreEditor;
10 my $U = 'OpenILS::Application::AppUtils';
11
12 my ${spc} = ' ' x 2;
13 sub subquery_callback {
14     my ($invocant, $self, $struct, $filter, $params, $negate) = @_;
15
16     return sprintf(' ((%s)) ',
17         join(
18             ') || (',
19             map {
20                 $_->query_text
21             } @{
22                 OpenILS::Utils::CStoreEditor
23                     ->new
24                     ->search_actor_search_query({ id => $params })
25             }
26         )
27     );
28 }
29
30 sub filter_group_entry_callback {
31     my ($invocant, $self, $struct, $filter, $params, $negate) = @_;
32
33     return sprintf(' saved_query(%s)', 
34         join(
35             ',', 
36             map {
37                 $_->query
38             } @{
39                 OpenILS::Utils::CStoreEditor
40                     ->new
41                     ->search_actor_search_filter_group_entry({ id => $params })
42             }
43         )
44     );
45 }
46
47 sub location_groups_callback {
48     my ($invocant, $self, $struct, $filter, $params, $negate) = @_;
49
50     return sprintf(' %slocations(%s)',
51         $negate ? '-' : '',
52         join(
53             ',',
54             map {
55                 $_->location
56             } @{
57                 OpenILS::Utils::CStoreEditor
58                     ->new
59                     ->search_asset_copy_location_group_map({ lgroup => $params })
60             }
61         )
62     );
63 }
64
65 sub format_callback {
66     my ($invocant, $self, $struct, $filter, $params, $negate) = @_;
67
68     my $return = '';
69     my $negate_flag = ($negate ? '-' : '');
70     if(@$params[0]) {
71         my ($t,$f) = split('-', @$params[0]);
72         $return .= $negate_flag .'item_type(' . join(',',split('', $t)) . ')' if ($t);
73         $return .= ' ' if ($t and $f);
74         $return .= $negate_flag .'item_form(' . join(',',split('', $f)) . ')' if ($f);
75         $return = '(' . $return . ')' if ($t and $f);
76     }
77     return $return;
78 }
79
80 sub quote_value {
81     my $self = shift;
82     my $value = shift;
83
84     if ($value =~ /^\d/) { # may have to use non-$ quoting
85         $value =~ s/'/''/g;
86         $value =~ s/\\/\\\\/g;
87         return "E'$value'";
88     }
89     return "\$_$$\$$value\$_$$\$";
90 }
91
92 sub quote_phrase_value {
93     my $self = shift;
94     my $value = shift;
95
96     my $left_anchored  = $value =~ m/^\^/;
97     my $right_anchored = $value =~ m/\$$/;
98     $value =~ s/\^//   if $left_anchored;
99     $value =~ s/\$$//  if $right_anchored;
100     $value = quotemeta($value);
101     $value = '^' . $value if $left_anchored;
102     $value = "$value\$"   if $right_anchored;
103     return $self->quote_value($value);
104 }
105
106 sub init {
107     my $class = shift;
108 }
109
110 sub default_preferred_language {
111     my $self = shift;
112     my $lang = shift;
113
114     $self->custom_data->{default_preferred_language} = $lang if ($lang);
115     return $self->custom_data->{default_preferred_language};
116 }
117
118 sub default_preferred_language_multiplier {
119     my $self = shift;
120     my $lang = shift;
121
122     $self->custom_data->{default_preferred_language_multiplier} = $lang if ($lang);
123     return $self->custom_data->{default_preferred_language_multiplier};
124 }
125
126 sub simple_plan {
127     my $self = shift;
128
129     return 0 unless $self->parse_tree;
130     return 0 if @{$self->parse_tree->filters};
131     return 0 if @{$self->parse_tree->modifiers};
132     for my $node ( @{ $self->parse_tree->query_nodes } ) {
133         return 0 if (!ref($node) && $node eq '|');
134         next unless (ref($node));
135         return 0 if ($node->isa('QueryParser::query_plan'));
136     }
137
138     return 1;
139 }
140
141 sub toSQL {
142     my $self = shift;
143     return $self->parse_tree->toSQL;
144 }
145
146 sub dynamic_filters {
147     my $self = shift;
148     my $new = shift;
149
150     $self->custom_data->{dynamic_filters} ||= [];
151     push(@{$self->custom_data->{dynamic_filters}}, $new) if ($new);
152     return $self->custom_data->{dynamic_filters};
153 }
154
155 sub dynamic_sorters {
156     my $self = shift;
157     my $new = shift;
158
159     $self->custom_data->{dynamic_sorters} ||= [];
160     push(@{$self->custom_data->{dynamic_sorters}}, $new) if ($new);
161     return $self->custom_data->{dynamic_sorters};
162 }
163
164 sub facet_field_id_map {
165     my $self = shift;
166     my $map = shift;
167
168     $self->custom_data->{facet_field_id_map} ||= {};
169     $self->custom_data->{facet_field_id_map} = $map if ($map);
170     return $self->custom_data->{facet_field_id_map};
171 }
172
173 sub add_facet_field_id_map {
174     my $self = shift;
175     my $class = shift;
176     my $field = shift;
177     my $id = shift;
178     my $weight = shift;
179
180     $self->add_facet_field( $class => $field );
181     $self->facet_field_id_map->{by_id}{$id} = { classname => $class, field => $field, weight => $weight };
182     $self->facet_field_id_map->{by_class}{$class}{$field} = $id;
183
184     return {
185         by_id => { $id => { classname => $class, field => $field, weight => $weight } },
186         by_class => { $class => { $field => $id } }
187     };
188 }
189
190 sub facet_field_class_by_id {
191     my $self = shift;
192     my $id = shift;
193
194     return $self->facet_field_id_map->{by_id}{$id};
195 }
196
197 sub facet_field_ids_by_class {
198     my $self = shift;
199     my $class = shift;
200     my $field = shift;
201
202     return undef unless ($class);
203
204     if ($field) {
205         return [$self->facet_field_id_map->{by_class}{$class}{$field}];
206     }
207
208     return [values( %{ $self->facet_field_id_map->{by_class}{$class} } )];
209 }
210
211 sub search_field_id_map {
212     my $self = shift;
213     my $map = shift;
214
215     $self->custom_data->{search_field_id_map} ||= {};
216     $self->custom_data->{search_field_id_map} = $map if ($map);
217     return $self->custom_data->{search_field_id_map};
218 }
219
220 sub add_search_field_id_map {
221     my $self = shift;
222     my $class = shift;
223     my $field = shift;
224     my $id = shift;
225     my $weight = shift;
226
227     $self->add_search_field( $class => $field );
228     $self->search_field_id_map->{by_id}{$id} = { classname => $class, field => $field, weight => $weight };
229     $self->search_field_id_map->{by_class}{$class}{$field} = $id;
230
231     return {
232         by_id => { $id => { classname => $class, field => $field, weight => $weight } },
233         by_class => { $class => { $field => $id } }
234     };
235 }
236
237 sub search_field_class_by_id {
238     my $self = shift;
239     my $id = shift;
240
241     return $self->search_field_id_map->{by_id}{$id};
242 }
243
244 sub search_field_ids_by_class {
245     my $self = shift;
246     my $class = shift;
247     my $field = shift;
248
249     return undef unless ($class);
250
251     if ($field) {
252         return [$self->search_field_id_map->{by_class}{$class}{$field}];
253     }
254
255     return [values( %{ $self->search_field_id_map->{by_class}{$class} } )];
256 }
257
258 sub relevance_bumps {
259     my $self = shift;
260     my $bumps = shift;
261
262     $self->custom_data->{rel_bumps} ||= {};
263     $self->custom_data->{rel_bumps} = $bumps if ($bumps);
264     return $self->custom_data->{rel_bumps};
265 }
266
267 sub find_relevance_bumps {
268     my $self = shift;
269     my $class = shift;
270     my $field = shift;
271
272     return $self->relevance_bumps->{$class}{$field};
273 }
274
275 sub add_relevance_bump {
276     my $self = shift;
277     my $class = shift;
278     my $field = shift;
279     my $type = shift;
280     my $multiplier = shift;
281     my $active = shift;
282
283     if (defined($active) and $active eq 'f') {
284         $active = 0;
285     } else {
286         $active = 1;
287     }
288
289     $self->relevance_bumps->{$class}{$field}{$type} = { multiplier => $multiplier, active => $active };
290
291     return { $class => { $field => { $type => { multiplier => $multiplier, active => $active } } } };
292 }
293
294
295 sub initialize_search_field_id_map {
296     my $self = shift;
297     my $cmf_list = shift;
298
299     for my $cmf (@$cmf_list) {
300         __PACKAGE__->add_search_field_id_map( $cmf->field_class, $cmf->name, $cmf->id, $cmf->weight ) if ($U->is_true($cmf->search_field));
301         __PACKAGE__->add_facet_field_id_map( $cmf->field_class, $cmf->name, $cmf->id, $cmf->weight ) if ($U->is_true($cmf->facet_field));
302     }
303
304     return $self->search_field_id_map;
305 }
306
307 sub initialize_aliases {
308     my $self = shift;
309     my $cmsa_list = shift;
310
311     for my $cmsa (@$cmsa_list) {
312         if (!$cmsa->field) {
313             __PACKAGE__->add_search_class_alias( $cmsa->field_class, $cmsa->alias );
314         } else {
315             my $c = $self->search_field_class_by_id( $cmsa->field );
316             __PACKAGE__->add_search_field_alias( $cmsa->field_class, $c->{field}, $cmsa->alias );
317         }
318     }
319 }
320
321 sub initialize_relevance_bumps {
322     my $self = shift;
323     my $sra_list = shift;
324
325     for my $sra (@$sra_list) {
326         my $c = $self->search_field_class_by_id( $sra->field );
327         __PACKAGE__->add_relevance_bump( $c->{classname}, $c->{field}, $sra->bump_type, $sra->multiplier, $sra->active );
328     }
329
330     return $self->relevance_bumps;
331 }
332
333 sub initialize_query_normalizers {
334     my $self = shift;
335     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" }] }
336
337     for my $cmfinm ( @$tree ) {
338         my $field_info = $self->search_field_class_by_id( $cmfinm->field );
339         __PACKAGE__->add_query_normalizer( $field_info->{classname}, $field_info->{field}, $cmfinm->norm->func, OpenSRF::Utils::JSON->JSON2perl($cmfinm->params) );
340     }
341 }
342
343 sub initialize_dynamic_filters {
344     my $self = shift;
345     my $list = shift; # open-ils.cstore.direct.config.record_attr_definition.search.atomic { "id" : { "!=" : null } }
346
347     for my $crad ( @$list ) {
348         __PACKAGE__->dynamic_filters( __PACKAGE__->add_search_filter( $crad->name ) ) if ($U->is_true($crad->filter));
349         __PACKAGE__->dynamic_sorters( $crad->name ) if ($U->is_true($crad->sorter));
350     }
351 }
352
353 sub initialize_filter_normalizers {
354     my $self = shift;
355     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" }] }
356
357     for my $crainm ( @$tree ) {
358         __PACKAGE__->add_filter_normalizer( $crainm->attr, $crainm->norm->func, OpenSRF::Utils::JSON->JSON2perl($crainm->params) );
359     }
360 }
361
362 our $_complete = 0;
363 sub initialization_complete {
364     return $_complete;
365 }
366
367 sub initialize {
368     my $self = shift;
369     my %args = @_;
370
371     return $_complete if ($_complete);
372
373     # tsearch rank normalization adjustments. see http://www.postgresql.org/docs/9.0/interactive/textsearch-controls.html#TEXTSEARCH-RANKING for details
374     $self->custom_data->{rank_cd_weight_map} = {
375         CD_logDocumentLength    => 1,
376         CD_documentLength       => 2,
377         CD_meanHarmonic         => 4,
378         CD_uniqueWords          => 8,
379         CD_logUniqueWords       => 16,
380         CD_selfPlusOne          => 32
381     };
382
383     $self->add_search_modifier( $_ ) for (keys %{ $self->custom_data->{rank_cd_weight_map} });
384
385     $self->initialize_search_field_id_map( $args{config_metabib_field} )
386         if ($args{config_metabib_field});
387
388     $self->initialize_aliases( $args{config_metabib_search_alias} )
389         if ($args{config_metabib_search_alias});
390
391     $self->initialize_relevance_bumps( $args{search_relevance_adjustment} )
392         if ($args{search_relevance_adjustment});
393
394     $self->initialize_query_normalizers( $args{config_metabib_field_index_norm_map} )
395         if ($args{config_metabib_field_index_norm_map});
396
397     $self->initialize_dynamic_filters( $args{config_record_attr_definition} )
398         if ($args{config_record_attr_definition});
399
400     $self->initialize_filter_normalizers( $args{config_record_attr_index_norm_map} )
401         if ($args{config_record_attr_index_norm_map});
402
403     $_complete = 1 if (
404         $args{config_metabib_field_index_norm_map} &&
405         $args{search_relevance_adjustment} &&
406         $args{config_metabib_search_alias} &&
407         $args{config_metabib_field} &&
408         $args{config_record_attr_definition}
409     );
410
411     return $_complete;
412 }
413
414 sub TEST_SETUP {
415     
416     __PACKAGE__->allow_nested_modifiers(1);
417
418     __PACKAGE__->add_search_field_id_map( series => seriestitle => 1 => 1 );
419
420     __PACKAGE__->add_search_field_id_map( series => seriestitle => 1 => 1 );
421     __PACKAGE__->add_relevance_bump( series => seriestitle => first_word => 1.5 );
422     __PACKAGE__->add_relevance_bump( series => seriestitle => full_match => 20 );
423     
424     __PACKAGE__->add_search_field_id_map( title => abbreviated => 2 => 1 );
425     __PACKAGE__->add_relevance_bump( title => abbreviated => first_word => 1.5 );
426     __PACKAGE__->add_relevance_bump( title => abbreviated => full_match => 20 );
427     
428     __PACKAGE__->add_search_field_id_map( title => translated => 3 => 1 );
429     __PACKAGE__->add_relevance_bump( title => translated => first_word => 1.5 );
430     __PACKAGE__->add_relevance_bump( title => translated => full_match => 20 );
431     
432     __PACKAGE__->add_search_field_id_map( title => proper => 6 => 1 );
433     __PACKAGE__->add_query_normalizer( title => proper => 'search_normalize' );
434     __PACKAGE__->add_relevance_bump( title => proper => first_word => 1.5 );
435     __PACKAGE__->add_relevance_bump( title => proper => full_match => 20 );
436     __PACKAGE__->add_relevance_bump( title => proper => word_order => 10 );
437     
438     __PACKAGE__->add_search_field_id_map( author => corporate => 7 => 1 );
439     __PACKAGE__->add_relevance_bump( author => corporate => first_word => 1.5 );
440     __PACKAGE__->add_relevance_bump( author => corporate => full_match => 20 );
441     
442     __PACKAGE__->add_facet_field_id_map( author => personal => 8 => 1 );
443
444     __PACKAGE__->add_search_field_id_map( author => personal => 8 => 1 );
445     __PACKAGE__->add_relevance_bump( author => personal => first_word => 1.5 );
446     __PACKAGE__->add_relevance_bump( author => personal => full_match => 20 );
447     __PACKAGE__->add_query_normalizer( author => personal => 'search_normalize' );
448     __PACKAGE__->add_query_normalizer( author => personal => 'split_date_range' );
449     
450     __PACKAGE__->add_facet_field_id_map( subject => topic => 14 => 1 );
451
452     __PACKAGE__->add_search_field_id_map( subject => topic => 14 => 1 );
453     __PACKAGE__->add_relevance_bump( subject => topic => first_word => 1 );
454     __PACKAGE__->add_relevance_bump( subject => topic => full_match => 1 );
455     
456     __PACKAGE__->add_search_field_id_map( subject => complete => 16 => 1 );
457     __PACKAGE__->add_relevance_bump( subject => complete => first_word => 1 );
458     __PACKAGE__->add_relevance_bump( subject => complete => full_match => 1 );
459     
460     __PACKAGE__->add_search_field_id_map( keyword => keyword => 15 => 1 );
461     __PACKAGE__->add_relevance_bump( keyword => keyword => first_word => 1 );
462     __PACKAGE__->add_relevance_bump( keyword => keyword => full_match => 1 );
463     
464     
465     __PACKAGE__->add_search_class_alias( keyword => 'kw' );
466     __PACKAGE__->add_search_class_alias( title => 'ti' );
467     __PACKAGE__->add_search_class_alias( author => 'au' );
468     __PACKAGE__->add_search_class_alias( author => 'name' );
469     __PACKAGE__->add_search_class_alias( author => 'dc.contributor' );
470     __PACKAGE__->add_search_class_alias( subject => 'su' );
471     __PACKAGE__->add_search_class_alias( subject => 'bib.subject(?:Title|Place|Occupation)' );
472     __PACKAGE__->add_search_class_alias( series => 'se' );
473     __PACKAGE__->add_search_class_alias( keyword => 'dc.identifier' );
474     
475     __PACKAGE__->add_query_normalizer( author => corporate => 'search_normalize' );
476     __PACKAGE__->add_query_normalizer( keyword => keyword => 'search_normalize' );
477     
478     __PACKAGE__->add_search_field_alias( subject => name => 'bib.subjectName' );
479     
480 }
481
482 __PACKAGE__->default_search_class( 'keyword' );
483
484 # implements EG-specific stored subqueries
485 __PACKAGE__->add_search_filter( 'saved_query', sub { return __PACKAGE__->subquery_callback(@_) } );
486 __PACKAGE__->add_search_filter( 'filter_group_entry', sub { return __PACKAGE__->filter_group_entry_callback(@_) } );
487
488 # will be retained simply for back-compat
489 __PACKAGE__->add_search_filter( 'format', sub { return __PACKAGE__->format_callback(@_) } );
490
491 # grumble grumble, special cases against date1 and date2
492 __PACKAGE__->add_search_filter( 'before' );
493 __PACKAGE__->add_search_filter( 'after' );
494 __PACKAGE__->add_search_filter( 'between' );
495 __PACKAGE__->add_search_filter( 'during' );
496
497 # various filters for limiting in various ways
498 __PACKAGE__->add_search_filter( 'statuses' );
499 __PACKAGE__->add_search_filter( 'locations' );
500 __PACKAGE__->add_search_filter( 'location_groups', sub { return __PACKAGE__->location_groups_callback(@_) } );
501 __PACKAGE__->add_search_filter( 'bib_source' );
502 __PACKAGE__->add_search_filter( 'site' );
503 __PACKAGE__->add_search_filter( 'pref_ou' );
504 __PACKAGE__->add_search_filter( 'lasso' );
505 __PACKAGE__->add_search_filter( 'my_lasso' );
506 __PACKAGE__->add_search_filter( 'depth' );
507 __PACKAGE__->add_search_filter( 'language' );
508 __PACKAGE__->add_search_filter( 'offset' );
509 __PACKAGE__->add_search_filter( 'limit' );
510 __PACKAGE__->add_search_filter( 'check_limit' );
511 __PACKAGE__->add_search_filter( 'skip_check' );
512 __PACKAGE__->add_search_filter( 'superpage' );
513 __PACKAGE__->add_search_filter( 'superpage_size' );
514 __PACKAGE__->add_search_filter( 'estimation_strategy' );
515 __PACKAGE__->add_search_modifier( 'available' );
516 __PACKAGE__->add_search_modifier( 'staff' );
517
518 # Start from container data (bre, acn, acp): container(bre,bookbag,123,deadb33fdeadb33fdeadb33fdeadb33f)
519 __PACKAGE__->add_search_filter( 'container' );
520
521 # Start from a list of record ids, either bre or metarecords, depending on the #metabib modifier
522 __PACKAGE__->add_search_filter( 'record_list' );
523
524 # used internally, but generally not user-settable
525 __PACKAGE__->add_search_filter( 'preferred_language' );
526 __PACKAGE__->add_search_filter( 'preferred_language_weight' );
527 __PACKAGE__->add_search_filter( 'preferred_language_multiplier' );
528 __PACKAGE__->add_search_filter( 'core_limit' );
529
530 # XXX Valid values to be supplied by SVF
531 __PACKAGE__->add_search_filter( 'sort' );
532
533 # modifies core query, not configurable
534 __PACKAGE__->add_search_modifier( 'descending' );
535 __PACKAGE__->add_search_modifier( 'ascending' );
536 __PACKAGE__->add_search_modifier( 'nullsfirst' );
537 __PACKAGE__->add_search_modifier( 'nullslast' );
538 __PACKAGE__->add_search_modifier( 'metarecord' );
539 __PACKAGE__->add_search_modifier( 'metabib' );
540
541
542 #-------------------------------
543 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan;
544 use base 'QueryParser::query_plan';
545 use OpenSRF::Utils::Logger qw($logger);
546 use Data::Dumper;
547 use OpenILS::Application::AppUtils;
548 use OpenILS::Utils::CStoreEditor;
549 my $apputils = "OpenILS::Application::AppUtils";
550 my $editor = OpenILS::Utils::CStoreEditor->new;
551
552 sub toSQL {
553     my $self = shift;
554
555     my %filters;
556
557     for my $f ( qw/preferred_language preferred_language_multiplier preferred_language_weight core_limit check_limit skip_check superpage superpage_size/ ) {
558         my $col = $f;
559         $col = 'preferred_language_multiplier' if ($f eq 'preferred_language_weight');
560         my ($filter) = $self->find_filter($f);
561         if ($filter and @{$filter->args}) {
562             $filters{$col} = $filter->args->[0];
563         }
564     }
565     $self->new_filter( statuses => [0,7,12] ) if ($self->find_modifier('available'));
566
567     $self->QueryParser->superpage($filters{superpage}) if ($filters{superpage});
568     $self->QueryParser->superpage_size($filters{superpage_size}) if ($filters{superpage_size});
569     $self->QueryParser->core_limit($filters{core_limit}) if ($filters{core_limit});
570
571     $logger->debug("Query plan:\n".Dumper($self));
572
573     my $flat_plan = $self->flatten;
574
575     # generate the relevance ranking
576     my $rel = '1'; # Default to something simple in case rank_list is empty.
577     $rel = "AVG(\n${spc}${spc}${spc}${spc}${spc}(" . join(")\n${spc}${spc}${spc}${spc}${spc}+ (", @{$$flat_plan{rank_list}}) . ")\n${spc}${spc}${spc}${spc})+1" if (@{$$flat_plan{rank_list}});
578
579     # find any supplied sort option
580     my ($sort_filter) = $self->find_filter('sort');
581     if ($sort_filter) {
582         $sort_filter = $sort_filter->args->[0];
583     } else {
584         $sort_filter = 'rel';
585     }
586
587     if (($filters{preferred_language} || $self->QueryParser->default_preferred_language) && ($filters{preferred_language_multiplier} || $self->QueryParser->default_preferred_language_multiplier)) {
588         my $pl = $self->QueryParser->quote_value( $filters{preferred_language} ? $filters{preferred_language} : $self->QueryParser->default_preferred_language );
589         my $plw = $filters{preferred_language_multiplier} ? $filters{preferred_language_multiplier} : $self->QueryParser->default_preferred_language_multiplier;
590         $rel = "($rel * COALESCE( NULLIF( FIRST(mrd.attrs \@> hstore('item_lang', $pl)), FALSE )::INT * $plw, 1))";
591     }
592     $rel = "1.0/($rel)::NUMERIC";
593
594     my $rank = $rel;
595
596     my $desc = 'ASC';
597     $desc = 'DESC' if ($self->find_modifier('descending'));
598
599     my $nullpos = 'NULLS LAST';
600     $nullpos = 'NULLS FIRST' if ($self->find_modifier('nullsfirst'));
601
602     if (grep {$_ eq $sort_filter} @{$self->QueryParser->dynamic_sorters}) {
603         $rank = "FIRST(mrd.attrs->'$sort_filter')"
604     } elsif ($sort_filter eq 'create_date') {
605         $rank = "FIRST((SELECT create_date FROM biblio.record_entry rbr WHERE rbr.id = m.source))";
606     } elsif ($sort_filter eq 'edit_date') {
607         $rank = "FIRST((SELECT edit_date FROM biblio.record_entry rbr WHERE rbr.id = m.source))";
608     } else {
609         # default to rel ranking
610         $rank = $rel;
611     }
612
613     my $key = 'm.source';
614     $key = 'm.metarecord' if (grep {$_->name eq 'metarecord' or $_->name eq 'metabib'} @{$self->modifiers});
615
616     my $core_limit = $self->QueryParser->core_limit || 25000;
617
618     my $flat_where = $$flat_plan{where};
619     if ($flat_where eq '()') {
620         $flat_where = '';
621     } else {
622         $flat_where = "AND $flat_where";
623     }
624
625     my $site = $self->find_filter('site');
626     if ($site && $site->args) {
627         $site = $site->args->[0];
628         if ($site && $site !~ /^(-)?\d+$/) {
629             my $search = $editor->search_actor_org_unit({ shortname => $site });
630             $site = @$search[0]->id if($search && @$search);
631             $site = undef unless ($search);
632         }
633     } else {
634         $site = undef;
635     }
636     my $lasso = $self->find_filter('lasso');
637     if ($lasso && $lasso->args) {
638         $lasso = $lasso->args->[0];
639         if ($lasso && $lasso !~ /^\d+$/) {
640             my $search = $editor->search_actor_org_lasso({ name => $lasso });
641             $lasso = @$search[0]->id if($search && @$search);
642             $lasso = undef unless ($search);
643         }
644     } else {
645         $lasso = undef;
646     }
647     my $depth = $self->find_filter('depth');
648     if ($depth && $depth->args) {
649         $depth = $depth->args->[0];
650         if ($depth && $depth !~ /^\d+$/) {
651             # This *is* what metabib.pm has been doing....but it makes no sense to me. :/
652             # Should this be looking up the depth of the OU type on the OU in question?
653             my $search = $editor->search_actor_org_unit([{ name => $depth },{ opac_label => $depth }]);
654             $depth = @$search[0]->id if($search && @$search);
655             $depth = undef unless($search);
656         }
657     } else {
658         $depth = undef;
659     }
660     my $pref_ou = $self->find_filter('pref_ou');
661     if ($pref_ou && $pref_ou->args) {
662         $pref_ou = $pref_ou->args->[0];
663         if ($pref_ou && $pref_ou !~ /^(-)?\d+$/) {
664             my $search = $editor->search_actor_org_unit({ shortname => $pref_ou });
665             $pref_ou = @$search[0]->id if($search && @$search);
666             $pref_ou = undef unless ($search);
667         }
668     } else {
669         $pref_ou = undef;
670     }
671
672     # Supposedly at some point a site of 0 and a depth will equal user lasso id.
673     # We need OU buckets before that happens. 'my_lasso' is, I believe, the target filter for it.
674
675     $site = -$lasso if ($lasso);
676
677     # Default to the top of the org tree if we have nothing else. This would need tweaking for the user lasso bit.
678     if (!$site) {
679         my $search = $editor->search_actor_org_unit({ parent_ou => undef });
680         $site = @$search[0]->id if ($search);
681     }
682
683     my $depth_check = '';
684     $depth_check = ", $depth" if ($depth);
685
686     my $with = '';
687     $with .= "     search_org_list AS (\n";
688     if ($site < 0) {
689         # Lasso!
690         $lasso = -$site;
691         $with .= "       SELECT DISTINCT org_unit from actor.org_lasso_map WHERE lasso = $lasso\n";
692     } elsif ($site > 0) {
693         $with .= "       SELECT DISTINCT id FROM actor.org_unit_descendants($site$depth_check)\n";
694     } else {
695         # Placeholder for user lasso stuff.
696     }
697     $with .= "     ),\n";
698     $with .= "     luri_org_list AS (\n";
699     if ($site < 0) {
700         # We can re-use the lasso var, we already updated it above.
701         $with .= "       SELECT DISTINCT (actor.org_unit_ancestors(org_unit)).id from actor.org_lasso_map WHERE lasso = $lasso\n";
702     } elsif ($site > 0) {
703         $with .= "       SELECT DISTINCT id FROM actor.org_unit_ancestors($site)\n";
704     } else {
705         # Placeholder for user lasso stuff.
706     }
707     if ($pref_ou) {
708         $with .= "       UNION\n";
709         $with .= "       SELECT DISTINCT id FROM actor.org_unit_ancestors($pref_ou)\n";
710     }
711     $with .= "     )";
712     $with .= ",\n     " . $$flat_plan{with} if ($$flat_plan{with});
713
714     # Limit stuff
715     my $limit_where = <<"    SQL";
716 -- Filter records based on visibility
717         AND (
718             cbs.transcendant IS TRUE
719             OR
720             EXISTS(
721                 SELECT 1 FROM asset.call_number acn
722                     JOIN asset.uri_call_number_map aucnm ON acn.id = aucnm.call_number
723                     JOIN asset.uri uri ON aucnm.uri = uri.id
724                 WHERE NOT acn.deleted AND uri.active AND acn.record = m.source AND acn.owning_lib IN (
725                     SELECT * FROM luri_org_list
726                 )
727                 LIMIT 1
728             )
729             OR
730     SQL
731     if ($self->find_modifier('staff')) {
732         $limit_where .= <<"        SQL";
733             EXISTS(
734                 SELECT 1 FROM asset.call_number cn
735                     JOIN asset.copy cp ON (cp.call_number = cn.id)
736                 WHERE NOT cn.deleted
737                     AND NOT cp.deleted
738                     AND cp.circ_lib IN ( SELECT * FROM search_org_list )
739                     AND cn.record = m.source
740                 LIMIT 1
741             )
742             OR
743             EXISTS(
744                 SELECT 1 FROM biblio.peer_bib_copy_map pr
745                     JOIN asset.copy cp ON (cp.id = pr.target_copy)
746                 WHERE NOT cp.deleted
747                     AND cp.circ_lib IN ( SELECT * FROM search_org_list )
748                     AND pr.peer_record = m.source
749                 LIMIT 1
750             )
751             OR (
752                 NOT EXISTS(
753                     SELECT 1 FROM asset.call_number cn
754                         JOIN asset.copy cp ON (cp.call_number = cn.id)
755                     WHERE cn.record = m.source
756                         AND NOT cp.deleted
757                     LIMIT 1
758                 )
759                 AND
760                 NOT EXISTS(
761                     SELECT 1 FROM biblio.peer_bib_copy_map pr
762                         JOIN asset.copy cp ON (cp.id = pr.target_copy)
763                     WHERE NOT cp.deleted
764                         AND pr.peer_record = m.source
765                     LIMIT 1
766                 )
767             )
768         SQL
769     } else {
770         $limit_where .= <<"        SQL";
771             EXISTS(
772                 SELECT 1 FROM asset.opac_visible_copies
773                 WHERE circ_lib IN ( SELECT * FROM search_org_list )
774                     AND record = m.source
775                 LIMIT 1
776             )
777             OR
778             EXISTS(
779                 SELECT 1 FROM biblio.peer_bib_copy_map pr
780                     JOIN asset.opac_visible_copies cp ON (cp.copy_id = pr.target_copy)
781                 WHERE cp.circ_lib IN ( SELECT * FROM search_org_list )
782                     AND pr.peer_record = m.source
783                 LIMIT 1
784             )
785         SQL
786     }
787     $limit_where .= "        )";
788
789     # For single records we want the record id
790     # For metarecords we want NULL or the only record ID.
791     my $agg_record = 'm.source AS record';
792     if ($key =~ /metarecord/) {
793         $agg_record = 'CASE WHEN COUNT(DISTINCT m.source) = 1 THEN FIRST(m.source) ELSE NULL END AS record';
794     }
795
796     my $sql = <<SQL;
797 WITH
798 $with
799 SELECT  $key AS id,
800         $agg_record,
801         $rel AS rel,
802         $rank AS rank, 
803         FIRST(mrd.attrs->'date1') AS tie_break
804   FROM  metabib.metarecord_source_map m
805         $$flat_plan{from}
806         INNER JOIN metabib.record_attr mrd ON m.source = mrd.id
807         INNER JOIN biblio.record_entry bre ON m.source = bre.id
808         LEFT JOIN config.bib_source cbs ON bre.source = cbs.id
809   WHERE 1=1
810         $flat_where
811         $limit_where
812   GROUP BY 1
813   ORDER BY 4 $desc $nullpos, 5 DESC $nullpos, 3 DESC
814   LIMIT $core_limit
815 SQL
816
817     warn $sql if $self->QueryParser->debug;
818     return $sql;
819
820 }
821
822
823 sub rel_bump {
824     my $self = shift;
825     my $node = shift;
826     my $bump = shift;
827     my $multiplier = shift;
828
829     my $only_atoms = $node->only_real_atoms;
830     return '' if (!@$only_atoms);
831
832     if ($bump eq 'first_word') {
833         return "/* first_word */ COALESCE(NULLIF( (search_normalize(".$node->table_alias.".value) ~ ('^'||search_normalize(".$self->QueryParser->quote_phrase_value($only_atoms->[0]->content)."))), FALSE )::INT * $multiplier, 1)";
834     } elsif ($bump eq 'full_match') {
835         return "/* full_match */ COALESCE(NULLIF( (search_normalize(".$node->table_alias.".value) ~ ('^'||".
836                     join( "||' '||", map { "search_normalize(".$self->QueryParser->quote_phrase_value($_->content).")" } @$only_atoms )."||'\$')), FALSE )::INT * $multiplier, 1)";
837     } elsif ($bump eq 'word_order') {
838         return "/* word_order */ COALESCE(NULLIF( (search_normalize(".$node->table_alias.".value) ~ (".
839                     join( "||'.*'||", map { "search_normalize(".$self->QueryParser->quote_phrase_value($_->content).")" } @$only_atoms ).")), FALSE )::INT * $multiplier, 1)";
840     }
841
842     return '';
843 }
844
845 sub flatten {
846     my $self = shift;
847
848     my $from = shift || '';
849     my $where = shift || '(';
850     my $with = '';
851
852     my @rank_list;
853     for my $node ( @{$self->query_nodes} ) {
854
855         if (ref($node)) {
856             if ($node->isa( 'QueryParser::query_plan::node' )) {
857
858                 unless (@{$node->only_atoms}) {
859                     push @rank_list, '1';
860                     $where .= 'TRUE';
861                     next;
862                 }
863
864                 my $table = $node->table;
865                 my $talias = $node->table_alias;
866
867                 my $node_rank = 'COALESCE(' . $node->rank . " * ${talias}.weight, 0.0)";
868
869                 my $core_limit = $self->QueryParser->core_limit || 25000;
870                 $from .= "\n${spc}${spc}${spc}${spc}LEFT JOIN (\n${spc}${spc}${spc}${spc}${spc}SELECT fe.*, fe_weight.weight, ${talias}_xq.tsq /* search */\n${spc}${spc}${spc}${spc}${spc}  FROM  $table AS fe";
871                 $from .= "\n${spc}${spc}${spc}${spc}${spc}${spc}JOIN config.metabib_field AS fe_weight ON (fe_weight.id = fe.field)";
872
873                 if ($node->dummy_count < @{$node->only_atoms} ) {
874                     $with .= ",\n     " if $with;
875                     $with .= "${talias}_xq AS (SELECT ". $node->tsquery ." AS tsq )";
876                     $from .= "\n${spc}${spc}${spc}${spc}${spc}${spc}JOIN ${talias}_xq ON (fe.index_vector @@ ${talias}_xq.tsq)";
877                 } else {
878                     $from .= "\n${spc}${spc}${spc}${spc}${spc}${spc}, (SELECT NULL::tsquery AS tsq ) AS ${talias}_xq";
879                 }
880
881                 my @bump_fields;
882                 if (@{$node->fields} > 0) {
883                     @bump_fields = @{$node->fields};
884
885                     my @field_ids = grep defined, (
886                         map {
887                             $self->QueryParser->search_field_ids_by_class(
888                                 $node->classname, $_
889                             )->[0]
890                         } @bump_fields
891                     );
892                     if (@field_ids) {
893                         $from .= "\n${spc}${spc}${spc}${spc}${spc}${spc}WHERE fe_weight.id IN  (" .
894                             join(',', @field_ids) . ")";
895                     }
896
897                 } else {
898                     @bump_fields = @{$self->QueryParser->search_fields->{$node->classname}};
899                 }
900
901                 ###$from .= "\n${spc}${spc}LIMIT $core_limit";
902                 $from .= "\n${spc}${spc}${spc}${spc}) AS $talias ON (m.source = ${talias}.source)";
903
904
905                 my %used_bumps;
906                 for my $field ( @bump_fields ) {
907                     my $bumps = $self->QueryParser->find_relevance_bumps( $node->classname => $field );
908                     for my $b (keys %$bumps) {
909                         next if (!$$bumps{$b}{active});
910                         next if ($used_bumps{$b});
911                         $used_bumps{$b} = 1;
912
913                         next if ($$bumps{$b}{multiplier} == 1); # optimization to remove unneeded bumps
914
915                         my $bump_case = $self->rel_bump( $node, $b, $$bumps{$b}{multiplier} );
916                         $node_rank .= "\n${spc}${spc}${spc}${spc}${spc}* " . $bump_case if ($bump_case);
917                     }
918                 }
919
920
921                 $where .= '(' . $talias . ".id IS NOT NULL";
922                 $where .= ' AND ' . join(' AND ', map {"${talias}.value ~* ".$self->QueryParser->quote_phrase_value($_)} @{$node->phrases}) if (@{$node->phrases});
923                 $where .= ' AND ' . join(' AND ', map {"${talias}.value !~* ".$self->QueryParser->quote_phrase_value($_)} @{$node->unphrases}) if (@{$node->unphrases});
924                 for my $atom (@{$node->only_real_atoms}) {
925                     next unless $atom->{content} && $atom->{content} =~ /(^\^|\$$)/;
926                     $where .= " AND ${talias}.value ~* ".$self->QueryParser->quote_phrase_value($atom->{content});
927                 }
928                 $where .= ')';
929
930                 push @rank_list, $node_rank;
931
932             } elsif ($node->isa( 'QueryParser::query_plan::facet' )) {
933
934                 my $table = $node->table;
935                 my $talias = $node->table_alias;
936
937                 my @field_ids;
938                 if (@{$node->fields} > 0) {
939                     push(@field_ids, $self->QueryParser->facet_field_ids_by_class( $node->classname, $_ )->[0]) for (@{$node->fields});
940                 } else {
941                     @field_ids = @{ $self->QueryParser->facet_field_ids_by_class( $node->classname ) };
942                 }
943
944                 my $join_type = ($node->negate or !$self->top_plan) ? 'LEFT' : 'INNER';
945                 $from .= "\n${spc}$join_type JOIN /* facet */ metabib.facet_entry $talias ON (\n${spc}${spc}m.source = ${talias}.source\n${spc}${spc}".
946                          "AND SUBSTRING(${talias}.value,1,1024) IN (" . join(",", map { $self->QueryParser->quote_value($_) } @{$node->values}) . ")\n${spc}${spc}".
947                          "AND ${talias}.field IN (". join(',', @field_ids) . ")\n${spc})";
948
949                 if ($join_type ne 'INNER') {
950                     my $NOT = $node->negate ? '' : ' NOT';
951                     $where .= "${talias}.id IS$NOT NULL";
952                 } elsif ($where ne '(') {
953                     # Strip extra joiner
954                     $where =~ s/\s(AND|OR)\s$//;
955                 }
956
957             } else {
958                 my $subnode = $node->flatten;
959
960                 # strip the trailing bool from the previous loop if there is 
961                 # nothing to add to the where within this loop.
962                 if ($$subnode{where} eq '()') {
963                     $where =~ s/\s(AND|OR)\s$//;
964                 }
965
966                 push(@rank_list, @{$$subnode{rank_list}});
967                 $from .= $$subnode{from};
968
969                 $where .= "$$subnode{where}" unless $$subnode{where} eq '()';
970
971                 if ($$subnode{with}) {
972                     $with .= ",\n     " if $with;
973                     $with .= $$subnode{with};
974                 }
975             }
976         } else {
977
978             warn "flatten(): appending WHERE bool to: $where\n" if $self->QueryParser->debug;
979
980             if ($where ne '(') {
981                 $where .= ' AND ' if ($node eq '&');
982                 $where .= ' OR ' if ($node eq '|');
983             }
984         }
985     }
986
987     my $joiner = sprintf(" %s ", ($self->joiner eq '&' ? 'AND' : 'OR'));
988     # for each dynamic filter, build more of the WHERE clause
989     for my $filter (@{$self->filters}) {
990         my $NOT = $filter->negate ? 'NOT ' : '';
991         if (grep { $_ eq $filter->name } @{ $self->QueryParser->dynamic_filters }) {
992
993             warn "flatten(): processing dynamic filter ". $filter->name ."\n"
994                 if $self->QueryParser->debug;
995
996             # bool joiner for intra-plan nodes/filters
997             $where .= $joiner if $where ne '(';
998
999             my @fargs = @{$filter->args};
1000             my $fname = $filter->name;
1001             $fname = 'item_lang' if $fname eq 'language'; #XXX filter aliases 
1002
1003             $where .= sprintf(
1004                 "${NOT}COALESCE((mrd.attrs->'%s') IN (%s), false)", $fname, 
1005                 join(',', map { $self->QueryParser->quote_value($_) } @fargs)
1006             );
1007
1008             warn "flatten(): filter where => $where\n"
1009                 if $self->QueryParser->debug;
1010         } else {
1011             if ($filter->name eq 'before') {
1012                 if (@{$filter->args} == 1) {
1013                     $where .= $joiner if $where ne '(';
1014                     $where .= "${NOT}COALESCE((mrd.attrs->'date1') <= " . $self->QueryParser->quote_value($filter->args->[0]) . ", false)";
1015                 }
1016             } elsif ($filter->name eq 'after') {
1017                 if (@{$filter->args} == 1) {
1018                     $where .= $joiner if $where ne '(';
1019                     $where .= "${NOT}COALESCE((mrd.attrs->'date1') >= " . $self->QueryParser->quote_value($filter->args->[0]) . ", false)";
1020                 }
1021             } elsif ($filter->name eq 'during') {
1022                 if (@{$filter->args} == 1) {
1023                     $where .= $joiner if $where ne '(';
1024                     $where .= "${NOT}COALESCE(" . $self->QueryParser->quote_value($filter->args->[0]) . " BETWEEN (mrd.attrs->'date1') AND (mrd.attrs->'date2'), false)";
1025                 }
1026             } elsif ($filter->name eq 'between') {
1027                 if (@{$filter->args} == 2) {
1028                     $where .= $joiner if $where ne '(';
1029                     $where .= "${NOT}COALESCE((mrd.attrs->'date1') BETWEEN " . $self->QueryParser->quote_value($filter->args->[0]) . " AND " . $self->QueryParser->quote_value($filter->args->[1]) . ", false)";
1030                 }
1031             } elsif ($filter->name eq 'container') {
1032                 if (@{$filter->args} >= 3) {
1033                     my ($class, $ctype, $cid, $token) = @{$filter->args};
1034                     my $perm_join = '';
1035                     my $rec_join = '';
1036                     my $rec_field = 'ci.target_biblio_record_entry';
1037                     if ($class eq 'bre') {
1038                         $class = 'biblio_record_entry';
1039                     } elsif ($class eq 'acn') {
1040                         $class = 'call_number';
1041                         $rec_field = 'cn.record';
1042                         $rec_join = 'JOIN asset.call_number cn ON (ci.target_call_number = cn.id)';
1043                     } elsif ($class eq 'acp') {
1044                         $class = 'copy';
1045                         $rec_field = 'cn.record';
1046                         $rec_join = 'JOIN asset.copy cp ON (ci.target_copy = cp.id) JOIN asset.call_number cn ON (cp.call_number = cn.id)';
1047                     } else {
1048                         $class = undef;
1049                     }
1050
1051                     if ($class) {
1052                         my ($u,$e) = $apputils->checksesperm($token) if ($token);
1053                         $perm_join = ' OR c.owner = ' . $u->id if ($u && !$e);
1054                         $where .= $joiner if $where ne '(';
1055                         $where .= '(' if $class eq 'copy';
1056                         $where .= "${NOT}EXISTS(SELECT 1 FROM container.${class}_bucket_item ci JOIN container.${class}_bucket c ON (c.id = ci.bucket) $rec_join WHERE c.btype = " . $self->QueryParser->quote_value($ctype) . " AND c.id = " . $self->QueryParser->quote_value($cid) . " AND (c.pub IS TRUE$perm_join) AND $rec_field = m.source LIMIT 1)";
1057                     }
1058                     if ($class eq 'copy') {
1059                         my $subjoiner = $filter->negate ? ' AND ' : ' OR ';
1060                         $where .= "$subjoiner${NOT}EXISTS(SELECT 1 FROM container.copy_bucket_item ci JOIN container.copy_bucket c ON (c.id = ci.bucket) JOIN biblio.peer_bib_copy_map pr ON ci.target_copy = pr.target_copy WHERE c.btype = " . $self->QueryParser->quote_value($cid) . " AND (c.pub IS TRUE$perm_join) AND pr.peer_record = m.source LIMIT 1))";
1061                     }
1062                 }
1063             } elsif ($filter->name eq 'record_list') {
1064                 if (@{$filter->args} > 0) {
1065                     my $key = 'm.source';
1066                     $key = 'm.metarecord' if (grep {$_->name eq 'metarecord' or $_->name eq 'metabib'} @{$self->QueryParser->parse_tree->modifiers});
1067                     $where .= $joiner if $where ne '(';
1068                     $where .= "$key ${NOT}IN (" . join(',', map { $self->QueryParser->quote_value($_) } @{$filter->args}) . ')';
1069                 }
1070             } elsif ($filter->name eq 'locations') {
1071                 if (@{$filter->args} > 0) {
1072                     $where .= $joiner if $where ne '(';
1073                     $where .= "(${NOT}EXISTS(SELECT 1 FROM asset.call_number acn JOIN asset.copy acp ON acn.id = acp.call_number WHERE m.source = acn.record AND acp.circ_lib IN (SELECT * FROM search_org_list) AND NOT acn.deleted AND NOT acp.deleted AND acp.location IN (" . join(',', map { $self->QueryParser->quote_value($_) } @{ $filter->args }) . ") LIMIT 1)";
1074                     $where .= $filter->negate ? ' AND ' : ' OR ';
1075                     $where .= "${NOT}EXISTS(SELECT 1 FROM biblio.peer_bib_copy_map pr JOIN asset.copy acp ON pr.target_copy = acp.id WHERE m.source = pr.peer_record AND acp.circ_lib IN (SELECT * FROM search_org_list) AND NOT acp.deleted AND acp.location IN (" . join(',', map { $self->QueryParser->quote_value($_) } @{ $filter->args }) . ") LIMIT 1))";
1076                 }
1077             } elsif ($filter->name eq 'statuses') {
1078                 if (@{$filter->args} > 0) {
1079                     $where .= $joiner if $where ne '(';
1080                     $where .= "(${NOT}EXISTS(SELECT 1 FROM asset.call_number acn JOIN asset.copy acp ON acn.id = acp.call_number WHERE m.source = acn.record AND acp.circ_lib IN (SELECT * FROM search_org_list) AND NOT acn.deleted AND NOT acp.deleted AND acp.status IN (" . join(',', map { $self->QueryParser->quote_value($_) } @{ $filter->args }) . ") LIMIT 1)";
1081                     $where .= $filter->negate ? ' AND ' : ' OR ';
1082                     $where .= "${NOT}EXISTS(SELECT 1 FROM biblio.peer_bib_copy_map pr JOIN asset.copy acp ON pr.target_copy = acp.id WHERE m.source = pr.peer_record AND acp.circ_lib IN (SELECT * FROM search_org_list) AND NOT acp.deleted AND acp.status IN (" . join(',', map { $self->QueryParser->quote_value($_) } @{ $filter->args }) . ") LIMIT 1))";
1083                 }
1084             } elsif ($filter->name eq 'bib_source') {
1085                 if (@{$filter->args} > 0) {
1086                     $where .= $joiner if $where ne '(';
1087                     $where .= "${NOT}COALESCE(bre.source IN (" . join(',', map { $self->QueryParser->quote_value($_) } @{ $filter->args }) . "), false)";
1088                 }
1089             }
1090         }
1091     }
1092     warn "flatten(): full filter where => $where\n" if $self->QueryParser->debug;
1093
1094     return { rank_list => \@rank_list, from => $from, where => $where.')',  with => $with };
1095 }
1096
1097
1098 #-------------------------------
1099 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::filter;
1100 use base 'QueryParser::query_plan::filter';
1101
1102 #-------------------------------
1103 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::facet;
1104 use base 'QueryParser::query_plan::facet';
1105
1106 sub classname {
1107     my $self = shift;
1108     my ($classname) = split '\|', $self->name;
1109     return $classname;
1110 }
1111
1112 sub table {
1113     my $self = shift;
1114     return 'metabib.' . $self->classname . '_field_entry';
1115 }
1116
1117 sub fields {
1118     my $self = shift;
1119     my ($classname,@fields) = split '\|', $self->name;
1120     return \@fields;
1121 }
1122
1123 sub table_alias {
1124     my $self = shift;
1125
1126     my $table_alias = "$self";
1127     $table_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1128     $table_alias .= '_' . $self->name;
1129     $table_alias =~ s/\|/_/go;
1130
1131     return $table_alias;
1132 }
1133
1134
1135 #-------------------------------
1136 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::modifier;
1137 use base 'QueryParser::query_plan::modifier';
1138
1139 #-------------------------------
1140 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::node::atom;
1141 use base 'QueryParser::query_plan::node::atom';
1142
1143 sub sql {
1144     my $self = shift;
1145     my $sql = shift;
1146
1147     $self->{sql} = $sql if ($sql);
1148
1149     return $self->{sql} if ($self->{sql});
1150     return $self->buildSQL;
1151 }
1152
1153 sub buildSQL {
1154     my $self = shift;
1155
1156     my $classname = $self->node->classname;
1157
1158     return $self->sql("to_tsquery('$classname','')") if $self->{dummy};
1159
1160     my $normalizers = $self->node->plan->QueryParser->query_normalizers( $classname );
1161     my $fields = $self->node->fields;
1162
1163     $fields = $self->node->plan->QueryParser->search_fields->{$classname} if (!@$fields);
1164
1165     my %norms;
1166     my $pos = 0;
1167     for my $field (@$fields) {
1168         for my $nfield (keys %$normalizers) {
1169             for my $nizer ( @{$$normalizers{$nfield}} ) {
1170                 if ($field eq $nfield) {
1171                     my $param_string = OpenSRF::Utils::JSON->perl2JSON($nizer->{params});
1172                     if (!exists($norms{$nizer->{function}.$param_string})) {
1173                         $norms{$nizer->{function}.$param_string} = {p=>$pos++,n=>$nizer};
1174                     }
1175                 }
1176             }
1177         }
1178     }
1179
1180     my $sql = $self->node->plan->QueryParser->quote_value($self->content);
1181
1182     for my $n ( map { $$_{n} } sort { $$a{p} <=> $$b{p} } values %norms ) {
1183         $sql = join(', ', $sql, map { $self->node->plan->QueryParser->quote_value($_) } @{ $n->{params} });
1184         $sql = $n->{function}."($sql)";
1185     }
1186
1187     my $prefix = $self->prefix || '';
1188     my $suffix = $self->suffix || '';
1189
1190     $prefix = "'$prefix' ||" if $prefix;
1191     my $suffix_op = '';
1192     my $suffix_after = '';
1193
1194     $suffix_op = ":$suffix" if $suffix;
1195     $suffix_after = "|| '$suffix_op'" if $suffix;
1196
1197     $sql = "to_tsquery('$classname', COALESCE(NULLIF($prefix '(' || btrim(regexp_replace($sql,E'(?:\\\\s+|:)','$suffix_op&','g'),'&|') $suffix_after || ')', '()'), ''))";
1198
1199     return $self->sql($sql);
1200 }
1201
1202 #-------------------------------
1203 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::node;
1204 use base 'QueryParser::query_plan::node';
1205
1206 sub only_atoms {
1207     my $self = shift;
1208
1209     $self->{dummy_count} = 0;
1210
1211     my $atoms = $self->query_atoms;
1212     my @only_atoms;
1213     for my $a (@$atoms) {
1214         push(@only_atoms, $a) if (ref($a) && $a->isa('QueryParser::query_plan::node::atom'));
1215         $self->{dummy_count}++ if (ref($a) && $a->{dummy});
1216     }
1217
1218     return \@only_atoms;
1219 }
1220
1221 sub only_real_atoms {
1222     my $self = shift;
1223
1224     my $atoms = $self->query_atoms;
1225     my @only_real_atoms;
1226     for my $a (@$atoms) {
1227         push(@only_real_atoms, $a) if (ref($a) && $a->isa('QueryParser::query_plan::node::atom') && !($a->{dummy}));
1228     }
1229
1230     return \@only_real_atoms;
1231 }
1232
1233 sub dummy_count {
1234     my $self = shift;
1235     return $self->{dummy_count};
1236 }
1237
1238 sub table {
1239     my $self = shift;
1240     my $table = shift;
1241     $self->{table} = $table if ($table);
1242     return $self->{table} if $self->{table};
1243     return $self->table( 'metabib.' . $self->classname . '_field_entry' );
1244 }
1245
1246 sub table_alias {
1247     my $self = shift;
1248     my $table_alias = shift;
1249     $self->{table_alias} = $table_alias if ($table_alias);
1250     return $self->{table_alias} if ($self->{table_alias});
1251
1252     $table_alias = "$self";
1253     $table_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1254     $table_alias .= '_' . $self->requested_class;
1255     $table_alias =~ s/\|/_/go;
1256
1257     return $self->table_alias( $table_alias );
1258 }
1259
1260 sub tsquery {
1261     my $self = shift;
1262     return $self->{tsquery} if ($self->{tsquery});
1263
1264     for my $atom (@{$self->query_atoms}) {
1265         if (ref($atom)) {
1266             $self->{tsquery} .= "\n${spc}${spc}${spc}" .$atom->sql;
1267         } else {
1268             $self->{tsquery} .= $atom x 2;
1269         }
1270     }
1271
1272     return $self->{tsquery};
1273 }
1274
1275 sub rank {
1276     my $self = shift;
1277
1278     my $rank_norm_map = $self->plan->QueryParser->custom_data->{rank_cd_weight_map};
1279
1280     my $cover_density = 0;
1281     for my $norm ( keys %$rank_norm_map) {
1282         $cover_density += $$rank_norm_map{$norm} if ($self->plan->find_modifier($norm));
1283     }
1284
1285     return $self->{rank} if ($self->{rank});
1286     return $self->{rank} = 'ts_rank_cd(' . $self->table_alias . '.index_vector, ' . $self->table_alias . ".tsq, $cover_density)";
1287 }
1288
1289
1290 1;
1291