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