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