# $Id: SQL.pm 564 2009-02-05 00:27:19Z athomason $ package Data::ObjectDriver::SQL; use strict; use warnings; use base qw( Class::Accessor::Fast ); __PACKAGE__->mk_accessors(qw( select distinct select_map select_map_reverse from joins where bind limit offset group order having where_values column_mutator index_hint comment )); sub new { my $class = shift; my $stmt = $class->SUPER::new(@_); $stmt->select([]); $stmt->distinct(0); $stmt->select_map({}); $stmt->select_map_reverse({}); $stmt->bind([]); $stmt->from([]); $stmt->where([]); $stmt->where_values({}); $stmt->having([]); $stmt->joins([]); $stmt->index_hint({}); $stmt; } sub add_select { my $stmt = shift; my($term, $col) = @_; $col ||= $term; push @{ $stmt->select }, $term; $stmt->select_map->{$term} = $col; $stmt->select_map_reverse->{$col} = $term; } sub add_join { my $stmt = shift; my($table, $joins) = @_; push @{ $stmt->joins }, { table => $table, joins => ref($joins) eq 'ARRAY' ? $joins : [ $joins ], }; } sub add_index_hint { my $stmt = shift; my($table, $hint) = @_; $stmt->index_hint->{$table} = { type => $hint->{type} || 'USE', list => ref($hint->{list}) eq 'ARRAY' ? $hint->{list} : [ $hint->{list} ], }; } sub as_sql { my $stmt = shift; my $sql = ''; if (@{ $stmt->select }) { $sql .= 'SELECT '; $sql .= 'DISTINCT ' if $stmt->distinct; $sql .= join(', ', map { my $alias = $stmt->select_map->{$_}; $alias && /(?:^|\.)\Q$alias\E$/ ? $_ : "$_ $alias"; } @{ $stmt->select }) . "\n"; } $sql .= 'FROM '; ## Add any explicit JOIN statements before the non-joined tables. my %joined; my @from = @{ $stmt->from || [] }; if ($stmt->joins && @{ $stmt->joins }) { my $initial_table_written = 0; for my $j (@{ $stmt->joins }) { my($table, $joins) = map { $j->{$_} } qw( table joins ); $table = $stmt->_add_index_hint($table); ## index hint handling $sql .= $table unless $initial_table_written++; $joined{$table}++; for my $join (@{ $j->{joins} }) { $sql .= ' ' . uc($join->{type}) . ' JOIN ' . $join->{table} . ' ON ' . $join->{condition}; } } @from = grep { ! $joined{ $_ } } @from; $sql .= ', ' if @from; } if (@from) { $sql .= join ', ', map { $stmt->_add_index_hint($_) } @from; } $sql .= "\n"; $sql .= $stmt->as_sql_where; $sql .= $stmt->as_aggregate('group'); $sql .= $stmt->as_sql_having; $sql .= $stmt->as_aggregate('order'); $sql .= $stmt->as_limit; my $comment = $stmt->comment; if ($comment && $comment =~ /([ 0-9a-zA-Z.:;()_#&,]+)/) { $sql .= "-- $1" if $1; } return $sql; } sub as_limit { my $stmt = shift; my $n = $stmt->limit or return ''; die "Non-numerics in limit clause ($n)" if $n =~ /\D/; return sprintf "LIMIT %d%s\n", $n, ($stmt->offset ? " OFFSET " . int($stmt->offset) : ""); } sub as_aggregate { my $stmt = shift; my($set) = @_; if (my $attribute = $stmt->$set()) { my $elements = (ref($attribute) eq 'ARRAY') ? $attribute : [ $attribute ]; return uc($set) . ' BY ' . join(', ', map { $_->{column} . ($_->{desc} ? (' ' . $_->{desc}) : '') } @$elements) . "\n"; } return ''; } sub as_sql_where { my $stmt = shift; $stmt->where && @{ $stmt->where } ? 'WHERE ' . join(' AND ', @{ $stmt->where }) . "\n" : ''; } sub as_sql_having { my $stmt = shift; $stmt->having && @{ $stmt->having } ? 'HAVING ' . join(' AND ', @{ $stmt->having }) . "\n" : ''; } sub add_where { my $stmt = shift; ## xxx Need to support old range and transform behaviors. my($col, $val) = @_; Carp::croak("Invalid/unsafe column name $col") unless $col =~ /^[\w\.]+$/; my($term, $bind, $tcol) = $stmt->_mk_term($col, $val); push @{ $stmt->{where} }, "($term)"; push @{ $stmt->{bind} }, @$bind; $stmt->where_values->{$tcol} = $val; } sub add_complex_where { my $stmt = shift; my ($terms) = @_; my ($where, $bind) = $stmt->_parse_array_terms($terms); push @{ $stmt->{where} }, $where; push @{ $stmt->{bind} }, @$bind; } sub _parse_array_terms { my $stmt = shift; my ($term_list) = @_; my @out; my $logic = 'AND'; my @bind; foreach my $t ( @$term_list ) { if (! ref $t ) { $logic = $1 if uc($t) =~ m/^-?(OR|AND|OR_NOT|AND_NOT)$/; $logic =~ s/_/ /; next; } my $out; if (ref $t eq 'HASH') { # bag of terms to apply $logic with my @out; foreach my $t2 ( keys %$t ) { my ($term, $bind, $col) = $stmt->_mk_term($t2, $t->{$t2}); $stmt->where_values->{$col} = $t->{$t2}; push @out, $term; push @bind, @$bind; } $out .= '(' . join(" AND ", @out) . ")"; } elsif (ref $t eq 'ARRAY') { # another array of terms to process! my ($where, $bind) = $stmt->_parse_array_terms( $t ); push @bind, @$bind; $out = '(' . $where . ')'; } push @out, (@out ? ' ' . $logic . ' ' : '') . $out; } return (join("", @out), \@bind); } sub has_where { my $stmt = shift; my($col, $val) = @_; # TODO: should check if the value is same with $val? exists $stmt->where_values->{$col}; } sub add_having { my $stmt = shift; my($col, $val) = @_; # Carp::croak("Invalid/unsafe column name $col") unless $col =~ /^[\w\.]+$/; if (my $orig = $stmt->select_map_reverse->{$col}) { $col = $orig; } my($term, $bind) = $stmt->_mk_term($col, $val); push @{ $stmt->{having} }, "($term)"; push @{ $stmt->{bind} }, @$bind; } sub _mk_term { my $stmt = shift; my($col, $val) = @_; my $term = ''; my (@bind, $m); if (ref($val) eq 'ARRAY') { if (ref $val->[0] or (($val->[0] || '') eq '-and')) { my $logic = 'OR'; my @values = @$val; if ($val->[0] eq '-and') { $logic = 'AND'; shift @values; } my @terms; for my $v (@values) { my($term, $bind) = $stmt->_mk_term($col, $v); push @terms, "($term)"; push @bind, @$bind; } $term = join " $logic ", @terms; } else { $col = $m->($col) if $m = $stmt->column_mutator; $term = "$col IN (".join(',', ('?') x scalar @$val).')'; @bind = @$val; } } elsif (ref($val) eq 'HASH') { my $c = $val->{column} || $col; $c = $m->($c) if $m = $stmt->column_mutator; $term = "$c $val->{op} ?"; push @bind, $val->{value}; } elsif (ref($val) eq 'SCALAR') { $col = $m->($col) if $m = $stmt->column_mutator; $term = "$col $$val"; } else { $col = $m->($col) if $m = $stmt->column_mutator; $term = "$col = ?"; push @bind, $val; } ($term, \@bind, $col); } sub _add_index_hint { my $stmt = shift; my ($tbl_name) = @_; my $hint = $stmt->index_hint->{$tbl_name}; return $tbl_name unless $hint && ref($hint) eq 'HASH'; if ($hint->{list} && @{ $hint->{list} }) { return $tbl_name . ' ' . uc($hint->{type} || 'USE') . ' INDEX (' . join (',', @{ $hint->{list} }) . ')'; } return $tbl_name; } 1; __END__ =head1 NAME Data::ObjectDriver::SQL - an SQL statement =head1 SYNOPSIS my $sql = Data::ObjectDriver::SQL->new(); $sql->select([ 'id', 'name', 'bucket_id', 'note_id' ]); $sql->from([ 'foo' ]); $sql->add_where('name', 'fred'); $sql->add_where('bucket_id', { op => '!=', value => 47 }); $sql->add_where('note_id', \'IS NULL'); $sql->limit(1); my $sth = $dbh->prepare($sql->as_sql); $sth->execute(@{ $sql->{bind} }); my @values = $sth->selectrow_array(); my $obj = SomeObject->new(); $obj->set_columns(...); =head1 DESCRIPTION I represents an SQL statement. SQL statements are used internally to C object drivers to convert database operations (C, C, etc) into database operations, but sometimes you just gotta use SQL. =head1 ATTRIBUTES I sports several data attributes that represent the parts of the modeled SQL statement. These attributes all have accessor and mutator methods. Note that some attributes have more convenient methods of modification (for example, C for the C attribute). =head2 C query. =head2 C (boolean) Whether the C query. Use this mapping to convert members of the C query. Use this map to reverse the C mapping where needed. =head2 C (arrayref) The list of tables from which to query results in a C query with multiple tables, the rows will be selected as Cartesian products that you'll need to reduce with C clauses. Your query might be better served with real joins specified through the C attribute of your statement. =head2 C (arrayref of hashrefs containing scalars and hashrefs) The list of C clauses to use in the table list of the statement. Each clause is a hashref containing these members: =over 4 =item * C The name of the table in C being joined. =item * C (arrayref) The list of joins to perform on the table named in C
. Each member of C is a hashref containing: =over 4 =item * C The type of join to use. That is, the SQL string to use before the word C in the join expression; for example, C or C). This member is optional. When not specified, the default plain C join is specified. =item * C
The name of the table to which to join. =item * C The SQL expression across which to perform the join, as a string. =back =back =head2 C (arrayref) The list of C clauses that apply to the SQL statement. Individual members of the list are strings of SQL. All members of this attribute must be true for a record to be included as a result; that is, the list members are Ced together to form the full C clause. =head2 C (hashref of variant structures) The set of data structures used to generate the C clause SQL found in the C attributes, keyed on the associated column names. =head2 C (arrayref) The list of values to bind to the query when performed. That is, the list of values to be replaced for the Ces in the SQL. =head2 C (scalar) The maximum number of results on which to perform the query. =head2 C (scalar) The number of records to skip before performing the query. Combined with a C and application logic to increase the offset in subsequent queries, you can paginate a set of records with a moving window containing C records. =head2 C (hashref, or an arrayref of hashrefs) The fields on which to group the results. Grouping fields are hashrefs containing these members: =over 4 =item * C Name of the column on which to group. =back Note you can set a single grouping field, or use an arrayref containing multiple grouping fields. =head2 C (arrayref) The list of clauses to specify in the C portion of a C clause. Individual clauses are simple strings containing the conditional expression, as in C. =head2 C (hashref, or an arrayref of hashrefs) Returns or sets the fields by which to order the results. Ordering fields are hashrefs containing these members: =over 4 =item * C Name of the column by which to order. =item * C The SQL keyword to use to specify the ordering. For example, use C to specify a descending order. This member is optional. =back Note you can set a single ordering field, or use an arrayref containing multiple ordering fields. =head2 C<$sql-Ecomment([ $comment ])> Returns or sets a simple comment to the SQL statement =head1 USAGE =head2 Cnew()> Creates a new, empty SQL statement. =head2 C<$sql-Eadd_select($column [, $term ])> Adds the database column C<$column> to the list of fields to return in a C query. The structure for the set of C<\@hints> are arrayref of hashrefs containing these members: =over 4 =item * C (scalar) The name of the type. "USE", "IGNORE or "FORCE". =item * C (arrayref) The list of name of indexes which to use. =back =head2 C<$sql-Eas_sql()> Returns the SQL fully representing the SQL statement C<$sql>. =head2 C<$sql-Eas_sql_having()> Returns the SQL representing the C portion of C<$sql>'s C clause. =head2 C<$sql-Eas_sql_where()> Returns the SQL representing C<$sql>'s C clause. =head2 C<$sql-Eas_limit()> Returns the SQL for the C clause of the statement. =head2 C<$sql-Eas_aggregate($set)> Returns the SQL representing the aggregation clause of type C<$set> for the SQL statement C<$sql>. Reasonable values of C<$set> are C and C. =head1 DIAGNOSTICS =over 4 =item * C> The column name you specified to C contained characters that are not allowed in database column names. Only word characters and periods are allowed. Perhaps you didn't filter punctuation out of a generated column name correctly. =back =head1 BUGS AND LIMITATIONS I does not provide the functionality for turning SQL statements into instances of object classes. =head1 SEE ALSO =head1 LICENSE I is free software; you may redistribute it and/or modify it under the same terms as Perl itself. =head1 AUTHOR & COPYRIGHT Except where otherwise noted, I is Copyright 2005-2006 Six Apart, cpan@sixapart.com. All rights reserved. =cut