]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Storage/Driver/Pg/QueryParser.pm
bb12b7580441cbf9164018523387c7f970162ac1
[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 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     if (@{$$flat_plan{rank_list}}) {
578         $rel = "AVG(\n"
579              . ${spc} x 5 ."("
580              . join(")\n" . ${spc} x 5 . "+ (", @{$$flat_plan{rank_list}})
581              . ")\n"
582              . ${spc} x 4 . ")+1";
583     }
584
585     # find any supplied sort option
586     my ($sort_filter) = $self->find_filter('sort');
587     if ($sort_filter) {
588         $sort_filter = $sort_filter->args->[0];
589     } else {
590         $sort_filter = 'rel';
591     }
592
593     if (($filters{preferred_language} || $self->QueryParser->default_preferred_language) && ($filters{preferred_language_multiplier} || $self->QueryParser->default_preferred_language_multiplier)) {
594         my $pl = $self->QueryParser->quote_value( $filters{preferred_language} ? $filters{preferred_language} : $self->QueryParser->default_preferred_language );
595         my $plw = $filters{preferred_language_multiplier} ? $filters{preferred_language_multiplier} : $self->QueryParser->default_preferred_language_multiplier;
596         $rel = "($rel * COALESCE( NULLIF( FIRST(mrd.attrs \@> hstore('item_lang', $pl)), FALSE )::INT * $plw, 1))";
597     }
598     $rel = "1.0/($rel)::NUMERIC";
599
600     my $rank = $rel;
601
602     my $desc = 'ASC';
603     $desc = 'DESC' if ($self->find_modifier('descending'));
604
605     my $nullpos = 'NULLS LAST';
606     $nullpos = 'NULLS FIRST' if ($self->find_modifier('nullsfirst'));
607
608     if (grep {$_ eq $sort_filter} @{$self->QueryParser->dynamic_sorters}) {
609         $rank = "FIRST(mrd.attrs->'$sort_filter')"
610     } elsif ($sort_filter eq 'create_date') {
611         $rank = "FIRST((SELECT create_date FROM biblio.record_entry rbr WHERE rbr.id = m.source))";
612     } elsif ($sort_filter eq 'edit_date') {
613         $rank = "FIRST((SELECT edit_date FROM biblio.record_entry rbr WHERE rbr.id = m.source))";
614     } else {
615         # default to rel ranking
616         $rank = $rel;
617     }
618
619     my $key = 'm.source';
620     $key = 'm.metarecord' if (grep {$_->name eq 'metarecord' or $_->name eq 'metabib'} @{$self->modifiers});
621
622     my $core_limit = $self->QueryParser->core_limit || 25000;
623
624     my $flat_where = $$flat_plan{where};
625     if ($flat_where ne '') {
626         $flat_where = "AND (\n" . ${spc} x 5 . $flat_where . "\n" . ${spc} x 4 . ")";
627     }
628
629     my $site = $self->find_filter('site');
630     if ($site && $site->args) {
631         $site = $site->args->[0];
632         if ($site && $site !~ /^(-)?\d+$/) {
633             my $search = $editor->search_actor_org_unit({ shortname => $site });
634             $site = @$search[0]->id if($search && @$search);
635             $site = undef unless ($search);
636         }
637     } else {
638         $site = undef;
639     }
640     my $lasso = $self->find_filter('lasso');
641     if ($lasso && $lasso->args) {
642         $lasso = $lasso->args->[0];
643         if ($lasso && $lasso !~ /^\d+$/) {
644             my $search = $editor->search_actor_org_lasso({ name => $lasso });
645             $lasso = @$search[0]->id if($search && @$search);
646             $lasso = undef unless ($search);
647         }
648     } else {
649         $lasso = undef;
650     }
651     my $depth = $self->find_filter('depth');
652     if ($depth && $depth->args) {
653         $depth = $depth->args->[0];
654         if ($depth && $depth !~ /^\d+$/) {
655             # This *is* what metabib.pm has been doing....but it makes no sense to me. :/
656             # Should this be looking up the depth of the OU type on the OU in question?
657             my $search = $editor->search_actor_org_unit([{ name => $depth },{ opac_label => $depth }]);
658             $depth = @$search[0]->id if($search && @$search);
659             $depth = undef unless($search);
660         }
661     } else {
662         $depth = undef;
663     }
664     my $pref_ou = $self->find_filter('pref_ou');
665     if ($pref_ou && $pref_ou->args) {
666         $pref_ou = $pref_ou->args->[0];
667         if ($pref_ou && $pref_ou !~ /^(-)?\d+$/) {
668             my $search = $editor->search_actor_org_unit({ shortname => $pref_ou });
669             $pref_ou = @$search[0]->id if($search && @$search);
670             $pref_ou = undef unless ($search);
671         }
672     } else {
673         $pref_ou = undef;
674     }
675
676     # Supposedly at some point a site of 0 and a depth will equal user lasso id.
677     # We need OU buckets before that happens. 'my_lasso' is, I believe, the target filter for it.
678
679     $site = -$lasso if ($lasso);
680
681     # Default to the top of the org tree if we have nothing else. This would need tweaking for the user lasso bit.
682     if (!$site) {
683         my $search = $editor->search_actor_org_unit({ parent_ou => undef });
684         $site = @$search[0]->id if ($search);
685     }
686
687     my $depth_check = '';
688     $depth_check = ", $depth" if ($depth);
689
690     my $with = '';
691     $with .= "     search_org_list AS (\n";
692     if ($site < 0) {
693         # Lasso!
694         $lasso = -$site;
695         $with .= "       SELECT DISTINCT org_unit from actor.org_lasso_map WHERE lasso = $lasso\n";
696     } elsif ($site > 0) {
697         $with .= "       SELECT DISTINCT id FROM actor.org_unit_descendants($site$depth_check)\n";
698     } else {
699         # Placeholder for user lasso stuff.
700     }
701     $with .= "     ),\n";
702     $with .= "     luri_org_list AS (\n";
703     if ($site < 0) {
704         # We can re-use the lasso var, we already updated it above.
705         $with .= "       SELECT DISTINCT (actor.org_unit_ancestors(org_unit)).id from actor.org_lasso_map WHERE lasso = $lasso\n";
706     } elsif ($site > 0) {
707         $with .= "       SELECT DISTINCT id FROM actor.org_unit_ancestors($site)\n";
708     } else {
709         # Placeholder for user lasso stuff.
710     }
711     if ($pref_ou) {
712         $with .= "       UNION\n";
713         $with .= "       SELECT DISTINCT id FROM actor.org_unit_ancestors($pref_ou)\n";
714     }
715     $with .= "     )";
716     $with .= ",\n     " . $$flat_plan{with} if ($$flat_plan{with});
717
718     # Limit stuff
719     my $limit_where = <<"    SQL";
720 -- Filter records based on visibility
721         AND (
722             cbs.transcendant IS TRUE
723             OR
724             EXISTS(
725                 SELECT 1 FROM asset.call_number acn
726                     JOIN asset.uri_call_number_map aucnm ON acn.id = aucnm.call_number
727                     JOIN asset.uri uri ON aucnm.uri = uri.id
728                 WHERE NOT acn.deleted AND uri.active AND acn.record = m.source AND acn.owning_lib IN (
729                     SELECT * FROM luri_org_list
730                 )
731                 LIMIT 1
732             )
733             OR
734     SQL
735     if ($self->find_modifier('staff')) {
736         $limit_where .= <<"        SQL";
737             EXISTS(
738                 SELECT 1 FROM asset.call_number cn
739                     JOIN asset.copy cp ON (cp.call_number = cn.id)
740                 WHERE NOT cn.deleted
741                     AND NOT cp.deleted
742                     AND cp.circ_lib IN ( SELECT * FROM search_org_list )
743                     AND cn.record = m.source
744                 LIMIT 1
745             )
746             OR
747             EXISTS(
748                 SELECT 1 FROM biblio.peer_bib_copy_map pr
749                     JOIN asset.copy cp ON (cp.id = pr.target_copy)
750                 WHERE NOT cp.deleted
751                     AND cp.circ_lib IN ( SELECT * FROM search_org_list )
752                     AND pr.peer_record = m.source
753                 LIMIT 1
754             )
755             OR (
756                 NOT EXISTS(
757                     SELECT 1 FROM asset.call_number cn
758                         JOIN asset.copy cp ON (cp.call_number = cn.id)
759                     WHERE cn.record = m.source
760                         AND NOT cp.deleted
761                     LIMIT 1
762                 )
763                 AND
764                 NOT EXISTS(
765                     SELECT 1 FROM biblio.peer_bib_copy_map pr
766                         JOIN asset.copy cp ON (cp.id = pr.target_copy)
767                     WHERE NOT cp.deleted
768                         AND pr.peer_record = m.source
769                     LIMIT 1
770                 )
771             )
772         SQL
773     } else {
774         $limit_where .= <<"        SQL";
775             EXISTS(
776                 SELECT 1 FROM asset.opac_visible_copies
777                 WHERE circ_lib IN ( SELECT * FROM search_org_list )
778                     AND record = m.source
779                 LIMIT 1
780             )
781             OR
782             EXISTS(
783                 SELECT 1 FROM biblio.peer_bib_copy_map pr
784                     JOIN asset.opac_visible_copies cp ON (cp.copy_id = pr.target_copy)
785                 WHERE cp.circ_lib IN ( SELECT * FROM search_org_list )
786                     AND pr.peer_record = m.source
787                 LIMIT 1
788             )
789         SQL
790     }
791     $limit_where .= "        )";
792
793     # For single records we want the record id
794     # For metarecords we want NULL or the only record ID.
795     my $agg_record = 'm.source AS record';
796     if ($key =~ /metarecord/) {
797         $agg_record = 'CASE WHEN COUNT(DISTINCT m.source) = 1 THEN FIRST(m.source) ELSE NULL END AS record';
798     }
799
800     my $sql = <<SQL;
801 WITH
802 $with
803 SELECT  $key AS id,
804         $agg_record,
805         $rel AS rel,
806         $rank AS rank, 
807         FIRST(mrd.attrs->'date1') AS tie_break
808   FROM  metabib.metarecord_source_map m
809         $$flat_plan{from}
810         INNER JOIN metabib.record_attr mrd ON m.source = mrd.id
811         INNER JOIN biblio.record_entry bre ON m.source = bre.id
812         LEFT JOIN config.bib_source cbs ON bre.source = cbs.id
813   WHERE 1=1
814         $flat_where
815         $limit_where
816   GROUP BY 1
817   ORDER BY 4 $desc $nullpos, 5 DESC $nullpos, 3 DESC
818   LIMIT $core_limit
819 SQL
820
821     warn $sql if $self->QueryParser->debug;
822     return $sql;
823
824 }
825
826
827 sub rel_bump {
828     my $self = shift;
829     my $node = shift;
830     my $bump = shift;
831     my $multiplier = shift;
832
833     my $only_atoms = $node->only_real_atoms;
834     return '' if (!@$only_atoms);
835
836     if ($bump eq 'first_word') {
837         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)";
838     } elsif ($bump eq 'full_match') {
839         return "/* full_match */ 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     } elsif ($bump eq 'word_order') {
842         return "/* word_order */ COALESCE(NULLIF( (search_normalize(".$node->table_alias.".value) ~ (".
843                     join( "||'.*'||", map { "search_normalize(".$self->QueryParser->quote_phrase_value($_->content).")" } @$only_atoms ).")), FALSE )::INT * $multiplier, 1)";
844     }
845
846     return '';
847 }
848
849 sub flatten {
850     my $self = shift;
851
852     my $from = shift || '';
853     my $where = shift || '';
854     my $with = '';
855
856     my @rank_list;
857     for my $node ( @{$self->query_nodes} ) {
858
859         if (ref($node)) {
860             if ($node->isa( 'QueryParser::query_plan::node' )) {
861
862                 unless (@{$node->only_atoms}) {
863                     push @rank_list, '1';
864                     $where .= 'TRUE';
865                     next;
866                 }
867
868                 my $table = $node->table;
869                 my $talias = $node->table_alias;
870
871                 my $node_rank = 'COALESCE(' . $node->rank . " * ${talias}.weight, 0.0)";
872
873                 $from .= "\n" . ${spc} x 4 ."LEFT JOIN (\n"
874                       . ${spc} x 5 . "SELECT fe.*, fe_weight.weight, ${talias}_xq.tsq /* search */\n"
875                       . ${spc} x 6 . "FROM  $table AS fe";
876                 $from .= "\n" . ${spc} x 7 . "JOIN config.metabib_field AS fe_weight ON (fe_weight.id = fe.field)";
877
878                 if ($node->dummy_count < @{$node->only_atoms} ) {
879                     $with .= ",\n     " if $with;
880                     $with .= "${talias}_xq AS (SELECT ". $node->tsquery ." AS tsq )";
881                     $from .= "\n" . ${spc} x 6 . "JOIN ${talias}_xq ON (fe.index_vector @@ ${talias}_xq.tsq)";
882                 } else {
883                     $from .= "\n" . ${spc} x 6 . ", (SELECT NULL::tsquery AS tsq ) AS ${talias}_xq";
884                 }
885
886                 my @bump_fields;
887                 if (@{$node->fields} > 0) {
888                     @bump_fields = @{$node->fields};
889
890                     my @field_ids = grep defined, (
891                         map {
892                             $self->QueryParser->search_field_ids_by_class(
893                                 $node->classname, $_
894                             )->[0]
895                         } @bump_fields
896                     );
897                     if (@field_ids) {
898                         $from .= "\n" . ${spc} x 6 . "WHERE fe_weight.id IN  (" .
899                             join(',', @field_ids) . ")";
900                     }
901
902                 } else {
903                     @bump_fields = @{$self->QueryParser->search_fields->{$node->classname}};
904                 }
905
906                 $from .= "\n" . ${spc} x 4 . ") AS $talias ON (m.source = ${talias}.source)";
907
908
909                 my %used_bumps;
910                 for my $field ( @bump_fields ) {
911                     my $bumps = $self->QueryParser->find_relevance_bumps( $node->classname => $field );
912                     for my $b (keys %$bumps) {
913                         next if (!$$bumps{$b}{active});
914                         next if ($used_bumps{$b});
915                         $used_bumps{$b} = 1;
916
917                         next if ($$bumps{$b}{multiplier} == 1); # optimization to remove unneeded bumps
918
919                         my $bump_case = $self->rel_bump( $node, $b, $$bumps{$b}{multiplier} );
920                         $node_rank .= "\n" . ${spc} x 5 . "* " . $bump_case if ($bump_case);
921                     }
922                 }
923
924
925                 $where .= '(' . $talias . ".id IS NOT NULL";
926                 if (@{$node->phrases}) {
927                     $where .= ' AND ' . join(' AND ', map {
928                         "${talias}.value ~* ".$self->QueryParser->quote_phrase_value($_)
929                     } @{$node->phrases});
930                 }
931                 if (@{$node->unphrases}) {
932                     $where .= ' AND ' . join(' AND ', map {
933                         "${talias}.value !~* ".$self->QueryParser->quote_phrase_value($_)
934                     } @{$node->unphrases});
935                 }
936                 for my $atom (@{$node->only_real_atoms}) {
937                     next unless $atom->{content} && $atom->{content} =~ /(^\^|\$$)/;
938                     $where .= " AND ${talias}.value ~* ".$self->QueryParser->quote_phrase_value($atom->{content});
939                 }
940                 $where .= ')';
941
942                 push @rank_list, $node_rank;
943
944             } elsif ($node->isa( 'QueryParser::query_plan::facet' )) {
945
946                 my $table = $node->table;
947                 my $talias = $node->table_alias;
948
949                 my @field_ids;
950                 if (@{$node->fields} > 0) {
951                     push(@field_ids, $self->QueryParser->facet_field_ids_by_class( $node->classname, $_ )->[0]) for (@{$node->fields});
952                 } else {
953                     @field_ids = @{ $self->QueryParser->facet_field_ids_by_class( $node->classname ) };
954                 }
955
956                 my $join_type = ($node->negate or !$self->top_plan) ? 'LEFT' : 'INNER';
957                 $from .= "\n${spc}$join_type JOIN /* facet */ metabib.facet_entry $talias ON (\n"
958                       . ${spc} x 2 . "m.source = ${talias}.source\n"
959                       . ${spc} x 2 . "AND SUBSTRING(${talias}.value,1,1024) IN ("
960                       . join(",", map { $self->QueryParser->quote_value($_) } @{$node->values}) . ")\n"
961                       . ${spc} x 2 ."AND ${talias}.field IN (". join(',', @field_ids) . ")\n"
962                       . "${spc})";
963
964                 if ($join_type ne 'INNER') {
965                     my $NOT = $node->negate ? '' : ' NOT';
966                     $where .= "${talias}.id IS$NOT NULL";
967                 } elsif ($where ne '') {
968                     # Strip extra joiner
969                     $where =~ s/(\s|\n)+(AND|OR)\s$//;
970                 }
971
972             } else {
973                 my $subnode = $node->flatten;
974
975                 # strip the trailing bool from the previous loop if there is 
976                 # nothing to add to the where within this loop.
977                 if ($$subnode{where} eq '') {
978                     $where =~ s/(\s|\n)+(AND|OR)\s$//;
979                 }
980
981                 push(@rank_list, @{$$subnode{rank_list}});
982                 $from .= $$subnode{from};
983
984                 if ($$subnode{where} ne '') {
985                     $where .= "(\n"
986                            . ${spc} x ($self->plan_level + 6) . $$subnode{where} . "\n"
987                            . ${spc} x ($self->plan_level + 5) . ')';
988                 }
989
990                 if ($$subnode{with}) {
991                     $with .= ",\n     " if $with;
992                     $with .= $$subnode{with};
993                 }
994             }
995         } else {
996
997             warn "flatten(): appending WHERE bool to: $where\n" if $self->QueryParser->debug;
998
999             if ($where ne '') {
1000                 $where .= "\n" . ${spc} x ( $self->plan_level + 5 ) . 'AND ' if ($node eq '&');
1001                 $where .= "\n" . ${spc} x ( $self->plan_level + 5 ) . 'OR ' if ($node eq '|');
1002             }
1003         }
1004     }
1005
1006     my $joiner = "\n" . ${spc} x ( $self->plan_level + 5 ) . ($self->joiner eq '&' ? 'AND ' : 'OR ');
1007     # for each dynamic filter, build more of the WHERE clause
1008     for my $filter (@{$self->filters}) {
1009         my $NOT = $filter->negate ? 'NOT ' : '';
1010         if (grep { $_ eq $filter->name } @{ $self->QueryParser->dynamic_filters }) {
1011
1012             warn "flatten(): processing dynamic filter ". $filter->name ."\n"
1013                 if $self->QueryParser->debug;
1014
1015             # bool joiner for intra-plan nodes/filters
1016             $where .= $joiner if $where ne '';
1017
1018             my @fargs = @{$filter->args};
1019             my $fname = $filter->name;
1020             $fname = 'item_lang' if $fname eq 'language'; #XXX filter aliases 
1021
1022             $where .= sprintf(
1023                 "${NOT}COALESCE((mrd.attrs->'%s') IN (%s), false)", $fname, 
1024                 join(',', map { $self->QueryParser->quote_value($_) } @fargs)
1025             );
1026
1027             warn "flatten(): filter where => $where\n"
1028                 if $self->QueryParser->debug;
1029         } else {
1030             if ($filter->name eq 'before') {
1031                 if (@{$filter->args} == 1) {
1032                     $where .= $joiner if $where ne '';
1033                     $where .= "${NOT}COALESCE((mrd.attrs->'date1') <= "
1034                            . $self->QueryParser->quote_value($filter->args->[0])
1035                            . ", false)";
1036                 }
1037             } elsif ($filter->name eq 'after') {
1038                 if (@{$filter->args} == 1) {
1039                     $where .= $joiner if $where ne '';
1040                     $where .= "${NOT}COALESCE((mrd.attrs->'date1') >= "
1041                            . $self->QueryParser->quote_value($filter->args->[0])
1042                            . ", false)";
1043                 }
1044             } elsif ($filter->name eq 'during') {
1045                 if (@{$filter->args} == 1) {
1046                     $where .= $joiner if $where ne '';
1047                     $where .= "${NOT}COALESCE("
1048                            . $self->QueryParser->quote_value($filter->args->[0])
1049                            . " BETWEEN (mrd.attrs->'date1') AND (mrd.attrs->'date2'), false)";
1050                 }
1051             } elsif ($filter->name eq 'between') {
1052                 if (@{$filter->args} == 2) {
1053                     $where .= $joiner if $where ne '';
1054                     $where .= "${NOT}COALESCE((mrd.attrs->'date1') BETWEEN "
1055                            . $self->QueryParser->quote_value($filter->args->[0])
1056                            . " AND "
1057                            . $self->QueryParser->quote_value($filter->args->[1])
1058                            . ", false)";
1059                 }
1060             } elsif ($filter->name eq 'container') {
1061                 if (@{$filter->args} >= 3) {
1062                     my ($class, $ctype, $cid, $token) = @{$filter->args};
1063                     my $perm_join = '';
1064                     my $rec_join = '';
1065                     my $rec_field = 'ci.target_biblio_record_entry';
1066                     if ($class eq 'bre') {
1067                         $class = 'biblio_record_entry';
1068                     } elsif ($class eq 'acn') {
1069                         $class = 'call_number';
1070                         $rec_field = 'cn.record';
1071                         $rec_join = 'JOIN asset.call_number cn ON (ci.target_call_number = cn.id)';
1072                     } elsif ($class eq 'acp') {
1073                         $class = 'copy';
1074                         $rec_field = 'cn.record';
1075                         $rec_join = 'JOIN asset.copy cp ON (ci.target_copy = cp.id) JOIN asset.call_number cn ON (cp.call_number = cn.id)';
1076                     } else {
1077                         $class = undef;
1078                     }
1079
1080                     if ($class) {
1081                         my ($u,$e) = $apputils->checksesperm($token) if ($token);
1082                         $perm_join = ' OR c.owner = ' . $u->id if ($u && !$e);
1083                         $where .= $joiner if $where ne '';
1084                         my $spcdepth = $self->plan_level + 5;
1085                         if($class eq 'copy') {
1086                             $spcdepth += 1;
1087                             $where .= "(\n" . ${spc} x $spcdepth;
1088                         }
1089                         $where .= "${NOT}EXISTS(\n"
1090                                . ${spc} x ($spcdepth + 1) . "SELECT 1 FROM container.${class}_bucket_item ci\n"
1091                                . ${spc} x ($spcdepth + 4) . "JOIN container.${class}_bucket c ON (c.id = ci.bucket) $rec_join\n"
1092                                . ${spc} x ($spcdepth + 1) . "WHERE c.btype = " . $self->QueryParser->quote_value($ctype) . "\n"
1093                                . ${spc} x ($spcdepth + 4) . "AND c.id = " . $self->QueryParser->quote_value($cid) . "\n"
1094                                . ${spc} x ($spcdepth + 4) . "AND (c.pub IS TRUE$perm_join)\n"
1095                                . ${spc} x ($spcdepth + 4) . "AND $rec_field = m.source\n"
1096                                . ${spc} x ($spcdepth + 1) . "LIMIT 1\n"
1097                                . ${spc} x $spcdepth . ")";
1098                         if ($class eq 'copy') {
1099                             my $subjoiner = $filter->negate ? 'AND' : 'OR';
1100                             $where .= "\n"
1101                                    . ${spc} x ($spcdepth) . $subjoiner . "\n"
1102                                    . ${spc} x ($spcdepth) . "${NOT}EXISTS(\n"
1103                                    . ${spc} x ($spcdepth + 1) . "SELECT 1 FROM container.copy_bucket_item ci\n"
1104                                    . ${spc} x ($spcdepth + 4) . "JOIN container.copy_bucket c ON (c.id = ci.bucket)\n"
1105                                    . ${spc} x ($spcdepth + 4) . "JOIN biblio.peer_bib_copy_map pr ON ci.target_copy = pr.target_copy\n"
1106                                    . ${spc} x ($spcdepth + 1) . "WHERE c.btype = " . $self->QueryParser->quote_value($cid) . "\n"
1107                                    . ${spc} x ($spcdepth + 4) . "AND (c.pub IS TRUE$perm_join)\n"
1108                                    . ${spc} x ($spcdepth + 4) . "AND pr.peer_record = m.source\n"
1109                                    . ${spc} x ($spcdepth + 1) . "LIMIT 1\n"
1110                                    . ${spc} x $spcdepth . ")\n"
1111                                    . ${spc} x ($spcdepth - 1) . ")";
1112                         }
1113                     }
1114                 }
1115             } elsif ($filter->name eq 'record_list') {
1116                 if (@{$filter->args} > 0) {
1117                     my $key = 'm.source';
1118                     $key = 'm.metarecord' if (grep {$_->name eq 'metarecord' or $_->name eq 'metabib'} @{$self->QueryParser->parse_tree->modifiers});
1119                     $where .= $joiner if $where ne '';
1120                     $where .= "$key ${NOT}IN (" . join(',', map { $self->QueryParser->quote_value($_) } @{$filter->args}) . ')';
1121                 }
1122             } elsif ($filter->name eq 'locations') {
1123                 if (@{$filter->args} > 0) {
1124                     my $spcdepth = $self->plan_level + 5;
1125                     $where .= $joiner if $where ne '';
1126                     $where .= "(\n"
1127                            . ${spc} x ($spcdepth + 1) . "${NOT}EXISTS(\n"
1128                            . ${spc} x ($spcdepth + 2) . "SELECT 1 FROM asset.call_number acn\n"
1129                            . ${spc} x ($spcdepth + 5) . "JOIN asset.copy acp ON acn.id = acp.call_number\n"
1130                            . ${spc} x ($spcdepth + 2) . "WHERE m.source = acn.record\n"
1131                            . ${spc} x ($spcdepth + 5) . "AND acp.circ_lib IN (SELECT * FROM search_org_list)\n"
1132                            . ${spc} x ($spcdepth + 5) . "AND NOT acn.deleted\n"
1133                            . ${spc} x ($spcdepth + 5) . "AND NOT acp.deleted\n"
1134                            . ${spc} x ($spcdepth + 5) . "AND acp.location IN (" . join(',', map { $self->QueryParser->quote_value($_) } @{ $filter->args }) . ")\n"
1135                            . ${spc} x ($spcdepth + 2) . "LIMIT 1\n"
1136                            . ${spc} x ($spcdepth + 1) . ")\n"
1137                            . ${spc} x ($spcdepth + 1) . ($filter->negate ? 'AND' : 'OR') . "\n"
1138                            . ${spc} x ($spcdepth + 1) . "${NOT}EXISTS(\n"
1139                            . ${spc} x ($spcdepth + 2) . "SELECT 1 FROM biblio.peer_bib_copy_map pr\n"
1140                            . ${spc} x ($spcdepth + 5) . "JOIN asset.copy acp ON pr.target_copy = acp.id\n"
1141                            . ${spc} x ($spcdepth + 2) . "WHERE m.source = pr.peer_record\n"
1142                            . ${spc} x ($spcdepth + 5) . "AND acp.circ_lib IN (SELECT * FROM search_org_list)\n"
1143                            . ${spc} x ($spcdepth + 5) . "AND NOT acp.deleted\n"
1144                            . ${spc} x ($spcdepth + 5) . "AND acp.location IN (" . join(',', map { $self->QueryParser->quote_value($_) } @{ $filter->args }) . ")\n"
1145                            . ${spc} x ($spcdepth + 2) . "LIMIT 1\n"
1146                            . ${spc} x ($spcdepth + 1) . ")\n"
1147                            . ${spc} x $spcdepth . ")";
1148                 }
1149             } elsif ($filter->name eq 'statuses') {
1150                 if (@{$filter->args} > 0) {
1151                     my $spcdepth = $self->plan_level + 5;
1152                     $where .= $joiner if $where ne '';
1153                     $where .= "(\n"
1154                            . ${spc} x ($spcdepth + 1) . "${NOT}EXISTS(\n"
1155                            . ${spc} x ($spcdepth + 2) . "SELECT 1 FROM asset.call_number acn\n"
1156                            . ${spc} x ($spcdepth + 5) . "JOIN asset.copy acp ON acn.id = acp.call_number\n"
1157                            . ${spc} x ($spcdepth + 2) . "WHERE m.source = acn.record\n"
1158                            . ${spc} x ($spcdepth + 5) . "AND acp.circ_lib IN (SELECT * FROM search_org_list)\n"
1159                            . ${spc} x ($spcdepth + 5) . "AND NOT acn.deleted\n"
1160                            . ${spc} x ($spcdepth + 5) . "AND NOT acp.deleted\n"
1161                            . ${spc} x ($spcdepth + 5) . "AND acp.status IN (" . join(',', map { $self->QueryParser->quote_value($_) } @{ $filter->args }) . ")\n"
1162                            . ${spc} x ($spcdepth + 2) . "LIMIT 1\n"
1163                            . ${spc} x ($spcdepth + 1) . ")\n"
1164                            . ${spc} x ($spcdepth + 1) . ($filter->negate ? 'AND' : 'OR') . "\n"
1165                            . ${spc} x ($spcdepth + 1) . "${NOT}EXISTS(\n"
1166                            . ${spc} x ($spcdepth + 2) . "SELECT 1 FROM biblio.peer_bib_copy_map pr\n"
1167                            . ${spc} x ($spcdepth + 5) . "JOIN asset.copy acp ON pr.target_copy = acp.id\n"
1168                            . ${spc} x ($spcdepth + 2) . "WHERE m.source = pr.peer_record\n"
1169                            . ${spc} x ($spcdepth + 5) . "AND acp.circ_lib IN (SELECT * FROM search_org_list)\n"
1170                            . ${spc} x ($spcdepth + 5) . "AND NOT acp.deleted\n"
1171                            . ${spc} x ($spcdepth + 5) . "AND acp.status IN (" . join(',', map { $self->QueryParser->quote_value($_) } @{ $filter->args }) . ")\n"
1172                            . ${spc} x ($spcdepth + 2) . "LIMIT 1\n"
1173                            . ${spc} x ($spcdepth + 1) . ")\n"
1174                            . ${spc} x $spcdepth . ")";
1175                 }
1176             } elsif ($filter->name eq 'bib_source') {
1177                 if (@{$filter->args} > 0) {
1178                     $where .= $joiner if $where ne '';
1179                     $where .= "${NOT}COALESCE(bre.source IN ("
1180                            . join(',', map { $self->QueryParser->quote_value($_) } @{ $filter->args })
1181                            . "), false)";
1182                 }
1183             }
1184         }
1185     }
1186     warn "flatten(): full filter where => $where\n" if $self->QueryParser->debug;
1187
1188     return { rank_list => \@rank_list, from => $from, where => $where,  with => $with };
1189 }
1190
1191
1192 #-------------------------------
1193 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::filter;
1194 use base 'QueryParser::query_plan::filter';
1195
1196 #-------------------------------
1197 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::facet;
1198 use base 'QueryParser::query_plan::facet';
1199
1200 sub classname {
1201     my $self = shift;
1202     my ($classname) = split '\|', $self->name;
1203     return $classname;
1204 }
1205
1206 sub table {
1207     my $self = shift;
1208     return 'metabib.' . $self->classname . '_field_entry';
1209 }
1210
1211 sub fields {
1212     my $self = shift;
1213     my ($classname,@fields) = split '\|', $self->name;
1214     return \@fields;
1215 }
1216
1217 sub table_alias {
1218     my $self = shift;
1219
1220     my $table_alias = "$self";
1221     $table_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1222     $table_alias .= '_' . $self->name;
1223     $table_alias =~ s/\|/_/go;
1224
1225     return $table_alias;
1226 }
1227
1228
1229 #-------------------------------
1230 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::modifier;
1231 use base 'QueryParser::query_plan::modifier';
1232
1233 #-------------------------------
1234 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::node::atom;
1235 use base 'QueryParser::query_plan::node::atom';
1236
1237 sub sql {
1238     my $self = shift;
1239     my $sql = shift;
1240
1241     $self->{sql} = $sql if ($sql);
1242
1243     return $self->{sql} if ($self->{sql});
1244     return $self->buildSQL;
1245 }
1246
1247 sub buildSQL {
1248     my $self = shift;
1249
1250     my $classname = $self->node->classname;
1251
1252     return $self->sql("to_tsquery('$classname','')") if $self->{dummy};
1253
1254     my $normalizers = $self->node->plan->QueryParser->query_normalizers( $classname );
1255     my $fields = $self->node->fields;
1256
1257     $fields = $self->node->plan->QueryParser->search_fields->{$classname} if (!@$fields);
1258
1259     my %norms;
1260     my $pos = 0;
1261     for my $field (@$fields) {
1262         for my $nfield (keys %$normalizers) {
1263             for my $nizer ( @{$$normalizers{$nfield}} ) {
1264                 if ($field eq $nfield) {
1265                     my $param_string = OpenSRF::Utils::JSON->perl2JSON($nizer->{params});
1266                     if (!exists($norms{$nizer->{function}.$param_string})) {
1267                         $norms{$nizer->{function}.$param_string} = {p=>$pos++,n=>$nizer};
1268                     }
1269                 }
1270             }
1271         }
1272     }
1273
1274     my $sql = $self->node->plan->QueryParser->quote_value($self->content);
1275
1276     for my $n ( map { $$_{n} } sort { $$a{p} <=> $$b{p} } values %norms ) {
1277         $sql = join(', ', $sql, map { $self->node->plan->QueryParser->quote_value($_) } @{ $n->{params} });
1278         $sql = $n->{function}."($sql)";
1279     }
1280
1281     my $prefix = $self->prefix || '';
1282     my $suffix = $self->suffix || '';
1283
1284     $prefix = "'$prefix' ||" if $prefix;
1285     my $suffix_op = '';
1286     my $suffix_after = '';
1287
1288     $suffix_op = ":$suffix" if $suffix;
1289     $suffix_after = "|| '$suffix_op'" if $suffix;
1290
1291     $sql = "to_tsquery('$classname', COALESCE(NULLIF($prefix '(' || btrim(regexp_replace($sql,E'(?:\\\\s+|:)','$suffix_op&','g'),'&|') $suffix_after || ')', '()'), ''))";
1292
1293     return $self->sql($sql);
1294 }
1295
1296 #-------------------------------
1297 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::node;
1298 use base 'QueryParser::query_plan::node';
1299
1300 sub only_atoms {
1301     my $self = shift;
1302
1303     $self->{dummy_count} = 0;
1304
1305     my $atoms = $self->query_atoms;
1306     my @only_atoms;
1307     for my $a (@$atoms) {
1308         push(@only_atoms, $a) if (ref($a) && $a->isa('QueryParser::query_plan::node::atom'));
1309         $self->{dummy_count}++ if (ref($a) && $a->{dummy});
1310     }
1311
1312     return \@only_atoms;
1313 }
1314
1315 sub only_real_atoms {
1316     my $self = shift;
1317
1318     my $atoms = $self->query_atoms;
1319     my @only_real_atoms;
1320     for my $a (@$atoms) {
1321         push(@only_real_atoms, $a) if (ref($a) && $a->isa('QueryParser::query_plan::node::atom') && !($a->{dummy}));
1322     }
1323
1324     return \@only_real_atoms;
1325 }
1326
1327 sub dummy_count {
1328     my $self = shift;
1329     return $self->{dummy_count};
1330 }
1331
1332 sub table {
1333     my $self = shift;
1334     my $table = shift;
1335     $self->{table} = $table if ($table);
1336     return $self->{table} if $self->{table};
1337     return $self->table( 'metabib.' . $self->classname . '_field_entry' );
1338 }
1339
1340 sub table_alias {
1341     my $self = shift;
1342     my $table_alias = shift;
1343     $self->{table_alias} = $table_alias if ($table_alias);
1344     return $self->{table_alias} if ($self->{table_alias});
1345
1346     $table_alias = "$self";
1347     $table_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1348     $table_alias .= '_' . $self->requested_class;
1349     $table_alias =~ s/\|/_/go;
1350
1351     return $self->table_alias( $table_alias );
1352 }
1353
1354 sub tsquery {
1355     my $self = shift;
1356     return $self->{tsquery} if ($self->{tsquery});
1357
1358     for my $atom (@{$self->query_atoms}) {
1359         if (ref($atom)) {
1360             $self->{tsquery} .= "\n" . ${spc} x 3 . $atom->sql;
1361         } else {
1362             $self->{tsquery} .= $atom x 2;
1363         }
1364     }
1365
1366     return $self->{tsquery};
1367 }
1368
1369 sub rank {
1370     my $self = shift;
1371
1372     my $rank_norm_map = $self->plan->QueryParser->custom_data->{rank_cd_weight_map};
1373
1374     my $cover_density = 0;
1375     for my $norm ( keys %$rank_norm_map) {
1376         $cover_density += $$rank_norm_map{$norm} if ($self->plan->find_modifier($norm));
1377     }
1378
1379     return $self->{rank} if ($self->{rank});
1380     return $self->{rank} = 'ts_rank_cd(' . $self->table_alias . '.index_vector, ' . $self->table_alias . ".tsq, $cover_density)";
1381 }
1382
1383
1384 1;
1385