1 # BEGIN BPS TAGGED BLOCK {{{
5 # This software is Copyright (c) 1996-2013 Best Practical Solutions, LLC
6 # <sales@bestpractical.com>
8 # (Except where explicitly superseded by other copyright notices)
13 # This work is made available to you under the terms of Version 2 of
14 # the GNU General Public License. A copy of that license should have
15 # been provided with this software, but in any event can be snarfed
18 # This work is distributed in the hope that it will be useful, but
19 # WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 # General Public License for more details.
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
26 # 02110-1301 or visit their web page on the internet at
27 # http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
30 # CONTRIBUTION SUBMISSION POLICY:
32 # (The following paragraph is not intended to limit the rights granted
33 # to you to modify and distribute this software under the terms of
34 # the GNU General Public License and is only of importance to you if
35 # you choose to contribute your changes and enhancements to the
36 # community by submitting them to Best Practical Solutions, LLC.)
38 # By intentionally submitting any modifications, corrections or
39 # derivatives to this work, or any other work intended for use with
40 # Request Tracker, to Best Practical Solutions, LLC, you confirm that
41 # you are the copyright holder for those contributions and you grant
42 # Best Practical Solutions, LLC a nonexclusive, worldwide, irrevocable,
43 # royalty-free, perpetual, license to use, copy, create derivative
44 # works based on those contributions, and sublicense and distribute
45 # those contributions and any derivatives thereof.
47 # END BPS TAGGED BLOCK }}}
57 # Import configuration data from the lexcial scope of __PACKAGE__ (or
58 # at least where those two Subroutines are defined.)
60 our (%FIELD_METADATA, %LOWER_CASE_FIELDS, %dispatch, %can_bundle);
65 # Private Member Variables (which should get cleaned)
66 $self->{'_sql_transalias'} = undef;
67 $self->{'_sql_trattachalias'} = undef;
68 $self->{'_sql_cf_alias'} = undef;
69 $self->{'_sql_object_cfv_alias'} = undef;
70 $self->{'_sql_watcher_join_users_alias'} = undef;
71 $self->{'_sql_query'} = '';
72 $self->{'_sql_looking_at'} = {};
78 if ($args{'FIELD'} eq 'EffectiveId' &&
79 (!$args{'ALIAS'} || $args{'ALIAS'} eq 'main' ) ) {
80 $self->{'looking_at_effective_id'} = 1;
83 if ($args{'FIELD'} eq 'Type' &&
84 (!$args{'ALIAS'} || $args{'ALIAS'} eq 'main' ) ) {
85 $self->{'looking_at_type'} = 1;
88 # All SQL stuff goes into one SB subclause so we can deal with all
90 $self->SUPER::Limit(%args,
91 SUBCLAUSE => 'ticketsql');
95 # All SQL stuff goes into one SB subclause so we can deal with all
99 $this->SUPER::Join(@_,
100 SUBCLAUSE => 'ticketsql');
105 $_[0]->SUPER::_OpenParen( 'ticketsql' );
108 $_[0]->SUPER::_CloseParen( 'ticketsql' );
115 =head2 Robert's Simple SQL Parser
117 Documentation In Progress
119 The Parser/Tokenizer is a relatively simple state machine that scans through a SQL WHERE clause type string extracting a token at a time (where a token is:
121 VALUE -> quoted string or number
122 AGGREGator -> AND or OR
123 KEYWORD -> quoted string or single word
124 OPerator -> =,!=,LIKE,etc..
125 PARENthesis -> open or close.
127 And that stream of tokens is passed through the "machine" in order to build up a structure that looks like:
133 That also deals with parenthesis for nesting. (The parentheses are
134 just handed off the SearchBuilder)
139 my ($self, @bundle) = @_;
140 return unless @bundle;
142 if ( @bundle == 1 ) {
143 $bundle[0]->{'dispatch'}->(
149 ENTRYAGGREGATOR => $bundle[0]->{ea},
150 SUBKEY => $bundle[0]->{subkey},
155 foreach my $chunk (@bundle) {
161 ENTRYAGGREGATOR => $chunk->{ea},
162 SUBKEY => $chunk->{subkey},
165 $bundle[0]->{dispatch}->( $self, \@args );
170 my ($self,$string) = @_;
175 $callback{'OpenParen'} = sub {
176 $self->_close_bundle(@bundle); @bundle = ();
179 $callback{'CloseParen'} = sub {
180 $self->_close_bundle(@bundle); @bundle = ();
183 $callback{'EntryAggregator'} = sub { $ea = $_[0] || '' };
184 $callback{'Condition'} = sub {
185 my ($key, $op, $value) = @_;
187 # key has dot then it's compound variant and we have subkey
189 ($key, $subkey) = ($1, $2) if $key =~ /^([^\.]+)\.(.+)$/;
191 # normalize key and get class (type)
193 if (exists $LOWER_CASE_FIELDS{lc $key}) {
194 $key = $LOWER_CASE_FIELDS{lc $key};
195 $class = $FIELD_METADATA{$key}->[0];
197 die "Unknown field '$key' in '$string'" unless $class;
199 # replace __CurrentUser__ with id
200 $value = $self->CurrentUser->id if $value eq '__CurrentUser__';
203 unless( $dispatch{ $class } ) {
204 die "No dispatch method for class '$class'"
206 my $sub = $dispatch{ $class };
208 if ( $can_bundle{ $class }
210 || ( $bundle[-1]->{dispatch} == $sub
211 && $bundle[-1]->{key} eq $key
212 && $bundle[-1]->{subkey} eq $subkey
227 $self->_close_bundle(@bundle); @bundle = ();
228 $sub->( $self, $key, $op, $value,
229 SUBCLAUSE => '', # don't need anymore
230 ENTRYAGGREGATOR => $ea,
234 $self->{_sql_looking_at}{lc $key} = 1;
237 RT::SQL::Parse($string, \%callback);
238 $self->_close_bundle(@bundle); @bundle = ();
250 for my $f (keys %{$clauses}) {
254 # Build SQL from the data hash
255 for my $data ( @{ $clauses->{$f} } ) {
256 $sql .= $data->[0] unless $first; $first=0; # ENTRYAGGREGATOR
257 $sql .= " '". $data->[2] . "' "; # FIELD
258 $sql .= $data->[3] . " "; # OPERATOR
259 $sql .= "'". $data->[4] . "' "; # VALUE
262 push @sql, " ( " . $sql . " ) ";
265 return join("AND",@sql);
270 Convert a RT-SQL string into a set of SearchBuilder restrictions.
272 Returns (1, 'Status message') on success and (0, 'Error Message') on
281 my ($self,$query) = @_;
284 # preserve first_row and show_rows across the CleanSlate
285 local ($self->{'first_row'}, $self->{'show_rows'});
290 return (1, $self->loc("No Query")) unless $query;
292 $self->{_sql_query} = $query;
293 eval { $self->_parser( $query ); };
295 $RT::Logger->error( $@ );
299 # We only want to look at EffectiveId's (mostly) for these searches.
300 unless ( exists $self->{_sql_looking_at}{'effectiveid'} ) {
301 #TODO, we shouldn't be hard #coding the tablename to main.
302 $self->SUPER::Limit( FIELD => 'EffectiveId',
304 ENTRYAGGREGATOR => 'AND',
308 # FIXME: Need to bring this logic back in
310 # if ($self->_isLimited && (! $self->{'looking_at_effective_id'})) {
311 # $self->SUPER::Limit( FIELD => 'EffectiveId',
314 # VALUE => 'main.id'); #TODO, we shouldn't be hard coding the tablename to main.
316 # --- This is hardcoded above. This comment block can probably go.
317 # Or, we need to reimplement the looking_at_effective_id toggle.
319 # Unless we've explicitly asked to look at a specific Type, we need
321 unless ( $self->{looking_at_type} ) {
322 $self->SUPER::Limit( FIELD => 'Type', VALUE => 'ticket' );
325 # We don't want deleted tickets unless 'allow_deleted_search' is set
326 unless( $self->{'allow_deleted_search'} ) {
327 $self->SUPER::Limit( FIELD => 'Status',
333 # set SB's dirty flag
334 $self->{'must_redo_search'} = 1;
335 $self->{'RecalcTicketLimits'} = 0;
337 return (1, $self->loc("Valid Query"));
342 Returns the query that this object was initialized with
347 return ($_[0]->{_sql_query});
352 '=' => '!=', '!=' => '=', '<>' => '=',
353 '>' => '<=', '<' => '>=', '>=' => '<', '<=' => '>',
354 'is' => 'IS NOT', 'is not' => 'IS',
355 'like' => 'NOT LIKE', 'not like' => 'LIKE',
356 'matches' => 'NOT MATCHES', 'not matches' => 'MATCHES',
357 'startswith' => 'NOT STARTSWITH', 'not startswith' => 'STARTSWITH',
358 'endswith' => 'NOT ENDSWITH', 'not endswith' => 'ENDSWITH',
361 my %range = map { $_ => 1 } qw(> >= < <=);
363 sub ClassifySQLOperation {
368 if ( $op eq '!=' || $op =~ /\bNOT\b/i ) {
373 if ( 'is not' eq lc($op) || 'is' eq lc($op) ) {
377 return ($is_negative, $is_null, $inv{lc $op}, $range{lc $op});
386 Most of the RT code does not use Exceptions (die/eval) but it is used
387 in the TicketSQL code for simplicity and historical reasons. Lest you
388 be worried that the dies will trigger user visible errors, all are
391 99% of the dies fall in subroutines called via FromSQL and then parse.
392 (This includes all of the _FooLimit routines in Tickets_Overlay.pm.)
393 The other 1% or so are via _ProcessRestrictions.
395 All dies are trapped by eval {}s, and will be logged at the 'error'
396 log level. The general failure mode is to not display any tickets.
402 Legacy LimitFoo routines build up a RestrictionsHash
404 _ProcessRestrictions converts the Restrictions to Clauses
407 Clauses are converted to RT-SQL (TicketSQL)
411 FromSQL calls the parser
413 The parser calls the _FooLimit routines to do DBIx::SearchBuilder
416 And then the normal SearchBuilder/Ticket routines are used for