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