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