SQL-Abstract-1.85/0000755000000000000000000000000013233057465013655 5ustar00rootroot00000000000000SQL-Abstract-1.85/Makefile.PL0000644000000000000000000000661113074150107015621 0ustar00rootroot00000000000000use strict; use warnings FATAL => 'all'; use 5.006; my %META = ( name => 'SQL-Abstract', license => 'perl_5', dynamic_config => 0, prereqs => { configure => { requires => { 'ExtUtils::MakeMaker' => 0, } }, build => { requires => {} }, test => { requires => { "Test::More" => '0.88', "Test::Exception" => '0.31', "Test::Warn" => '0', "Test::Deep" => '0.101', "Storable" => '0', # for cloning in tests }, }, runtime => { requires => { 'List::Util' => '0', 'Scalar::Util' => '0', 'Exporter' => '5.57', 'MRO::Compat' => '0.12', 'Moo' => '2.000001', 'Sub::Quote' => '2.000001', 'Hash::Merge' => '0.12', 'Text::Balanced' => '2.00', 'perl' => '5.006', }, }, develop => { requires => { 'Test::Pod' => '1.14', 'Test::Pod::Coverage' => '1.04', 'Pod::Coverage' => '0.19', 'Test::EOL' => '1.0', 'Test::NoTabs' => '0.9', }, }, }, resources => { repository => { url => 'https://github.com/dbsrgits/sql-abstract.git', web => 'https://github.com/dbsrgits/sql-abstract', type => 'git', }, x_IRC => 'irc://irc.perl.org/#dbix-class', bugtracker => { web => 'https://rt.cpan.org/Public/Dist/Display.html?Name=SQL-Abstract', mailto => 'bug-SQL-Abstract@rt.cpan.org', }, license => [ 'http://dev.perl.org/licenses/' ], }, no_index => { package => [ 'DBIx::Class::Storage::Debug::PrettyPrint' ], directory => [ 't', 'xt', 'examples' ], }, ); my %MM_ARGS = ( test => { TESTS => 't/*.t t/*/*.t' }, ); ## BOILERPLATE ############################################################### require ExtUtils::MakeMaker; (do './maint/Makefile.PL.include' or die $@) unless -f 'META.yml'; # have to do this since old EUMM dev releases miss the eval $VERSION line my $eumm_version = eval $ExtUtils::MakeMaker::VERSION; my $mymeta = $eumm_version >= 6.57_02; my $mymeta_broken = $mymeta && $eumm_version < 6.57_07; ($MM_ARGS{NAME} = $META{name}) =~ s/-/::/g; ($MM_ARGS{VERSION_FROM} = "lib/$MM_ARGS{NAME}.pm") =~ s{::}{/}g; $META{license} = [ $META{license} ] if $META{license} && !ref $META{license}; $MM_ARGS{LICENSE} = $META{license}[0] if $META{license} && $eumm_version >= 6.30; $MM_ARGS{NO_MYMETA} = 1 if $mymeta_broken; $MM_ARGS{META_ADD} = { 'meta-spec' => { version => 2 }, %META } unless -f 'META.yml'; for (qw(configure build test runtime)) { my $key = $_ eq 'runtime' ? 'PREREQ_PM' : uc $_.'_REQUIRES'; my $r = $MM_ARGS{$key} = { %{$META{prereqs}{$_}{requires} || {}}, %{delete $MM_ARGS{$key} || {}}, }; defined $r->{$_} or delete $r->{$_} for keys %$r; } $MM_ARGS{MIN_PERL_VERSION} = delete $MM_ARGS{PREREQ_PM}{perl} || 0; delete $MM_ARGS{MIN_PERL_VERSION} if $eumm_version < 6.47_01; $MM_ARGS{BUILD_REQUIRES} = {%{$MM_ARGS{BUILD_REQUIRES}}, %{delete $MM_ARGS{TEST_REQUIRES}}} if $eumm_version < 6.63_03; $MM_ARGS{PREREQ_PM} = {%{$MM_ARGS{PREREQ_PM}}, %{delete $MM_ARGS{BUILD_REQUIRES}}} if $eumm_version < 6.55_01; delete $MM_ARGS{CONFIGURE_REQUIRES} if $eumm_version < 6.51_03; ExtUtils::MakeMaker::WriteMakefile(%MM_ARGS); ## END BOILERPLATE ########################################################### SQL-Abstract-1.85/MANIFEST0000644000000000000000000000171113233057465015006 0ustar00rootroot00000000000000Changes examples/console.pl examples/dbic-console.pl examples/sqla-format lib/DBIx/Class/Storage/Debug/PrettyPrint.pm lib/SQL/Abstract.pm lib/SQL/Abstract/Test.pm lib/SQL/Abstract/Tree.pm maint/Makefile.PL.include Makefile.PL MANIFEST This list of files t/00new.t t/01generate.t t/02where.t t/03values.t t/04modifiers.t t/05in_between.t t/06order_by.t t/07subqueries.t t/08special_ops.t t/09refkind.t t/10test.t t/11parser.t t/12confmerge.t t/12format_keyword.t t/13whitespace_keyword.t t/14roundtrippin.t t/15placeholders.t t/16no_sideeffects.t t/20injection_guard.t t/21op_ident.t t/22op_value.t t/23_is_X_value.t t/dbic/bulk-insert.t t/dbic/no-repeats.t t/dbic/show-progress.t xt/90pod.t xt/91podcoverage.t xt/92whitespace.t META.yml Module YAML meta-data (added by MakeMaker) META.json Module JSON meta-data (added by MakeMaker) README README file (added by Distar) SQL-Abstract-1.85/README0000664000000000000000000015057413233057465014553 0ustar00rootroot00000000000000NAME SQL::Abstract - Generate SQL from Perl data structures SYNOPSIS use SQL::Abstract; my $sql = SQL::Abstract->new; my($stmt, @bind) = $sql->select($source, \@fields, \%where, $order); my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values); my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where); my($stmt, @bind) = $sql->delete($table, \%where); # Then, use these in your DBI statements my $sth = $dbh->prepare($stmt); $sth->execute(@bind); # Just generate the WHERE clause my($stmt, @bind) = $sql->where(\%where, $order); # Return values in the same order, for hashed queries # See PERFORMANCE section for more details my @bind = $sql->values(\%fieldvals); DESCRIPTION This module was inspired by the excellent DBIx::Abstract. However, in using that module I found that what I really wanted to do was generate SQL, but still retain complete control over my statement handles and use the DBI interface. So, I set out to create an abstract SQL generation module. While based on the concepts used by DBIx::Abstract, there are several important differences, especially when it comes to WHERE clauses. I have modified the concepts used to make the SQL easier to generate from Perl data structures and, IMO, more intuitive. The underlying idea is for this module to do what you mean, based on the data structures you provide it. The big advantage is that you don't have to modify your code every time your data changes, as this module figures it out. To begin with, an SQL INSERT is as easy as just specifying a hash of "key=value" pairs: my %data = ( name => 'Jimbo Bobson', phone => '123-456-7890', address => '42 Sister Lane', city => 'St. Louis', state => 'Louisiana', ); The SQL can then be generated with this: my($stmt, @bind) = $sql->insert('people', \%data); Which would give you something like this: $stmt = "INSERT INTO people (address, city, name, phone, state) VALUES (?, ?, ?, ?, ?)"; @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson', '123-456-7890', 'Louisiana'); These are then used directly in your DBI code: my $sth = $dbh->prepare($stmt); $sth->execute(@bind); Inserting and Updating Arrays If your database has array types (like for example Postgres), activate the special option "array_datatypes => 1" when creating the "SQL::Abstract" object. Then you may use an arrayref to insert and update database array types: my $sql = SQL::Abstract->new(array_datatypes => 1); my %data = ( planets => [qw/Mercury Venus Earth Mars/] ); my($stmt, @bind) = $sql->insert('solar_system', \%data); This results in: $stmt = "INSERT INTO solar_system (planets) VALUES (?)" @bind = (['Mercury', 'Venus', 'Earth', 'Mars']); Inserting and Updating SQL In order to apply SQL functions to elements of your %data you may specify a reference to an arrayref for the given hash value. For example, if you need to execute the Oracle "to_date" function on a value, you can say something like this: my %data = ( name => 'Bill', date_entered => \[ "to_date(?,'MM/DD/YYYY')", "03/02/2003" ], ); The first value in the array is the actual SQL. Any other values are optional and would be included in the bind values array. This gives you: my($stmt, @bind) = $sql->insert('people', \%data); $stmt = "INSERT INTO people (name, date_entered) VALUES (?, to_date(?,'MM/DD/YYYY'))"; @bind = ('Bill', '03/02/2003'); An UPDATE is just as easy, all you change is the name of the function: my($stmt, @bind) = $sql->update('people', \%data); Notice that your %data isn't touched; the module will generate the appropriately quirky SQL for you automatically. Usually you'll want to specify a WHERE clause for your UPDATE, though, which is where handling %where hashes comes in handy... Complex where statements This module can generate pretty complicated WHERE statements easily. For example, simple "key=value" pairs are taken to mean equality, and if you want to see if a field is within a set of values, you can use an arrayref. Let's say we wanted to SELECT some data based on this criteria: my %where = ( requestor => 'inna', worker => ['nwiger', 'rcwe', 'sfz'], status => { '!=', 'completed' } ); my($stmt, @bind) = $sql->select('tickets', '*', \%where); The above would give you something like this: $stmt = "SELECT * FROM tickets WHERE ( requestor = ? ) AND ( status != ? ) AND ( worker = ? OR worker = ? OR worker = ? )"; @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz'); Which you could then use in DBI code like so: my $sth = $dbh->prepare($stmt); $sth->execute(@bind); Easy, eh? METHODS The methods are simple. There's one for every major SQL operation, and a constructor you use first. The arguments are specified in a similar order for each method (table, then fields, then a where clause) to try and simplify things. new(option => 'value') The "new()" function takes a list of options and values, and returns a new SQL::Abstract object which can then be used to generate SQL through the methods below. The options accepted are: case If set to 'lower', then SQL will be generated in all lowercase. By default SQL is generated in "textbook" case meaning something like: SELECT a_field FROM a_table WHERE some_field LIKE '%someval%' Any setting other than 'lower' is ignored. cmp This determines what the default comparison operator is. By default it is "=", meaning that a hash like this: %where = (name => 'nwiger', email => 'nate@wiger.org'); Will generate SQL like this: WHERE name = 'nwiger' AND email = 'nate@wiger.org' However, you may want loose comparisons by default, so if you set "cmp" to "like" you would get SQL such as: WHERE name like 'nwiger' AND email like 'nate@wiger.org' You can also override the comparison on an individual basis - see the huge section on "WHERE CLAUSES" at the bottom. sqltrue, sqlfalse Expressions for inserting boolean values within SQL statements. By default these are "1=1" and "1=0". They are used by the special operators "-in" and "-not_in" for generating correct SQL even when the argument is an empty array (see below). logic This determines the default logical operator for multiple WHERE statements in arrays or hashes. If absent, the default logic is "or" for arrays, and "and" for hashes. This means that a WHERE array of the form: @where = ( event_date => {'>=', '2/13/99'}, event_date => {'<=', '4/24/03'}, ); will generate SQL like this: WHERE event_date >= '2/13/99' OR event_date <= '4/24/03' This is probably not what you want given this query, though (look at the dates). To change the "OR" to an "AND", simply specify: my $sql = SQL::Abstract->new(logic => 'and'); Which will change the above "WHERE" to: WHERE event_date >= '2/13/99' AND event_date <= '4/24/03' The logic can also be changed locally by inserting a modifier in front of an arrayref : @where = (-and => [event_date => {'>=', '2/13/99'}, event_date => {'<=', '4/24/03'} ]); See the "WHERE CLAUSES" section for explanations. convert This will automatically convert comparisons using the specified SQL function for both column and value. This is mostly used with an argument of "upper" or "lower", so that the SQL will have the effect of case-insensitive "searches". For example, this: $sql = SQL::Abstract->new(convert => 'upper'); %where = (keywords => 'MaKe iT CAse inSeNSItive'); Will turn out the following SQL: WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive') The conversion can be "upper()", "lower()", or any other SQL function that can be applied symmetrically to fields (actually SQL::Abstract does not validate this option; it will just pass through what you specify verbatim). bindtype This is a kludge because many databases suck. For example, you can't just bind values using DBI's "execute()" for Oracle "CLOB" or "BLOB" fields. Instead, you have to use "bind_param()": $sth->bind_param(1, 'reg data'); $sth->bind_param(2, $lots, {ora_type => ORA_CLOB}); The problem is, SQL::Abstract will normally just return a @bind array, which loses track of which field each slot refers to. Fear not. If you specify "bindtype" in new, you can determine how @bind is returned. Currently, you can specify either "normal" (default) or "columns". If you specify "columns", you will get an array that looks like this: my $sql = SQL::Abstract->new(bindtype => 'columns'); my($stmt, @bind) = $sql->insert(...); @bind = ( [ 'column1', 'value1' ], [ 'column2', 'value2' ], [ 'column3', 'value3' ], ); You can then iterate through this manually, using DBI's "bind_param()". $sth->prepare($stmt); my $i = 1; for (@bind) { my($col, $data) = @$_; if ($col eq 'details' || $col eq 'comments') { $sth->bind_param($i, $data, {ora_type => ORA_CLOB}); } elsif ($col eq 'image') { $sth->bind_param($i, $data, {ora_type => ORA_BLOB}); } else { $sth->bind_param($i, $data); } $i++; } $sth->execute; # execute without @bind now Now, why would you still use SQL::Abstract if you have to do this crap? Basically, the advantage is still that you don't have to care which fields are or are not included. You could wrap that above "for" loop in a simple sub called "bind_fields()" or something and reuse it repeatedly. You still get a layer of abstraction over manual SQL specification. Note that if you set "bindtype" to "columns", the "\[ $sql, @bind ]" construct (see "Literal SQL with placeholders and bind values (subqueries)") will expect the bind values in this format. quote_char This is the character that a table or column name will be quoted with. By default this is an empty string, but you could set it to the character "`", to generate SQL like this: SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%' Alternatively, you can supply an array ref of two items, the first being the left hand quote character, and the second the right hand quote character. For example, you could supply "['[',']']" for SQL Server 2000 compliant quotes that generates SQL like this: SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%' Quoting is useful if you have tables or columns names that are reserved words in your database's SQL dialect. escape_char This is the character that will be used to escape "quote_char"s appearing in an identifier before it has been quoted. The parameter default in case of a single "quote_char" character is the quote character itself. When opening-closing-style quoting is used ("quote_char" is an arrayref) this parameter defaults to the closing (right) "quote_char". Occurrences of the opening (left) "quote_char" within the identifier are currently left untouched. The default for opening-closing-style quotes may change in future versions, thus you are strongly encouraged to specify the escape character explicitly. name_sep This is the character that separates a table and column name. It is necessary to specify this when the "quote_char" option is selected, so that tables and column names can be individually quoted like this: SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1 injection_guard A regular expression "qr/.../" that is applied to any "-function" and unquoted column name specified in a query structure. This is a safety mechanism to avoid injection attacks when mishandling user input e.g.: my %condition_as_column_value_pairs = get_values_from_user(); $sqla->select( ... , \%condition_as_column_value_pairs ); If the expression matches an exception is thrown. Note that literal SQL supplied via "\'...'" or "\['...']" is not checked in any way. Defaults to checking for ";" and the "GO" keyword (TransactSQL) array_datatypes When this option is true, arrayrefs in INSERT or UPDATE are interpreted as array datatypes and are passed directly to the DBI layer. When this option is false, arrayrefs are interpreted as literal SQL, just like refs to arrayrefs (but this behavior is for backwards compatibility; when writing new queries, use the "reference to arrayref" syntax for literal SQL). special_ops Takes a reference to a list of "special operators" to extend the syntax understood by SQL::Abstract. See section "SPECIAL OPERATORS" for details. unary_ops Takes a reference to a list of "unary operators" to extend the syntax understood by SQL::Abstract. See section "UNARY OPERATORS" for details. insert($table, \@values || \%fieldvals, \%options) This is the simplest function. You simply give it a table name and either an arrayref of values or hashref of field/value pairs. It returns an SQL INSERT statement and a list of bind values. See the sections on "Inserting and Updating Arrays" and "Inserting and Updating SQL" for information on how to insert with those data types. The optional "\%options" hash reference may contain additional options to generate the insert SQL. Currently supported options are: returning Takes either a scalar of raw SQL fields, or an array reference of field names, and adds on an SQL "RETURNING" statement at the end. This allows you to return data generated by the insert statement (such as row IDs) without performing another "SELECT" statement. Note, however, this is not part of the SQL standard and may not be supported by all database engines. update($table, \%fieldvals, \%where, \%options) This takes a table, hashref of field/value pairs, and an optional hashref WHERE clause. It returns an SQL UPDATE function and a list of bind values. See the sections on "Inserting and Updating Arrays" and "Inserting and Updating SQL" for information on how to insert with those data types. The optional "\%options" hash reference may contain additional options to generate the update SQL. Currently supported options are: returning See the "returning" option to insert. select($source, $fields, $where, $order) This returns a SQL SELECT statement and associated list of bind values, as specified by the arguments : $source Specification of the 'FROM' part of the statement. The argument can be either a plain scalar (interpreted as a table name, will be quoted), or an arrayref (interpreted as a list of table names, joined by commas, quoted), or a scalarref (literal table name, not quoted), or a ref to an arrayref (list of literal table names, joined by commas, not quoted). $fields Specification of the list of fields to retrieve from the source. The argument can be either an arrayref (interpreted as a list of field names, will be joined by commas and quoted), or a plain scalar (literal SQL, not quoted). Please observe that this API is not as flexible as that of the first argument $source, for backwards compatibility reasons. $where Optional argument to specify the WHERE part of the query. The argument is most often a hashref, but can also be an arrayref or plain scalar -- see section WHERE clause for details. $order Optional argument to specify the ORDER BY part of the query. The argument can be a scalar, a hashref or an arrayref -- see section ORDER BY clause for details. delete($table, \%where, \%options) This takes a table name and optional hashref WHERE clause. It returns an SQL DELETE statement and list of bind values. The optional "\%options" hash reference may contain additional options to generate the delete SQL. Currently supported options are: returning See the "returning" option to insert. where(\%where, $order) This is used to generate just the WHERE clause. For example, if you have an arbitrary data structure and know what the rest of your SQL is going to look like, but want an easy way to produce a WHERE clause, use this. It returns an SQL WHERE clause and list of bind values. values(\%data) This just returns the values from the hash %data, in the same order that would be returned from any of the other above queries. Using this allows you to markedly speed up your queries if you are affecting lots of rows. See below under the "PERFORMANCE" section. generate($any, 'number', $of, \@data, $struct, \%types) Warning: This is an experimental method and subject to change. This returns arbitrarily generated SQL. It's a really basic shortcut. It will return two different things, depending on return context: my($stmt, @bind) = $sql->generate('create table', \$table, \@fields); my $stmt_and_val = $sql->generate('create table', \$table, \@fields); These would return the following: # First calling form $stmt = "CREATE TABLE test (?, ?)"; @bind = (field1, field2); # Second calling form $stmt_and_val = "CREATE TABLE test (field1, field2)"; Depending on what you're trying to do, it's up to you to choose the correct format. In this example, the second form is what you would want. By the same token: $sql->generate('alter session', { nls_date_format => 'MM/YY' }); Might give you: ALTER SESSION SET nls_date_format = 'MM/YY' You get the idea. Strings get their case twiddled, but everything else remains verbatim. EXPORTABLE FUNCTIONS is_plain_value Determines if the supplied argument is a plain value as understood by this module: * The value is "undef" * The value is a non-reference * The value is an object with stringification overloading * The value is of the form "{ -value => $anything }" On failure returns "undef", on success returns a scalar reference to the original supplied argument. * Note The stringification overloading detection is rather advanced: it takes into consideration not only the presence of a "" overload, but if that fails also checks for enabled autogenerated versions of "", based on either "0+" or "bool". Unfortunately testing in the field indicates that this detection may tickle a latent bug in perl versions before 5.018, but only when very large numbers of stringifying objects are involved. At the time of writing ( Sep 2014 ) there is no clear explanation of the direct cause, nor is there a manageably small test case that reliably reproduces the problem. If you encounter any of the following exceptions in random places within your application stack - this module may be to blame: Operation "ne": no method found, left argument in overloaded package , right argument in overloaded package or perhaps even Stub found while resolving method "???" overloading """" in package If you fall victim to the above - please attempt to reduce the problem to something that could be sent to the SQL::Abstract developers (either publicly or privately). As a workaround in the meantime you can set $ENV{SQLA_ISVALUE_IGNORE_AUTOGENERATED_STRINGIFICATION} to a true value, which will most likely eliminate your problem (at the expense of not being able to properly detect exotic forms of stringification). This notice and environment variable will be removed in a future version, as soon as the underlying problem is found and a reliable workaround is devised. is_literal_value Determines if the supplied argument is a literal value as understood by this module: * "\$sql_string" * "\[ $sql_string, @bind_values ]" On failure returns "undef", on success returns an array reference containing the unpacked version of the supplied literal SQL and bind values. WHERE CLAUSES Introduction This module uses a variation on the idea from DBIx::Abstract. It is NOT, repeat *not* 100% compatible. The main logic of this module is that things in arrays are OR'ed, and things in hashes are AND'ed. The easiest way to explain is to show lots of examples. After each %where hash shown, it is assumed you used: my($stmt, @bind) = $sql->where(\%where); However, note that the %where hash can be used directly in any of the other functions as well, as described above. Key-value pairs So, let's get started. To begin, a simple hash: my %where = ( user => 'nwiger', status => 'completed' ); Is converted to SQL "key = val" statements: $stmt = "WHERE user = ? AND status = ?"; @bind = ('nwiger', 'completed'); One common thing I end up doing is having a list of values that a field can be in. To do this, simply specify a list inside of an arrayref: my %where = ( user => 'nwiger', status => ['assigned', 'in-progress', 'pending']; ); This simple code will create the following: $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )"; @bind = ('nwiger', 'assigned', 'in-progress', 'pending'); A field associated to an empty arrayref will be considered a logical false and will generate 0=1. Tests for NULL values If the value part is "undef" then this is converted to SQL my %where = ( user => 'nwiger', status => undef, ); becomes: $stmt = "WHERE user = ? AND status IS NULL"; @bind = ('nwiger'); To test if a column IS NOT NULL: my %where = ( user => 'nwiger', status => { '!=', undef }, ); Specific comparison operators If you want to specify a different type of operator for your comparison, you can use a hashref for a given column: my %where = ( user => 'nwiger', status => { '!=', 'completed' } ); Which would generate: $stmt = "WHERE user = ? AND status != ?"; @bind = ('nwiger', 'completed'); To test against multiple values, just enclose the values in an arrayref: status => { '=', ['assigned', 'in-progress', 'pending'] }; Which would give you: "WHERE status = ? OR status = ? OR status = ?" The hashref can also contain multiple pairs, in which case it is expanded into an "AND" of its elements: my %where = ( user => 'nwiger', status => { '!=', 'completed', -not_like => 'pending%' } ); # Or more dynamically, like from a form $where{user} = 'nwiger'; $where{status}{'!='} = 'completed'; $where{status}{'-not_like'} = 'pending%'; # Both generate this $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?"; @bind = ('nwiger', 'completed', 'pending%'); To get an OR instead, you can combine it with the arrayref idea: my %where => ( user => 'nwiger', priority => [ { '=', 2 }, { '>', 5 } ] ); Which would generate: $stmt = "WHERE ( priority = ? OR priority > ? ) AND user = ?"; @bind = ('2', '5', 'nwiger'); If you want to include literal SQL (with or without bind values), just use a scalar reference or reference to an arrayref as the value: my %where = ( date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] }, date_expires => { '<' => \"now()" } ); Which would generate: $stmt = "WHERE date_entered > to_date(?, 'MM/DD/YYYY') AND date_expires < now()"; @bind = ('11/26/2008'); Logic and nesting operators In the example above, there is a subtle trap if you want to say something like this (notice the "AND"): WHERE priority != ? AND priority != ? Because, in Perl you *can't* do this: priority => { '!=' => 2, '!=' => 1 } As the second "!=" key will obliterate the first. The solution is to use the special "-modifier" form inside an arrayref: priority => [ -and => {'!=', 2}, {'!=', 1} ] Normally, these would be joined by "OR", but the modifier tells it to use "AND" instead. (Hint: You can use this in conjunction with the "logic" option to "new()" in order to change the way your queries work by default.) Important: Note that the "-modifier" goes INSIDE the arrayref, as an extra first element. This will NOT do what you think it might: priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG! Here is a quick list of equivalencies, since there is some overlap: # Same status => {'!=', 'completed', 'not like', 'pending%' } status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}] # Same status => {'=', ['assigned', 'in-progress']} status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}] status => [ {'=', 'assigned'}, {'=', 'in-progress'} ] Special operators : IN, BETWEEN, etc. You can also use the hashref format to compare a list of fields using the "IN" comparison operator, by specifying the list as an arrayref: my %where = ( status => 'completed', reportid => { -in => [567, 2335, 2] } ); Which would generate: $stmt = "WHERE status = ? AND reportid IN (?,?,?)"; @bind = ('completed', '567', '2335', '2'); The reverse operator "-not_in" generates SQL "NOT IN" and is used in the same way. If the argument to "-in" is an empty array, 'sqlfalse' is generated (by default : "1=0"). Similarly, "-not_in => []" generates 'sqltrue' (by default : "1=1"). In addition to the array you can supply a chunk of literal sql or literal sql with bind: my %where = { customer => { -in => \[ 'SELECT cust_id FROM cust WHERE balance > ?', 2000, ], status => { -in => \'SELECT status_codes FROM states' }, }; would generate: $stmt = "WHERE ( customer IN ( SELECT cust_id FROM cust WHERE balance > ? ) AND status IN ( SELECT status_codes FROM states ) )"; @bind = ('2000'); Finally, if the argument to "-in" is not a reference, it will be treated as a single-element array. Another pair of operators is "-between" and "-not_between", used with an arrayref of two values: my %where = ( user => 'nwiger', completion_date => { -not_between => ['2002-10-01', '2003-02-06'] } ); Would give you: WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? ) Just like with "-in" all plausible combinations of literal SQL are possible: my %where = { start0 => { -between => [ 1, 2 ] }, start1 => { -between => \["? AND ?", 1, 2] }, start2 => { -between => \"lower(x) AND upper(y)" }, start3 => { -between => [ \"lower(x)", \["upper(?)", 'stuff' ], ] }, }; Would give you: $stmt = "WHERE ( ( start0 BETWEEN ? AND ? ) AND ( start1 BETWEEN ? AND ? ) AND ( start2 BETWEEN lower(x) AND upper(y) ) AND ( start3 BETWEEN lower(x) AND upper(?) ) )"; @bind = (1, 2, 1, 2, 'stuff'); These are the two builtin "special operators"; but the list can be expanded : see section "SPECIAL OPERATORS" below. Unary operators: bool If you wish to test against boolean columns or functions within your database you can use the "-bool" and "-not_bool" operators. For example to test the column "is_user" being true and the column "is_enabled" being false you would use:- my %where = ( -bool => 'is_user', -not_bool => 'is_enabled', ); Would give you: WHERE is_user AND NOT is_enabled If a more complex combination is required, testing more conditions, then you should use the and/or operators:- my %where = ( -and => [ -bool => 'one', -not_bool => { two=> { -rlike => 'bar' } }, -not_bool => { three => [ { '=', 2 }, { '>', 5 } ] }, ], ); Would give you: WHERE one AND (NOT two RLIKE ?) AND (NOT ( three = ? OR three > ? )) Nested conditions, -and/-or prefixes So far, we've seen how multiple conditions are joined with a top-level "AND". We can change this by putting the different conditions we want in hashes and then putting those hashes in an array. For example: my @where = ( { user => 'nwiger', status => { -like => ['pending%', 'dispatched'] }, }, { user => 'robot', status => 'unassigned', } ); This data structure would create the following: $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) ) OR ( user = ? AND status = ? ) )"; @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned'); Clauses in hashrefs or arrayrefs can be prefixed with an "-and" or "-or" to change the logic inside : my @where = ( -and => [ user => 'nwiger', [ -and => [ workhrs => {'>', 20}, geo => 'ASIA' ], -or => { workhrs => {'<', 50}, geo => 'EURO' }, ], ], ); That would yield: $stmt = "WHERE ( user = ? AND ( ( workhrs > ? AND geo = ? ) OR ( workhrs < ? OR geo = ? ) ) )"; @bind = ('nwiger', '20', 'ASIA', '50', 'EURO'); Algebraic inconsistency, for historical reasons "Important note": when connecting several conditions, the "-and-"|"-or" operator goes "outside" of the nested structure; whereas when connecting several constraints on one column, the "-and" operator goes "inside" the arrayref. Here is an example combining both features : my @where = ( -and => [a => 1, b => 2], -or => [c => 3, d => 4], e => [-and => {-like => 'foo%'}, {-like => '%bar'} ] ) yielding WHERE ( ( ( a = ? AND b = ? ) OR ( c = ? OR d = ? ) OR ( e LIKE ? AND e LIKE ? ) ) ) This difference in syntax is unfortunate but must be preserved for historical reasons. So be careful : the two examples below would seem algebraically equivalent, but they are not { col => [ -and => { -like => 'foo%' }, { -like => '%bar' }, ] } # yields : WHERE ( ( col LIKE ? AND col LIKE ? ) ) [ -and => { col => { -like => 'foo%' } }, { col => { -like => '%bar' } }, ] # yields : WHERE ( ( col LIKE ? OR col LIKE ? ) ) Literal SQL and value type operators The basic premise of SQL::Abstract is that in WHERE specifications the "left side" is a column name and the "right side" is a value (normally rendered as a placeholder). This holds true for both hashrefs and arrayref pairs as you see in the "WHERE CLAUSES" examples above. Sometimes it is necessary to alter this behavior. There are several ways of doing so. -ident This is a virtual operator that signals the string to its right side is an identifier (a column name) and not a value. For example to compare two columns you would write: my %where = ( priority => { '<', 2 }, requestor => { -ident => 'submitter' }, ); which creates: $stmt = "WHERE priority < ? AND requestor = submitter"; @bind = ('2'); If you are maintaining legacy code you may see a different construct as described in "Deprecated usage of Literal SQL", please use "-ident" in new code. -value This is a virtual operator that signals that the construct to its right side is a value to be passed to DBI. This is for example necessary when you want to write a where clause against an array (for RDBMS that support such datatypes). For example: my %where = ( array => { -value => [1, 2, 3] } ); will result in: $stmt = 'WHERE array = ?'; @bind = ([1, 2, 3]); Note that if you were to simply say: my %where = ( array => [1, 2, 3] ); the result would probably not be what you wanted: $stmt = 'WHERE array = ? OR array = ? OR array = ?'; @bind = (1, 2, 3); Literal SQL Finally, sometimes only literal SQL will do. To include a random snippet of SQL verbatim, you specify it as a scalar reference. Consider this only as a last resort. Usually there is a better way. For example: my %where = ( priority => { '<', 2 }, requestor => { -in => \'(SELECT name FROM hitmen)' }, ); Would create: $stmt = "WHERE priority < ? AND requestor IN (SELECT name FROM hitmen)" @bind = (2); Note that in this example, you only get one bind parameter back, since the verbatim SQL is passed as part of the statement. CAVEAT Never use untrusted input as a literal SQL argument - this is a massive security risk (there is no way to check literal snippets for SQL injections and other nastyness). If you need to deal with untrusted input use literal SQL with placeholders as described next. Literal SQL with placeholders and bind values (subqueries) If the literal SQL to be inserted has placeholders and bind values, use a reference to an arrayref (yes this is a double reference -- not so common, but perfectly legal Perl). For example, to find a date in Postgres you can use something like this: my %where = ( date_column => \[ "= date '2008-09-30' - ?::integer", 10 ] ) This would create: $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )" @bind = ('10'); Note that you must pass the bind values in the same format as they are returned by where. This means that if you set "bindtype" to "columns", you must provide the bind values in the "[ column_meta => value ]" format, where "column_meta" is an opaque scalar value; most commonly the column name, but you can use any scalar value (including references and blessed references), SQL::Abstract will simply pass it through intact. So if "bindtype" is set to "columns" the above example will look like: my %where = ( date_column => \[ "= date '2008-09-30' - ?::integer", [ {} => 10 ] ] ) Literal SQL is especially useful for nesting parenthesized clauses in the main SQL query. Here is a first example : my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?", 100, "foo%"); my %where = ( foo => 1234, bar => \["IN ($sub_stmt)" => @sub_bind], ); This yields : $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?))"; @bind = (1234, 100, "foo%"); Other subquery operators, like for example "> ALL" or "NOT IN", are expressed in the same way. Of course the $sub_stmt and its associated bind values can be generated through a former call to "select()" : my ($sub_stmt, @sub_bind) = $sql->select("t1", "c1", {c2 => {"<" => 100}, c3 => {-like => "foo%"}}); my %where = ( foo => 1234, bar => \["> ALL ($sub_stmt)" => @sub_bind], ); In the examples above, the subquery was used as an operator on a column; but the same principle also applies for a clause within the main %where hash, like an EXISTS subquery : my ($sub_stmt, @sub_bind) = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"}); my %where = ( -and => [ foo => 1234, \["EXISTS ($sub_stmt)" => @sub_bind], ]); which yields $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1 WHERE c1 = ? AND c2 > t0.c0))"; @bind = (1234, 1); Observe that the condition on "c2" in the subquery refers to column "t0.c0" of the main query : this is *not* a bind value, so we have to express it through a scalar ref. Writing "c2 => {">" => "t0.c0"}" would have generated "c2 > ?" with bind value "t0.c0" ... not exactly what we wanted here. Finally, here is an example where a subquery is used for expressing unary negation: my ($sub_stmt, @sub_bind) = $sql->where({age => [{"<" => 10}, {">" => 20}]}); $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause my %where = ( lname => {like => '%son%'}, \["NOT ($sub_stmt)" => @sub_bind], ); This yields $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )" @bind = ('%son%', 10, 20) Deprecated usage of Literal SQL Below are some examples of archaic use of literal SQL. It is shown only as reference for those who deal with legacy code. Each example has a much better, cleaner and safer alternative that users should opt for in new code. * my %where = ( requestor => \'IS NOT NULL' ) $stmt = "WHERE requestor IS NOT NULL" This used to be the way of generating NULL comparisons, before the handling of "undef" got formalized. For new code please use the superior syntax as described in "Tests for NULL values". * my %where = ( requestor => \'= submitter' ) $stmt = "WHERE requestor = submitter" This used to be the only way to compare columns. Use the superior "-ident" method for all new code. For example an identifier declared in such a way will be properly quoted if "quote_char" is properly set, while the legacy form will remain as supplied. * my %where = ( is_ready => \"", completed => { '>', '2012-12-21' } ) $stmt = "WHERE completed > ? AND is_ready" @bind = ('2012-12-21') Using an empty string literal used to be the only way to express a boolean. For all new code please use the much more readable -bool operator. Conclusion These pages could go on for a while, since the nesting of the data structures this module can handle are pretty much unlimited (the module implements the "WHERE" expansion as a recursive function internally). Your best bet is to "play around" with the module a little to see how the data structures behave, and choose the best format for your data based on that. And of course, all the values above will probably be replaced with variables gotten from forms or the command line. After all, if you knew everything ahead of time, you wouldn't have to worry about dynamically-generating SQL and could just hardwire it into your script. ORDER BY CLAUSES Some functions take an order by clause. This can either be a scalar (just a column name), a hashref of "{ -desc => 'col' }" or "{ -asc => 'col' }", a scalarref, an arrayref-ref, or an arrayref of any of the previous forms. Examples: Given | Will Generate --------------------------------------------------------------- | 'colA' | ORDER BY colA | [qw/colA colB/] | ORDER BY colA, colB | {-asc => 'colA'} | ORDER BY colA ASC | {-desc => 'colB'} | ORDER BY colB DESC | ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC | { -asc => [qw/colA colB/] } | ORDER BY colA ASC, colB ASC | \'colA DESC' | ORDER BY colA DESC | \[ 'FUNC(colA, ?)', $x ] | ORDER BY FUNC(colA, ?) | /* ...with $x bound to ? */ | [ | ORDER BY { -asc => 'colA' }, | colA ASC, { -desc => [qw/colB/] }, | colB DESC, { -asc => [qw/colC colD/] },| colC ASC, colD ASC, \'colE DESC', | colE DESC, \[ 'FUNC(colF, ?)', $x ], | FUNC(colF, ?) ] | /* ...with $x bound to ? */ =============================================================== SPECIAL OPERATORS my $sqlmaker = SQL::Abstract->new(special_ops => [ { regex => qr/.../, handler => sub { my ($self, $field, $op, $arg) = @_; ... }, }, { regex => qr/.../, handler => 'method_name', }, ]); A "special operator" is a SQL syntactic clause that can be applied to a field, instead of a usual binary operator. For example : WHERE field IN (?, ?, ?) WHERE field BETWEEN ? AND ? WHERE MATCH(field) AGAINST (?, ?) Special operators IN and BETWEEN are fairly standard and therefore are builtin within "SQL::Abstract" (as the overridable methods "_where_field_IN" and "_where_field_BETWEEN"). For other operators, like the MATCH .. AGAINST example above which is specific to MySQL, you can write your own operator handlers - supply a "special_ops" argument to the "new" method. That argument takes an arrayref of operator definitions; each operator definition is a hashref with two entries: regex the regular expression to match the operator handler Either a coderef or a plain scalar method name. In both cases the expected return is "($sql, @bind)". When supplied with a method name, it is simply called on the SQL::Abstract object as: $self->$method_name($field, $op, $arg) Where: $field is the LHS of the operator $op is the part that matched the handler regex $arg is the RHS When supplied with a coderef, it is called as: $coderef->($self, $field, $op, $arg) For example, here is an implementation of the MATCH .. AGAINST syntax for MySQL my $sqlmaker = SQL::Abstract->new(special_ops => [ # special op for MySql MATCH (field) AGAINST(word1, word2, ...) {regex => qr/^match$/i, handler => sub { my ($self, $field, $op, $arg) = @_; $arg = [$arg] if not ref $arg; my $label = $self->_quote($field); my ($placeholder) = $self->_convert('?'); my $placeholders = join ", ", (($placeholder) x @$arg); my $sql = $self->_sqlcase('match') . " ($label) " . $self->_sqlcase('against') . " ($placeholders) "; my @bind = $self->_bindtype($field, @$arg); return ($sql, @bind); } }, ]); UNARY OPERATORS my $sqlmaker = SQL::Abstract->new(unary_ops => [ { regex => qr/.../, handler => sub { my ($self, $op, $arg) = @_; ... }, }, { regex => qr/.../, handler => 'method_name', }, ]); A "unary operator" is a SQL syntactic clause that can be applied to a field - the operator goes before the field You can write your own operator handlers - supply a "unary_ops" argument to the "new" method. That argument takes an arrayref of operator definitions; each operator definition is a hashref with two entries: regex the regular expression to match the operator handler Either a coderef or a plain scalar method name. In both cases the expected return is $sql. When supplied with a method name, it is simply called on the SQL::Abstract object as: $self->$method_name($op, $arg) Where: $op is the part that matched the handler regex $arg is the RHS or argument of the operator When supplied with a coderef, it is called as: $coderef->($self, $op, $arg) PERFORMANCE Thanks to some benchmarking by Mark Stosberg, it turns out that this module is many orders of magnitude faster than using "DBIx::Abstract". I must admit this wasn't an intentional design issue, but it's a byproduct of the fact that you get to control your "DBI" handles yourself. To maximize performance, use a code snippet like the following: # prepare a statement handle using the first row # and then reuse it for the rest of the rows my($sth, $stmt); for my $href (@array_of_hashrefs) { $stmt ||= $sql->insert('table', $href); $sth ||= $dbh->prepare($stmt); $sth->execute($sql->values($href)); } The reason this works is because the keys in your $href are sorted internally by SQL::Abstract. Thus, as long as your data retains the same structure, you only have to generate the SQL the first time around. On subsequent queries, simply use the "values" function provided by this module to return your values in the correct order. However this depends on the values having the same type - if, for example, the values of a where clause may either have values (resulting in sql of the form "column = ?" with a single bind value), or alternatively the values might be "undef" (resulting in sql of the form "column IS NULL" with no bind value) then the caching technique suggested will not work. FORMBUILDER If you use my "CGI::FormBuilder" module at all, you'll hopefully really like this part (I do, at least). Building up a complex query can be as simple as the following: #!/usr/bin/perl use warnings; use strict; use CGI::FormBuilder; use SQL::Abstract; my $form = CGI::FormBuilder->new(...); my $sql = SQL::Abstract->new; if ($form->submitted) { my $field = $form->field; my $id = delete $field->{id}; my($stmt, @bind) = $sql->update('table', $field, {id => $id}); } Of course, you would still have to connect using "DBI" to run the query, but the point is that if you make your form look like your table, the actual query script can be extremely simplistic. If you're REALLY lazy (I am), check out "HTML::QuickTable" for a fast interface to returning and formatting data. I frequently use these three modules together to write complex database query apps in under 50 lines. HOW TO CONTRIBUTE Contributions are always welcome, in all usable forms (we especially welcome documentation improvements). The delivery methods include git- or unified-diff formatted patches, GitHub pull requests, or plain bug reports either via RT or the Mailing list. Contributors are generally granted full access to the official repository after their first several patches pass successful review. This project is maintained in a git repository. The code and related tools are accessible at the following locations: * Official repo: * Official gitweb: * GitHub mirror: * Authorized committers: CHANGES Version 1.50 was a major internal refactoring of "SQL::Abstract". Great care has been taken to preserve the *published* behavior documented in previous versions in the 1.* family; however, some features that were previously undocumented, or behaved differently from the documentation, had to be changed in order to clarify the semantics. Hence, client code that was relying on some dark areas of "SQL::Abstract" v1.* might behave differently in v1.50. The main changes are : * support for literal SQL through the "\ [ $sql, @bind ]" syntax. * support for the { operator => \"..." } construct (to embed literal SQL) * support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values) * optional support for array datatypes * defensive programming : check arguments * fixed bug with global logic, which was previously implemented through global variables yielding side-effects. Prior versions would interpret "[ {cond1, cond2}, [cond3, cond4] ]" as "(cond1 AND cond2) OR (cond3 AND cond4)". Now this is interpreted as "(cond1 AND cond2) OR (cond3 OR cond4)". * fixed semantics of _bindtype on array args * dropped the "_anoncopy" of the %where tree. No longer necessary, we just avoid shifting arrays within that tree. * dropped the "_modlogic" function ACKNOWLEDGEMENTS There are a number of individuals that have really helped out with this module. Unfortunately, most of them submitted bugs via CPAN so I have no idea who they are! But the people I do know are: Ash Berlin (order_by hash term support) Matt Trout (DBIx::Class support) Mark Stosberg (benchmarking) Chas Owens (initial "IN" operator support) Philip Collins (per-field SQL functions) Eric Kolve (hashref "AND" support) Mike Fragassi (enhancements to "BETWEEN" and "LIKE") Dan Kubb (support for "quote_char" and "name_sep") Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by) Laurent Dami (internal refactoring, extensible list of special operators, literal SQL) Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests) Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests) Oliver Charles (support for "RETURNING" after "INSERT") Thanks! SEE ALSO DBIx::Class, DBIx::Abstract, CGI::FormBuilder, HTML::QuickTable. AUTHOR Copyright (c) 2001-2007 Nathan Wiger . All Rights Reserved. This module is actively maintained by Matt Trout For support, your best bet is to try the "DBIx::Class" users mailing list. While not an official support venue, "DBIx::Class" makes heavy use of "SQL::Abstract", and as such list members there are very familiar with how to create queries. LICENSE This module is free software; you may copy this under the same terms as perl itself (either the GNU General Public License or the Artistic License) SQL-Abstract-1.85/Changes0000644000000000000000000004001213233057053015136 0ustar00rootroot00000000000000Revision history for SQL::Abstract 1.85 - 2018-01-27 - Restore perl version requirement missed in the Distar port - Factor out the SET ... part of UPDATE for subclassability (GH#12) 1.84 - 2017-04-03 - Restore 'dynamic_config => 0' missed in the Distar port 1.83 - 2017-04-03 - Support for DELETE ... RETURNING (GH#9) - Port to Distar revision 1.82 2017-03-20 ------------------------- - Add explicit dependency on Sub::Quote (GH#8) - Fix syntax errors in ORDER BY docs (GH#7) revision 1.81_01 2017-02-28 ---------------------------- - Fix order clauses with bind parameters in ->where - Fix ->insert($table, \@values) with >26 values (RT#112684) - Teach ::Tree that ILIKE (PostgreSQL) and REGEXP (MySQL) are binary ops - Support for UPDATE ... RETURNING - Documentation improvements for ORDER BY revision 1.81 2014-10-25 ---------------------------- - Fix overly-enthusiastic parenthesis unroller (RT#99503) revision 1.80 2014-10-05 ---------------------------- - Fix erroneous behavior of is_literal_value($) wrt { -ident => ... } - Explicitly croak on top-level special ops (they didn't work anyway) revision 1.79 2014-09-25 ---------------------------- - New exportable functions: is_literal_value($) and is_plain_value($) - New attribute 'escape_char' allowing for proper escape of quote_chars present in an identifier - Deprecate { "" => \... } constructs - Treat { -value => undef } as plain undef in all cases - Explicitly throw on { -ident => undef } revision 1.78 2014-05-28 ---------------------------- - Fix parsing of binary ops to correctly take up only a single LHS element, instead of gobbling up the entire parse-to-date - Explicitly handle ROW_NUMBER() OVER as the snowflake-operator it is - Improve signatures/documentation of is_same_sql_bind / eq_sql_bind - Retire script/format-sql - the utility needs more work to be truly end-user convenient revision 1.77 2014-01-17 ---------------------------- - Reintroduce { -not => undef } column operator (regression from 1.75) revision 1.75 2013-12-27 ---------------------------- - *UPCOMING INCOMPATIBLE BUGFIX*: SQLA used to generate incorrect SQL on undef-containing lists fed to -in and -not_in. An exception will be raised for a while before properly fixing this, to avoid quiet but subtle changes to query results in production - Deprecate and warn when supplying an empty arrayref to like/not_like operators (likely to be removed before 2.0) - Warn when using an inequality operator with a multi-value array to arrive at what amounts to a 1=1 condition (no pre-2.0 plans to fix this behavior due to backwards comp concerns) - Fix false negative comparison of ORDER BY ASC - More improvements of incorrect parsing (placeholder at end of list element) - Fix typos in POD and comments (RT#87776) - Augment -not_bool example with nesting (RT#89601) revision 1.74 2013-06-04 ---------------------------- - Fix insufficient parenthesis unroll during operator comparison - 'ORDER BY foo' and 'ORDER BY foo ASC' are now considered equal by default (with a switch to reenable old behavior when necessary) - Change parser to not eagerly slurp RHS expressions it doesn't recognize revision 1.73 2012-07-10 ---------------------------- - Fix parsing of ORDER BY foo + ? - Stop filling in placeholders in `format-sql` since it does not support passing values for them anyway - Fix parsing of NOT EXISTS - Fix over-eager parenthesis unrolling - Fix deep recursion warnings while parsing obnoxiously long sql statements - Fix incorrect comparison of malformed lists - Fix incorrect reporting of mismatch-members in SQLA::Test - Migrate the -ident operator from DBIC into SQLA - Migrate the -value operator from DBIC into SQLA revision 1.72 2010-12-21 ---------------------------- - Extra checks of search arguments for possible SQL injection attacks - Remove excess parentheses in debug SQL - Fix parsing of foo.* in SQLA::Tree - Fix bindtype fail when using -between with arrayrefref literals - Add handling for NULL for -in - The -nest operator has entered semi-deprecated status and has been undocumented. Please do not use it in new code revision 1.71 2010-11-09 ---------------------------- - Add EXECUTING for clarity of long running SQL - Add "squash_repeats" option to fix it such that repeated SQL gets ellided except for placeholders - Highlight transaction keywords - Highlight HAVING - Leave quotes from DBIC in bindargs - Add error checking on "profile" for SQLA::Tree - Hide bulk inserts from DBIx::Class - Fix missing doc (RT#62587) - Format functions in MySQL-friendly manner foo( ... ) vs foo ( ... ) revision 1.69 2010-10-22 ---------------------------- - Add quotes for populated placeholders and make the background magenta instead of cyan - Color and indent pagination keywords - Fix a silly bug which broke placeholder fill-in in DBIC - Installs format-sql to format SQL passed in over STDIN - Switch the tokenizer to precompiled regexes (massive speedup) - Rudimentary handling of quotes ( 'WHERE' vs WHERE ) - Fix extended argument parsing by IN/BETWEEN - Add proper handling of lists (foo,bar,?) - Better handling of generic -function's during AST construction - Special handle IS NOT? NULL - Make sure unparse() does not destroy a passed in \@bindargs - Support ops with _'s in them (valid in Oracle) - Properly parse both types of default value inserts - Allow { -func => $val } as arguments to UPDATE revision 1.68 2010-09-16 ---------------------------- - Document methods on Tree - Add affordances for color coding placeholders - Change ::Tree::whitespace to whitespace_keyword revision 1.67_03 2010-09-11 ---------------------------- - Add docs for SQL::Abstract::Tree->new - correcty merge profile and parameters - added fill_in_placeholders option for excellent copy/pasta revision 1.67_02 2010-09-08 ---------------------------- - rename DBIx::Class::Storage::PrettyPrinter to DBIx::Class::Storage::Debug::PrettyPrint - decreased a lot of indentation from ::Tree - cleaned up handling of newlines inside of parens revision 1.67_01 2010-09-06 ---------------------------- - Add SQL::Abstract::Tree - Add unindexed DBIx::Class::Storage::PrettyPrinter - Better documentation of undef/NULL in where clause - Depend on bugfixed Module::Install (now again installs on old < 5.8.3 perls) revision 1.67 2010-05-31 14:21 (UTC) ---------------------------- - Fix SQL::Test failure when first chunk is an unrecognized literal - Generic -not operator tests - More columns-bindtype assertion checks revision 1.66 2010-04-27 02:44 (UTC) ---------------------------- - Optimized the quoting mechanism, winning nearly 10% speedup on repeatable sql generation revision 1.65 2010-04-11 19:59 (UTC) ---------------------------- - Rerelease last version to not include .svn files and grab MANIFEST.SKIP from DBIx::Class so it won't happen again revision 1.64 2010-04-11 16:58 (UTC) ---------------------------- - Fix multiple generic op handling regressions by reverting the auto-equality assumption (turned out to be a very very bad idea) revision 1.63 2010-03-24 09:56 (UTC) ---------------------------- - Add ILIKE to the core list of comparision ops revision 1.62 2010-03-15 11:06 (UTC) ---------------------------- - Fixed open outer parens for a multi-line literal - Allow recursively-nested column-functions in WHERE - Bumped minimum perl to 5.6.2 and changed tests to rely on core dependencies revision 1.61 2010-02-05 16:28 (UTC) ---------------------------- - Allow INSERT to take additional attributes - Support for INSERT ... RETURNING - Another iteration of SQL::Abstract::Test fixes and improvements revision 1.60 2009-09-22 11:03 (UTC) ---------------------------- - fix a well masked error in the sql-test tokenizer revision 1.59 2009-09-22 08:39 (UTC) ---------------------------- - fixed a couple of untrapped undefined warnings - allow -in/-between to accept literal sql in all logical variants - see POD for details - unroll multiple parenthesis around IN arguments to accomodate crappy databases revision 1.58 2009-09-04 15:20 (UTC) ---------------------------- - expanded the scope of -bool and -not_bool operators - added proper testing support revision 1.57 2009-09-03 20:18 (UTC) ---------------------------- - added -bool and -not_bool operators revision 1.56 2009-05-30 16:31 (UTC) ---------------------------- - support for \[$sql, @bind] in order_by clauses e.g.: { -desc => \['colA LIKE ?', 'somestring'] } revision 1.55 2009-05-17 22:54 (UTC) ---------------------------- - make sure that sql generation does not mutate the supplied where condition structure revision 1.54 2009-05-07 17:23 (UTC) ---------------------------- - allow special_operators to take both code refs and method names (makes it possible to properly subclass the builtin ones) revision 1.53 2009-04-30 14:58 (UTC) ---------------------------- - make sure hash keys are sorted in all search sub-conditions - switch installer from EU::MM to M::I revision 1.52 2009-04-28 23:14 (UTC) ---------------------------- - allow -between to handle [\"", \""] and \["", @bind] - allow order_by to handle -asc|desc => [qw/colA colB/] (artifact from DBIx::Class) - more tests and clearing up of some corner cases - t/10test.t does not run by default (developer only, too cpu intensive) ---------------------------- revision 1.51 2009-03-28 10:00 (UTC) - fixed behavior of [-and => ... ] depending on the current condition scope. This introduces backwards comp with 1.24 ---------------------------- revision 1.50 2009-03-10 12:30 (UTC) - fixed the problem with values() not behaving the same as the rest of the code (RT#43483) - fixed interjecting arrayrefref into a where clause - added value-only insert test with a literal SQL snippet - cleanup and enhancement of t/03values.t - better handling of borked SQL in tests - deal properly with parentheses in is_same_sql_bind() - fixed test subs (is_same_*) in SQL::Abstract::Test to return the correct test value - do not version MANIFEST Version 1.50 was a major internal refactoring of SQL::Abstract. Great care has been taken to preserve the published behavior documented in previous versions in the 1.* family; however, some features that were previously undocumented, or behaved. differently from the documentation, had to be changed in order to clarify the semantics. Hence, client code that was relying on some dark areas of SQL::Abstract v1.* might behave differently in v1.50. ---------------------------- revision 1.49_04 2009-03-03 - add support for a [\%column_meta => value] bind value format ---------------------------- revision 1.49_03 2009-02-17 - clarify syntax of \['...', @bind] when used with a bindtype of 'columns' ---------------------------- revision 1.49_02 2009-02-16 - added an AST-aware SQL::Abstract::Test library for sql syntax tests - vastly expanded test coverage - support for the { operator => \'...'|\['...', @bind] } syntax allowing to embed arbitrary operators on the LHS - fixed multiple regressions wrt DBIx::Class ---------------------------- revision 1.49_01 2009-02-11 - support for literal SQL through the [$sql, bind] syntax. - added -nest1, -nest2 or -nest_1, -nest_2, ... - optional support for array datatypes - defensive programming : check arguments to functions/methods - fixed bug with global logic of -and/-or (no side-effects any more) - changed logic for distributing an op over arrayrefs - fixed semantics of _bindtype on array args - dropped the _anoncopy of the %where tree. No longer necessary. - dropped the _modlogic function - Make col => [] and col => {$op => [] } DTRT or die instead of generating broken SQL. Added tests for this. - Added { -desc => 'column' } order by support - Tiny "$_"-related fix for { -desc => 'columns'} order by support tests + docs ---------------------------- revision 1.20 date: 2005/08/18 18:41:58; author: nwiger; state: Exp; lines: +104 -50 - added patch from Dan Kubb enabling quote_char and name_sep options - added patch from Andy Grundman to enhance _anoncopy for deep refs ---------------------------- revision 1.19 date: 2005/04/29 18:20:30; author: nwiger; state: Exp; lines: +34 -20 added _anoncopy to prevent destroying original; updated docs ---------------------------- revision 1.18 date: 2005/03/07 20:14:12; author: nwiger; state: Exp; lines: +201 -65 added support for -and, -or, and -nest; see docs for details ---------------------------- revision 1.17 date: 2004/08/25 20:11:27; author: nwiger; state: Exp; lines: +58 -46 added patch from Eric Kolve to iterate over all hashref elements ---------------------------- revision 1.16 date: 2004/06/10 17:20:01; author: nwiger; state: Exp; lines: +178 -12 added bindtype param to allow this to work with Orasuck 9+ ---------------------------- revision 1.15 date: 2003/11/05 23:40:40; author: nwiger; state: Exp; lines: +18 -6 several bugfixes, including _convert being applied wrong and the edge case field => { '!=', [qw/this that/] } not working ---------------------------- revision 1.14 date: 2003/11/04 21:20:33; author: nwiger; state: Exp; lines: +115 -34 added patch from Philip Collins, and also added 'convert' option ---------------------------- revision 1.13 date: 2003/05/21 17:22:29; author: nwiger; state: Exp; lines: +230 -74 added "IN" and "BETWEEN" operator support, as well as "NOT" modified where() to support ORDER BY, and fixed some bugs too added PERFORMANCE and FORMBUILDER doc sections fixed several bugs in _recurse_where(), it now works as expected added test suite, many thanks to Chas Owens modified all hash access to return keys sorted, to allow cached queries ---------------------------- revision 1.12 date: 2003/05/08 20:10:56; author: nwiger; state: Exp; lines: +181 -96 1.11 interim checking; major bugfixes and order_by, 1.12 will go to CPAN ---------------------------- revision 1.11 date: 2003/05/02 00:07:30; author: nwiger; state: Exp; lines: +52 -12 many minor enhancements to add querying flexibility ---------------------------- revision 1.10 date: 2002/09/27 18:06:25; author: nwiger; state: Exp; lines: +6 -2 added precatch for messed up where string ---------------------------- revision 1.9 date: 2002/08/29 18:04:35; author: nwiger; state: Exp; lines: +4 -3 CPAN ---------------------------- revision 1.8 date: 2001/11/07 22:18:12; author: nwiger; state: Exp; lines: +31 -14 added embedded SCALAR ref capability to insert() and update() ---------------------------- revision 1.7 date: 2001/11/07 01:23:28; author: nwiger; state: Exp; lines: +3 -3 damn uninit warning ---------------------------- revision 1.6 date: 2001/11/06 21:09:44; author: nwiger; state: Exp; lines: +14 -6 oops, had to actually *implement* the order by for select()! ---------------------------- revision 1.5 date: 2001/11/06 03:13:16; author: nwiger; state: Exp; lines: +43 -4 lots of docs ---------------------------- revision 1.4 date: 2001/11/06 03:07:42; author: nwiger; state: Exp; lines: +16 -7 added extra layer of ()'s to ensure correct semantics on AND ---------------------------- revision 1.3 date: 2001/11/06 01:16:31; author: nwiger; state: Exp; lines: +11 -10 updated all statements so that they use wantarray to just return SQL if asked ---------------------------- revision 1.2 date: 2001/10/26 22:23:46; author: nwiger; state: Exp; lines: +112 -15 added scalar ref for SQL verbatim in where, fixed bugs, array ref, docs ---------------------------- revision 1.1 date: 2001/10/24 00:26:43; author: nwiger; state: Exp; Initial revision SQL-Abstract-1.85/examples/0000755000000000000000000000000013233057465015473 5ustar00rootroot00000000000000SQL-Abstract-1.85/examples/dbic-console.pl0000644000000000000000000000065412353347763020403 0ustar00rootroot00000000000000#!/sur/bin/env perl use warnings; use strict; use DBIx::Class::Storage::Debug::PrettyPrint; my $pp = DBIx::Class::Storage::Debug::PrettyPrint->new({ profile => 'console', show_progress => 1, }); $pp->txn_begin; $pp->query_start("SELECT a, b, c FROM foo WHERE foo.a =1 and foo.b LIKE ?", q('station')); sleep 1; $pp->query_end("SELECT a, b, c FROM foo WHERE foo.a =1 and foo.b LIKE ?", q('station')); $pp->txn_commit; SQL-Abstract-1.85/examples/sqla-format0000755000000000000000000000251212353347763017654 0ustar00rootroot00000000000000#!/usr/bin/env perl use warnings; use strict; use Getopt::Long; my $p = Getopt::Long::Parser->new(config => [qw( gnu_getopt no_ignore_case )]); my $opts = { profile => 'console', help => \&showhelp }; $p->getoptions( $opts, qw( profile|p=s help|h )) or showhelp(); sub showhelp { require Pod::Usage; Pod::Usage::pod2usage( -verbose => 0, -exitval => 2 ); } require SQL::Abstract::Tree; my $sqlat = SQL::Abstract::Tree->new({ profile => $opts->{profile}, fill_in_placeholders => 0 }); my $chunk = ''; my $leftover = ''; do { $chunk = $leftover . $chunk if length $leftover; if ($chunk =~ / \A (.+?) (?: (?<=\S)\:\s+\'[^\n]+ # pasting DBIC_TRACE output directly | \;(?: \s | \z) | \z | ^ \s* (?=SELECT|INSERT|UPDATE|DELETE) ) (.*) /smix) { $leftover = $2; print $sqlat->format($1); print "\n"; } else { $leftover = $chunk; } } while ( (read *STDIN, $chunk, 4096) or length $leftover ); =head1 NAME sqla-format - An intelligent SQL formatter =head1 SYNOPSIS ~$ sqla-format << log.sql ~$ myprogram -v | sqla-format -p html > sqltrace.html =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2014 by Arthur Axel "fREW" Schmidt. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. SQL-Abstract-1.85/examples/console.pl0000644000000000000000000000757712353347763017517 0ustar00rootroot00000000000000#!/sur/bin/env perl use warnings; use strict; use SQL::Abstract::Tree; my $sqlat = SQL::Abstract::Tree->new({ profile => 'console' }); my @sql = ( "BEGIN WORK", "SELECT a, b, c FROM foo WHERE foo.a =1 and foo.b LIKE 'station'", "SELECT * FROM (SELECT * FROM foobar) WHERE foo.a =1 and foo.b LIKE 'station'", "SELECT * FROM lolz WHERE ( foo.a =1 ) and foo.b LIKE 'station'", "SELECT * LIMIT 5 OFFSET 5 FROM lolz ", "SELECT * LIMIT 5 5 FROM lolz ", "SELECT SKIP 5 FIRST 5 * FROM lolz ", "SELECT FIRST 5 SKIP 5 * FROM lolz ", "UPDATE session SET expires = ? WHERE (id = ?)", "INSERT INTO Request (creation_date, is_private, owner_id, request) VALUES (? , ? , ? , ?)", "SELECT [screen].[id], [screen].[name], [screen].[section_id], [screen].[xtype] FROM [users_roles] [me] JOIN [roles] [role] ON [role].[id] = [me].[role_id] JOIN [roles_permissions] [role_permissions] ON [role_permissions].[role_id] = [role].[id] JOIN [permissions] [permission] ON [permission].[id] = [role_permissions].[permission_id] JOIN [permissionscreens] [permission_screens] ON [permission_screens].[permission_id] = [permission].[id] JOIN [screens] [screen] ON [screen].[id] = [permission_screens].[screen_id] WHERE ( [me].[user_id] = ? ) GROUP BY [screen].[id], [screen].[name], [screen].[section_id], [screen].[xtype]", "SELECT [status], [supplier_id], [ship_to_supplier_id], [request_by_user_id], [is_printed], [creation_date], [id], [date], [fob_state], [is_confirmed], [is_outside_process], [ship_via], [special_instructions], [when_shipped] FROM ( SELECT [status], [supplier_id], [ship_to_supplier_id], [request_by_user_id], [is_printed], [creation_date], [id], [date], [fob_state], [is_confirmed], [is_outside_process], [ship_via], [special_instructions], [when_shipped], ROW_NUMBER() OVER( ORDER BY [me].[id] DESC ) AS [rno__row__index] FROM ( SELECT [me].[status], [me].[supplier_id], [me].[ship_to_supplier_id], [me].[request_by_user_id], [me].[is_printed], [me].[creation_date], [me].[id], [me].[date], [me].[fob_state], [me].[is_confirmed], [me].[is_outside_process], [me].[ship_via], [me].[special_instructions], [me].[when_shipped] FROM [PurchaseOrders] [me] WHERE ( [me].[status] = ? ) ) [me] ) [me] WHERE [rno__row__index] BETWEEN 1 AND 25", "SELECT me.id, me.name, me.creator_id, group_users.group_id, group_users.user_id, user.id, user.first_name, user.last_name, user.nickname, user.email, user.password, user.is_active, user.logins FROM Group me LEFT JOIN GroupUser group_users ON group_users.group_id = me.id LEFT JOIN User user ON user.id = group_users.user_id WHERE (me.creator_id = ?) ORDER BY name, group_users.group_id", "COMMIT", 'ROLLBACK', 'SAVEPOINT station', 'ROLLBACK TO SAVEPOINT station', 'RELEASE SAVEPOINT station', "SELECT COUNT( * ) FROM message_children me WHERE( ( me.phone_number NOT IN ( SELECT message_child.phone_number FROM blocked_destinations me JOIN message_children_status reason ON reason.id = me.reason_id JOIN message_children message_child ON message_child.id = reason.message_child_id) AND ( ( me.api_id IS NULL ) ) ) )" ); print "\n\n'" . $sqlat->format($_) . "'\n" for @sql; print "\n\n'" . $sqlat->format( "UPDATE session SET expires = ? WHERE (id = ?)", ['2010-12-02', 1] ) . "'\n"; print "\n\n'" . $sqlat->format( "SELECT raw_scores FROM ( SELECT raw_scores, ROW_NUMBER() OVER ( ORDER BY ( SELECT (1))) AS rno__row__index FROM ( SELECT rpt_score.raw_scores FROM users me JOIN access access ON access.userid = me.userid JOIN mgmt mgmt ON mgmt.mgmtid = access.mgmtid JOIN [order] orders ON orders.mgmtid = mgmt.mgmtid JOIN shop shops ON shops.orderno = orders.orderno JOIN rpt_scores rpt_score ON rpt_score.shopno = shops.shopno WHERE ( datecompleted IS NOT NULL AND ( (shops.datecompleted BETWEEN ? AND ?) AND (type = ? AND me.userid = ?)))) rpt_score) rpt_score WHERE rno__row__index BETWEEN ? AND ? )", ['2009-10-01', '2009-10-08', 1, 'frew', 1, 1] ) . "'\n"; SQL-Abstract-1.85/META.json0000664000000000000000000000431013233057465015276 0ustar00rootroot00000000000000{ "abstract" : "Generate SQL from Perl data structures", "author" : [ "Nathan Wiger " ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.24, CPAN::Meta::Converter version 2.150010", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "SQL-Abstract", "no_index" : { "directory" : [ "t", "xt", "examples" ], "package" : [ "DBIx::Class::Storage::Debug::PrettyPrint" ] }, "prereqs" : { "build" : { "requires" : {} }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "develop" : { "requires" : { "Pod::Coverage" : "0.19", "Test::EOL" : "1.0", "Test::NoTabs" : "0.9", "Test::Pod" : "1.14", "Test::Pod::Coverage" : "1.04" } }, "runtime" : { "requires" : { "Exporter" : "5.57", "Hash::Merge" : "0.12", "List::Util" : "0", "MRO::Compat" : "0.12", "Moo" : "2.000001", "Scalar::Util" : "0", "Sub::Quote" : "2.000001", "Text::Balanced" : "2.00", "perl" : "5.006" } }, "test" : { "requires" : { "Storable" : "0", "Test::Deep" : "0.101", "Test::Exception" : "0.31", "Test::More" : "0.88", "Test::Warn" : "0" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "mailto" : "bug-SQL-Abstract@rt.cpan.org", "web" : "https://rt.cpan.org/Public/Dist/Display.html?Name=SQL-Abstract" }, "license" : [ "http://dev.perl.org/licenses/" ], "repository" : { "type" : "git", "url" : "https://github.com/dbsrgits/sql-abstract.git", "web" : "https://github.com/dbsrgits/sql-abstract" }, "x_IRC" : "irc://irc.perl.org/#dbix-class" }, "version" : "1.85", "x_serialization_backend" : "JSON::PP version 2.27400_02" } SQL-Abstract-1.85/lib/0000755000000000000000000000000013233057465014423 5ustar00rootroot00000000000000SQL-Abstract-1.85/lib/DBIx/0000755000000000000000000000000013233057465015211 5ustar00rootroot00000000000000SQL-Abstract-1.85/lib/DBIx/Class/0000755000000000000000000000000013233057465016256 5ustar00rootroot00000000000000SQL-Abstract-1.85/lib/DBIx/Class/Storage/0000755000000000000000000000000013233057465017662 5ustar00rootroot00000000000000SQL-Abstract-1.85/lib/DBIx/Class/Storage/Debug/0000755000000000000000000000000013233057465020710 5ustar00rootroot00000000000000SQL-Abstract-1.85/lib/DBIx/Class/Storage/Debug/PrettyPrint.pm0000644000000000000000000000723713074150107023551 0ustar00rootroot00000000000000package DBIx::Class::Storage::Debug::PrettyPrint; use strict; use warnings; use base 'DBIx::Class::Storage::Statistics'; use SQL::Abstract::Tree; __PACKAGE__->mk_group_accessors( simple => '_sqlat' ); __PACKAGE__->mk_group_accessors( simple => '_clear_line_str' ); __PACKAGE__->mk_group_accessors( simple => '_executing_str' ); __PACKAGE__->mk_group_accessors( simple => '_show_progress' ); __PACKAGE__->mk_group_accessors( simple => '_last_sql' ); __PACKAGE__->mk_group_accessors( simple => 'squash_repeats' ); sub new { my $class = shift; my $args = shift; my $clear_line = $args->{clear_line} || "\r\x1b[J"; my $executing = $args->{executing} || ( eval { require Term::ANSIColor } ? do { my $c = \&Term::ANSIColor::color; $c->('blink white on_black') . 'EXECUTING...' . $c->('reset'); } : 'EXECUTING...' ); my $show_progress = $args->{show_progress}; my $squash_repeats = $args->{squash_repeats}; my $sqlat = SQL::Abstract::Tree->new($args); my $self = $class->next::method(@_); $self->_clear_line_str($clear_line); $self->_executing_str($executing); $self->_show_progress($show_progress); $self->squash_repeats($squash_repeats); $self->_sqlat($sqlat); $self->_last_sql(''); return $self } sub print { my $self = shift; my $string = shift; my $bindargs = shift || []; my ($lw, $lr); ($lw, $string, $lr) = $string =~ /^(\s*)(.+?)(\s*)$/s; local $self->_sqlat->{fill_in_placeholders} = 0 if defined $bindargs && defined $bindargs->[0] && $bindargs->[0] eq q('__BULK_INSERT__'); my $use_placeholders = !!$self->_sqlat->fill_in_placeholders; my $sqlat = $self->_sqlat; my $formatted; if ($self->squash_repeats && $self->_last_sql eq $string) { my ( $l, $r ) = @{ $sqlat->placeholder_surround }; $formatted = '... : ' . join(', ', map "$l$_$r", @$bindargs) } else { $self->_last_sql($string); $formatted = $sqlat->format($string, $bindargs); $formatted = "$formatted : " . join ', ', @{$bindargs} unless $use_placeholders; } $self->next::method("$lw$formatted$lr", @_); } sub query_start { my ($self, $string, @bind) = @_; if (defined $self->callback) { $string =~ m/^(\w+)/; $self->callback->($1, "$string: ".join(', ', @bind)."\n"); return; } $string =~ s/\s+$//; $self->print("$string\n", \@bind); $self->debugfh->print($self->_executing_str) if $self->_show_progress } sub query_end { $_[0]->debugfh->print($_[0]->_clear_line_str) if $_[0]->_show_progress } 1; =pod =head1 NAME DBIx::Class::Storage::Debug::PrettyPrint - Pretty Printing DebugObj =head1 SYNOPSIS DBIC_TRACE_PROFILE=~/dbic.json perl -Ilib ./foo.pl Where dbic.json contains: { "profile":"console", "show_progress":1, "squash_repeats":1 } =head1 METHODS =head2 new my $pp = DBIx::Class::Storage::Debug::PrettyPrint->new({ show_progress => 1, # tries it's best to make it clear that a SQL # statement is still running executing => '...', # the string that is added to the end of SQL # if show_progress is on. You probably don't # need to set this clear_line => '[J', # the string used to erase the string added # to SQL if show_progress is on. Again, the # default is probably good enough. squash_repeats => 1, # set to true to make repeated SQL queries # be ellided and only show the new bind params # any other args are passed through directly to SQL::Abstract::Tree }); SQL-Abstract-1.85/lib/SQL/0000755000000000000000000000000013233057465015062 5ustar00rootroot00000000000000SQL-Abstract-1.85/lib/SQL/Abstract/0000755000000000000000000000000013233057465016625 5ustar00rootroot00000000000000SQL-Abstract-1.85/lib/SQL/Abstract/Tree.pm0000644000000000000000000006241413074150107020057 0ustar00rootroot00000000000000package SQL::Abstract::Tree; use Moo; no warnings 'qw'; use Carp; use Sub::Quote 'quote_sub'; my $op_look_ahead = '(?: (?= [\s\)\(\;] ) | \z)'; my $op_look_behind = '(?: (?<= [\,\s\)\(] ) | \A )'; my $quote_left = qr/[\`\'\"\[]/; my $quote_right = qr/[\`\'\"\]]/; my $placeholder_re = qr/(?: \? | \$\d+ )/x; # These SQL keywords always signal end of the current expression (except inside # of a parenthesized subexpression). # Format: A list of strings that will be compiled to extended syntax ie. # /.../x) regexes, without capturing parentheses. They will be automatically # anchored to op boundaries (excluding quotes) to match the whole token. my @expression_start_keywords = ( 'SELECT', 'UPDATE', 'SET', 'INSERT \s+ INTO', 'DELETE \s+ FROM', 'FROM', '(?: (?: (?: (?: LEFT | RIGHT | FULL ) \s+ )? (?: (?: CROSS | INNER | OUTER ) \s+ )? )? JOIN )', 'ON', 'WHERE', '(?: DEFAULT \s+ )? VALUES', 'GROUP \s+ BY', 'HAVING', 'ORDER \s+ BY', 'SKIP', 'FETCH', 'FIRST', 'LIMIT', 'OFFSET', 'FOR', 'UNION', 'INTERSECT', 'EXCEPT', 'BEGIN \s+ WORK', 'COMMIT', 'ROLLBACK \s+ TO \s+ SAVEPOINT', 'ROLLBACK', 'SAVEPOINT', 'RELEASE \s+ SAVEPOINT', 'RETURNING', ); my $expr_start_re = join ("\n\t|\n", @expression_start_keywords ); $expr_start_re = qr/ $op_look_behind (?i: $expr_start_re ) $op_look_ahead /x; # These are binary operator keywords always a single LHS and RHS # * AND/OR are handled separately as they are N-ary # * so is NOT as being unary # * BETWEEN without parentheses around the ANDed arguments (which # makes it a non-binary op) is detected and accommodated in # _recurse_parse() # * AS is not really an operator but is handled here as it's also LHS/RHS # this will be included in the $binary_op_re, the distinction is interesting during # testing as one is tighter than the other, plus alphanum cmp ops have different # look ahead/behind (e.g. "x"="y" ) my @alphanum_cmp_op_keywords = (qw/< > != <> = <= >= /); my $alphanum_cmp_op_re = join ("\n\t|\n", map { "(?: (?<= [\\w\\s] | $quote_right ) | \\A )" . quotemeta ($_) . "(?: (?= [\\w\\s] | $quote_left ) | \\z )" } @alphanum_cmp_op_keywords ); $alphanum_cmp_op_re = qr/$alphanum_cmp_op_re/x; my $binary_op_re = '(?: NOT \s+)? (?:' . join ('|', qw/IN BETWEEN [RI]?LIKE REGEXP/) . ')'; $binary_op_re = join "\n\t|\n", "$op_look_behind (?i: $binary_op_re | AS ) $op_look_ahead", $alphanum_cmp_op_re, $op_look_behind . 'IS (?:\s+ NOT)?' . "(?= \\s+ NULL \\b | $op_look_ahead )", ; $binary_op_re = qr/$binary_op_re/x; my $rno_re = qr/ROW_NUMBER \s* \( \s* \) \s+ OVER/ix; my $unary_op_re = 'NOT \s+ EXISTS | NOT | ' . $rno_re; $unary_op_re = join "\n\t|\n", "$op_look_behind (?i: $unary_op_re ) $op_look_ahead", ; $unary_op_re = qr/$unary_op_re/x; my $asc_desc_re = qr/$op_look_behind (?i: ASC | DESC ) $op_look_ahead /x; my $and_or_re = qr/$op_look_behind (?i: AND | OR ) $op_look_ahead /x; my $tokenizer_re = join("\n\t|\n", $expr_start_re, $binary_op_re, $unary_op_re, $asc_desc_re, $and_or_re, $op_look_behind . ' \* ' . $op_look_ahead, (map { quotemeta $_ } qw/, ( )/), $placeholder_re, ); # this one *is* capturing for the split below # splits on whitespace if all else fails # has to happen before the composing qr's are anchored (below) $tokenizer_re = qr/ \s* ( $tokenizer_re ) \s* | \s+ /x; # Parser states for _recurse_parse() use constant PARSE_TOP_LEVEL => 0; use constant PARSE_IN_EXPR => 1; use constant PARSE_IN_PARENS => 2; use constant PARSE_IN_FUNC => 3; use constant PARSE_RHS => 4; use constant PARSE_LIST_ELT => 5; my $expr_term_re = qr/$expr_start_re | \)/x; my $rhs_term_re = qr/ $expr_term_re | $binary_op_re | $unary_op_re | $asc_desc_re | $and_or_re | \, /x; my $all_std_keywords_re = qr/ $rhs_term_re | \( | $placeholder_re /x; # anchor everything - even though keywords are separated by the tokenizer, leakage may occur for ( $quote_left, $quote_right, $placeholder_re, $expr_start_re, $alphanum_cmp_op_re, $binary_op_re, $unary_op_re, $asc_desc_re, $and_or_re, $expr_term_re, $rhs_term_re, $all_std_keywords_re, ) { $_ = qr/ \A $_ \z /x; } # what can be bunched together under one MISC in an AST my $compressable_node_re = qr/^ \- (?: MISC | LITERAL | PLACEHOLDER ) $/x; my %indents = ( select => 0, update => 0, 'insert into' => 0, 'delete from' => 0, from => 1, where => 0, join => 1, 'left join' => 1, on => 2, having => 0, 'group by' => 0, 'order by' => 0, set => 1, into => 1, values => 1, limit => 1, offset => 1, skip => 1, first => 1, ); has [qw( newline indent_string indent_amount fill_in_placeholders placeholder_surround )] => (is => 'ro'); has [qw( indentmap colormap )] => ( is => 'ro', default => quote_sub('{}') ); # class global is in fact desired my $merger; sub BUILDARGS { my $class = shift; my $args = ref $_[0] eq 'HASH' ? $_[0] : {@_}; if (my $p = delete $args->{profile}) { my %extra_args; if ($p eq 'console') { %extra_args = ( fill_in_placeholders => 1, placeholder_surround => ['?/', ''], indent_string => ' ', indent_amount => 2, newline => "\n", colormap => {}, indentmap => \%indents, ! ( eval { require Term::ANSIColor } ) ? () : do { my $c = \&Term::ANSIColor::color; my $red = [$c->('red') , $c->('reset')]; my $cyan = [$c->('cyan') , $c->('reset')]; my $green = [$c->('green') , $c->('reset')]; my $yellow = [$c->('yellow') , $c->('reset')]; my $blue = [$c->('blue') , $c->('reset')]; my $magenta = [$c->('magenta'), $c->('reset')]; my $b_o_w = [$c->('black on_white'), $c->('reset')]; ( placeholder_surround => [$c->('black on_magenta'), $c->('reset')], colormap => { 'begin work' => $b_o_w, commit => $b_o_w, rollback => $b_o_w, savepoint => $b_o_w, 'rollback to savepoint' => $b_o_w, 'release savepoint' => $b_o_w, select => $red, 'insert into' => $red, update => $red, 'delete from' => $red, set => $cyan, from => $cyan, where => $green, values => $yellow, join => $magenta, 'left join' => $magenta, on => $blue, 'group by' => $yellow, having => $yellow, 'order by' => $yellow, skip => $green, first => $green, limit => $green, offset => $green, } ); }, ); } elsif ($p eq 'console_monochrome') { %extra_args = ( fill_in_placeholders => 1, placeholder_surround => ['?/', ''], indent_string => ' ', indent_amount => 2, newline => "\n", indentmap => \%indents, ); } elsif ($p eq 'html') { %extra_args = ( fill_in_placeholders => 1, placeholder_surround => ['', ''], indent_string => ' ', indent_amount => 2, newline => "
\n", colormap => { map { (my $class = $_) =~ s/\s+/-/g; ( $_ => [ qq||, '' ] ) } ( keys %indents, qw(commit rollback savepoint), 'begin work', 'rollback to savepoint', 'release savepoint', ) }, indentmap => \%indents, ); } elsif ($p eq 'none') { # nada } else { croak "No such profile '$p'"; } # see if we got any duplicates and merge if needed if (scalar grep { exists $args->{$_} } keys %extra_args) { # heavy-duty merge $args = ($merger ||= do { require Hash::Merge; my $m = Hash::Merge->new; $m->specify_behavior({ SCALAR => { SCALAR => sub { $_[1] }, ARRAY => sub { [ $_[0], @{$_[1]} ] }, HASH => sub { $_[1] }, }, ARRAY => { SCALAR => sub { $_[1] }, ARRAY => sub { $_[1] }, HASH => sub { $_[1] }, }, HASH => { SCALAR => sub { $_[1] }, ARRAY => sub { [ values %{$_[0]}, @{$_[1]} ] }, HASH => sub { Hash::Merge::_merge_hashes( $_[0], $_[1] ) }, }, }, 'SQLA::Tree Behavior' ); $m; })->merge(\%extra_args, $args ); } else { $args = { %extra_args, %$args }; } } $args; } sub parse { my ($self, $s) = @_; return [] unless defined $s; # tokenize string, and remove all optional whitespace my $tokens = []; foreach my $token (split $tokenizer_re, $s) { push @$tokens, $token if ( defined $token and length $token and $token =~ /\S/ ); } return [ $self->_recurse_parse($tokens, PARSE_TOP_LEVEL) ]; } sub _recurse_parse { my ($self, $tokens, $state) = @_; my @left; while (1) { # left-associative parsing if (! @$tokens or ($state == PARSE_IN_PARENS && $tokens->[0] eq ')') or ($state == PARSE_IN_EXPR && $tokens->[0] =~ $expr_term_re ) or ($state == PARSE_RHS && $tokens->[0] =~ $rhs_term_re ) or ($state == PARSE_LIST_ELT && ( $tokens->[0] eq ',' or $tokens->[0] =~ $expr_term_re ) ) ) { return @left; } my $token = shift @$tokens; # nested expression in () if ($token eq '(' ) { my @right = $self->_recurse_parse($tokens, PARSE_IN_PARENS); $token = shift @$tokens or croak "missing closing ')' around block " . $self->unparse(\@right); $token eq ')' or croak "unexpected token '$token' terminating block " . $self->unparse(\@right); push @left, [ '-PAREN' => \@right ]; } # AND/OR elsif ($token =~ $and_or_re) { my $op = uc $token; my @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR); # Merge chunks if "logic" matches @left = [ $op => [ @left, (@right and $op eq $right[0][0]) ? @{ $right[0][1] } : @right ] ]; } # LIST (,) elsif ($token eq ',') { my @right = $self->_recurse_parse($tokens, PARSE_LIST_ELT); # deal with malformed lists ( foo, bar, , baz ) @right = [] unless @right; @right = [ -MISC => [ @right ] ] if @right > 1; if (!@left) { @left = [ -LIST => [ [], @right ] ]; } elsif ($left[0][0] eq '-LIST') { push @{$left[0][1]}, (@{$right[0]} and $right[0][0] eq '-LIST') ? @{$right[0][1]} : @right ; } else { @left = [ -LIST => [ @left, @right ] ]; } } # binary operator keywords elsif ($token =~ $binary_op_re) { my $op = uc $token; my @right = $self->_recurse_parse($tokens, PARSE_RHS); # A between with a simple LITERAL for a 1st RHS argument needs a # rerun of the search to (hopefully) find the proper AND construct if ($op eq 'BETWEEN' and $right[0] eq '-LITERAL') { unshift @$tokens, $right[1][0]; @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR); } push @left, [$op => [ (@left ? pop @left : ''), @right ]]; } # unary op keywords elsif ($token =~ $unary_op_re) { my $op = uc $token; # normalize RNO explicitly $op = 'ROW_NUMBER() OVER' if $op =~ /^$rno_re$/; my @right = $self->_recurse_parse($tokens, PARSE_RHS); push @left, [ $op => \@right ]; } # expression terminator keywords elsif ($token =~ $expr_start_re) { my $op = uc $token; my @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR); push @left, [ $op => \@right ]; } # a '?' elsif ($token =~ $placeholder_re) { push @left, [ -PLACEHOLDER => [ $token ] ]; } # check if the current token is an unknown op-start elsif (@$tokens and ($tokens->[0] eq '(' or $tokens->[0] =~ $placeholder_re ) ) { push @left, [ $token => [ $self->_recurse_parse($tokens, PARSE_RHS) ] ]; } # we're now in "unknown token" land - start eating tokens until # we see something familiar, OR in the case of RHS (binop) stop # after the first token # Also stop processing when we could end up with an unknown func else { my @lits = [ -LITERAL => [$token] ]; unshift @lits, pop @left if @left == 1; unless ( $state == PARSE_RHS ) { while ( @$tokens and $tokens->[0] !~ $all_std_keywords_re and ! (@$tokens > 1 and $tokens->[1] eq '(') ) { push @lits, [ -LITERAL => [ shift @$tokens ] ]; } } @lits = [ -MISC => [ @lits ] ] if @lits > 1; push @left, @lits; } # compress -LITERAL -MISC and -PLACEHOLDER pieces into a single # -MISC container if (@left > 1) { my $i = 0; while ($#left > $i) { if ($left[$i][0] =~ $compressable_node_re and $left[$i+1][0] =~ $compressable_node_re) { splice @left, $i, 2, [ -MISC => [ map { $_->[0] eq '-MISC' ? @{$_->[1]} : $_ } (@left[$i, $i+1]) ]]; } else { $i++; } } } return @left if $state == PARSE_RHS; # deal with post-fix operators if (@$tokens) { # asc/desc if ($tokens->[0] =~ $asc_desc_re) { @left = [ ('-' . uc (shift @$tokens)) => [ @left ] ]; } } } } sub format_keyword { my ($self, $keyword) = @_; if (my $around = $self->colormap->{lc $keyword}) { $keyword = "$around->[0]$keyword$around->[1]"; } return $keyword } my %starters = ( select => 1, update => 1, 'insert into' => 1, 'delete from' => 1, ); sub pad_keyword { my ($self, $keyword, $depth) = @_; my $before = ''; if (defined $self->indentmap->{lc $keyword}) { $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword}); } $before = '' if $depth == 0 and defined $starters{lc $keyword}; return [$before, '']; } sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) } sub _is_key { my ($self, $tree) = @_; $tree = $tree->[0] while ref $tree; defined $tree && defined $self->indentmap->{lc $tree}; } sub fill_in_placeholder { my ($self, $bindargs) = @_; if ($self->fill_in_placeholders) { my $val = shift @{$bindargs} || ''; my $quoted = $val =~ s/^(['"])(.*)\1$/$2/; my ($left, $right) = @{$self->placeholder_surround}; $val =~ s/\\/\\\\/g; $val =~ s/'/\\'/g; $val = qq('$val') if $quoted; return qq($left$val$right) } return '?' } # FIXME - terrible name for a user facing API sub unparse { my ($self, $tree, $bindargs) = @_; $self->_unparse($tree, [@{$bindargs||[]}], 0); } sub _unparse { my ($self, $tree, $bindargs, $depth) = @_; if (not $tree or not @$tree) { return ''; } # FIXME - needs a config switch to disable $self->_parenthesis_unroll($tree); my ($op, $args) = @{$tree}[0,1]; if (! defined $op or (! ref $op and ! defined $args) ) { require Data::Dumper; Carp::confess( sprintf ( "Internal error - malformed branch at depth $depth:\n%s", Data::Dumper::Dumper($tree) ) ); } if (ref $op) { return join (' ', map $self->_unparse($_, $bindargs, $depth), @$tree); } elsif ($op eq '-LITERAL') { # literal has different sig return $args->[0]; } elsif ($op eq '-PLACEHOLDER') { return $self->fill_in_placeholder($bindargs); } elsif ($op eq '-PAREN') { return sprintf ('( %s )', join (' ', map { $self->_unparse($_, $bindargs, $depth + 2) } @{$args} ) . ($self->_is_key($args) ? ( $self->newline||'' ) . $self->indent($depth + 1) : '' ) ); } elsif ($op eq 'AND' or $op eq 'OR' or $op =~ $binary_op_re ) { return join (" $op ", map $self->_unparse($_, $bindargs, $depth), @{$args}); } elsif ($op eq '-LIST' ) { return join (', ', map $self->_unparse($_, $bindargs, $depth), @{$args}); } elsif ($op eq '-MISC' ) { return join (' ', map $self->_unparse($_, $bindargs, $depth), @{$args}); } elsif ($op =~ qr/^-(ASC|DESC)$/ ) { my $dir = $1; return join (' ', (map $self->_unparse($_, $bindargs, $depth), @{$args}), $dir); } else { my ($l, $r) = @{$self->pad_keyword($op, $depth)}; my $rhs = $self->_unparse($args, $bindargs, $depth); return sprintf "$l%s$r", join( ( ref $args eq 'ARRAY' and @{$args} == 1 and $args->[0][0] eq '-PAREN' ) ? '' # mysql-- : ' ' , $self->format_keyword($op), (length $rhs ? $rhs : () ), ); } } # All of these keywords allow their parameters to be specified with or without parenthesis without changing the semantics my @unrollable_ops = ( 'ON', 'WHERE', 'GROUP \s+ BY', 'HAVING', 'ORDER \s+ BY', 'I?LIKE', ); my $unrollable_ops_re = join ' | ', @unrollable_ops; $unrollable_ops_re = qr/$unrollable_ops_re/xi; sub _parenthesis_unroll { my $self = shift; my $ast = shift; return unless (ref $ast and ref $ast->[1]); my $changes; do { my @children; $changes = 0; for my $child (@{$ast->[1]}) { # the current node in this loop is *always* a PAREN if (! ref $child or ! @$child or $child->[0] ne '-PAREN') { push @children, $child; next; } my $parent_op = $ast->[0]; # unroll nested parenthesis while ( $parent_op ne 'IN' and @{$child->[1]} == 1 and $child->[1][0][0] eq '-PAREN') { $child = $child->[1][0]; $changes++; } # set to CHILD in the case of PARENT ( CHILD ) # but NOT in the case of PARENT( CHILD1, CHILD2 ) my $single_child_op = (@{$child->[1]} == 1) ? $child->[1][0][0] : ''; my $child_op_argc = $single_child_op ? scalar @{$child->[1][0][1]} : undef; my $single_grandchild_op = ( $child_op_argc||0 == 1 and ref $child->[1][0][1][0] eq 'ARRAY' ) ? $child->[1][0][1][0][0] : '' ; # if the parent operator explicitly allows it AND the child isn't a subselect # nuke the parenthesis if ($parent_op =~ $unrollable_ops_re and $single_child_op ne 'SELECT') { push @children, @{$child->[1]}; $changes++; } # if the parenthesis are wrapped around an AND/OR matching the parent AND/OR - open the parenthesis up and merge the list elsif ( $single_child_op eq $parent_op and ( $parent_op eq 'AND' or $parent_op eq 'OR') ) { push @children, @{$child->[1][0][1]}; $changes++; } # only *ONE* LITERAL or placeholder element # as an AND/OR/NOT argument elsif ( ( $single_child_op eq '-LITERAL' or $single_child_op eq '-PLACEHOLDER' ) and ( $parent_op eq 'AND' or $parent_op eq 'OR' or $parent_op eq 'NOT' ) ) { push @children, @{$child->[1]}; $changes++; } # an AND/OR expression with only one binop in the parenthesis # with exactly two grandchildren # the only time when we can *not* unroll this is when both # the parent and the child are mathops (in which case we'll # break precedence) or when the child is BETWEEN (special # case) elsif ( ($parent_op eq 'AND' or $parent_op eq 'OR') and $single_child_op =~ $binary_op_re and $single_child_op ne 'BETWEEN' and $child_op_argc == 2 and ! ( $single_child_op =~ $alphanum_cmp_op_re and $parent_op =~ $alphanum_cmp_op_re ) ) { push @children, @{$child->[1]}; $changes++; } # a function binds tighter than a mathop - see if our ancestor is a # mathop, and our content is: # a single non-mathop child with a single PAREN grandchild which # would indicate mathop ( nonmathop ( ... ) ) # or a single non-mathop with a single LITERAL ( nonmathop foo ) # or a single non-mathop with a single PLACEHOLDER ( nonmathop ? ) elsif ( $single_child_op and $parent_op =~ $alphanum_cmp_op_re and $single_child_op !~ $alphanum_cmp_op_re and $child_op_argc == 1 and ( $single_grandchild_op eq '-PAREN' or $single_grandchild_op eq '-LITERAL' or $single_grandchild_op eq '-PLACEHOLDER' ) ) { push @children, @{$child->[1]}; $changes++; } # a construct of ... ( somefunc ( ... ) ) ... can safely lose the outer parens # except for the case of ( NOT ( ... ) ) which has already been handled earlier # and except for the case of RNO, where the double are explicit syntax elsif ( $parent_op ne 'ROW_NUMBER() OVER' and $single_child_op and $single_child_op ne 'NOT' and $child_op_argc == 1 and $single_grandchild_op eq '-PAREN' ) { push @children, @{$child->[1]}; $changes++; } # otherwise no more mucking for this pass else { push @children, $child; } } $ast->[1] = \@children; } while ($changes); } sub _strip_asc_from_order_by { my ($self, $ast) = @_; return $ast if ( ref $ast ne 'ARRAY' or $ast->[0] ne 'ORDER BY' ); my $to_replace; if (@{$ast->[1]} == 1 and $ast->[1][0][0] eq '-ASC') { $to_replace = [ $ast->[1][0] ]; } elsif (@{$ast->[1]} == 1 and $ast->[1][0][0] eq '-LIST') { $to_replace = [ grep { $_->[0] eq '-ASC' } @{$ast->[1][0][1]} ]; } @$_ = @{$_->[1][0]} for @$to_replace; $ast; } sub format { my $self = shift; $self->unparse($self->parse($_[0]), $_[1]) } 1; =pod =head1 NAME SQL::Abstract::Tree - Represent SQL as an AST =head1 SYNOPSIS my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' }); print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2'); # SELECT * # FROM foo # WHERE foo.a > 2 =head1 METHODS =head2 new my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' }); $args = { profile => 'console', # predefined profile to use (default: 'none') fill_in_placeholders => 1, # true for placeholder population placeholder_surround => # The strings that will be wrapped around [GREEN, RESET], # populated placeholders if the above is set indent_string => ' ', # the string used when indenting indent_amount => 2, # how many of above string to use for a single # indent level newline => "\n", # string for newline colormap => { select => [RED, RESET], # a pair of strings defining what to surround # the keyword with for colorization # ... }, indentmap => { select => 0, # A zero means that the keyword will start on # a new line from => 1, # Any other positive integer means that after on => 2, # said newline it will get that many indents # ... }, } Returns a new SQL::Abstract::Tree object. All arguments are optional. =head3 profiles There are four predefined profiles, C, C, C, and C. Typically a user will probably just use C or C, but if something about a profile bothers you, merely use the profile and override the parts that you don't like. =head2 format $sqlat->format('SELECT * FROM bar WHERE x = ?', [1]) Takes C<$sql> and C<\@bindargs>. Returns a formatting string based on the string passed in =head2 parse $sqlat->parse('SELECT * FROM bar WHERE x = ?') Returns a "tree" representing passed in SQL. Please do not depend on the structure of the returned tree. It may be stable at some point, but not yet. =head2 unparse $sqlat->unparse($tree_structure, \@bindargs) Transform "tree" into SQL, applying various transforms on the way. =head2 format_keyword $sqlat->format_keyword('SELECT') Currently this just takes a keyword and puts the C stuff around it. Later on it may do more and allow for coderef based transforms. =head2 pad_keyword my ($before, $after) = @{$sqlat->pad_keyword('SELECT')}; Returns whitespace to be inserted around a keyword. =head2 fill_in_placeholder my $value = $sqlat->fill_in_placeholder(\@bindargs) Removes last arg from passed arrayref and returns it, surrounded with the values in placeholder_surround, and then surrounded with single quotes. =head2 indent Returns as many indent strings as indent amounts times the first argument. =head1 ACCESSORS =head2 colormap See L =head2 fill_in_placeholders See L =head2 indent_amount See L =head2 indent_string See L =head2 indentmap See L =head2 newline See L =head2 placeholder_surround See L SQL-Abstract-1.85/lib/SQL/Abstract/Test.pm0000644000000000000000000002507513074150107020101 0ustar00rootroot00000000000000package SQL::Abstract::Test; # see doc at end of file use strict; use warnings; use base qw(Test::Builder::Module Exporter); use Test::Builder; use Test::Deep (); use SQL::Abstract::Tree; our @EXPORT_OK = qw( is_same_sql_bind is_same_sql is_same_bind eq_sql_bind eq_sql eq_bind dumper diag_where $case_sensitive $sql_differ ); my $sqlat = SQL::Abstract::Tree->new; our $case_sensitive = 0; our $parenthesis_significant = 0; our $order_by_asc_significant = 0; our $sql_differ; # keeps track of differing portion between SQLs our $tb = __PACKAGE__->builder; sub _unpack_arrayrefref { my @args; for (1,2) { my $chunk = shift @_; if (ref $chunk eq 'REF' and ref $$chunk eq 'ARRAY') { my ($sql, @bind) = @$$chunk; push @args, ($sql, \@bind); } else { push @args, $chunk, shift @_; } } # maybe $msg and ... stuff push @args, @_; @args; } sub is_same_sql_bind { my ($sql1, $bind_ref1, $sql2, $bind_ref2, $msg) = &_unpack_arrayrefref; # compare my $same_sql = eq_sql($sql1, $sql2); my $same_bind = eq_bind($bind_ref1, $bind_ref2); # call Test::Builder::ok my $ret = $tb->ok($same_sql && $same_bind, $msg); # add debugging info if (!$same_sql) { _sql_differ_diag($sql1, $sql2); } if (!$same_bind) { _bind_differ_diag($bind_ref1, $bind_ref2); } # pass ok() result further return $ret; } sub is_same_sql { my ($sql1, $sql2, $msg) = @_; # compare my $same_sql = eq_sql($sql1, $sql2); # call Test::Builder::ok my $ret = $tb->ok($same_sql, $msg); # add debugging info if (!$same_sql) { _sql_differ_diag($sql1, $sql2); } # pass ok() result further return $ret; } sub is_same_bind { my ($bind_ref1, $bind_ref2, $msg) = @_; # compare my $same_bind = eq_bind($bind_ref1, $bind_ref2); # call Test::Builder::ok my $ret = $tb->ok($same_bind, $msg); # add debugging info if (!$same_bind) { _bind_differ_diag($bind_ref1, $bind_ref2); } # pass ok() result further return $ret; } sub dumper { # FIXME # if we save the instance, we will end up with $VARx references # no time to figure out how to avoid this (Deepcopy is *not* an option) require Data::Dumper; Data::Dumper->new([])->Terse(1)->Indent(1)->Useqq(1)->Deparse(1)->Quotekeys(0)->Sortkeys(1)->Maxdepth(0) ->Values([@_])->Dump; } sub diag_where{ $tb->diag("Search term:\n" . &dumper); } sub _sql_differ_diag { my $sql1 = shift || ''; my $sql2 = shift || ''; $tb->${\($tb->in_todo ? 'note' : 'diag')} ( "SQL expressions differ\n" ." got: $sql1\n" ."want: $sql2\n" ."\nmismatch around\n$sql_differ\n" ); } sub _bind_differ_diag { my ($bind_ref1, $bind_ref2) = @_; $tb->${\($tb->in_todo ? 'note' : 'diag')} ( "BIND values differ " . dumper({ got => $bind_ref1, want => $bind_ref2 }) ); } sub eq_sql_bind { my ($sql1, $bind_ref1, $sql2, $bind_ref2) = &_unpack_arrayrefref; return eq_sql($sql1, $sql2) && eq_bind($bind_ref1, $bind_ref2); } sub eq_bind { goto &Test::Deep::eq_deeply }; sub eq_sql { my ($sql1, $sql2) = @_; # parse my $tree1 = $sqlat->parse($sql1); my $tree2 = $sqlat->parse($sql2); undef $sql_differ; return 1 if _eq_sql($tree1, $tree2); } sub _eq_sql { my ($left, $right) = @_; # one is defined the other not if ((defined $left) xor (defined $right)) { $sql_differ = sprintf ("[%s] != [%s]\n", map { defined $_ ? $sqlat->unparse($_) : 'N/A' } ($left, $right) ); return 0; } # one is undefined, then so is the other elsif (not defined $left) { return 1; } # both are empty elsif (@$left == 0 and @$right == 0) { return 1; } # one is empty if (@$left == 0 or @$right == 0) { $sql_differ = sprintf ("left: %s\nright: %s\n", map { @$_ ? $sqlat->unparse($_) : 'N/A'} ($left, $right) ); return 0; } # one is a list, the other is an op with a list elsif (ref $left->[0] xor ref $right->[0]) { $sql_differ = sprintf ("[%s] != [%s]\nleft: %s\nright: %s\n", map { ref $_ ? $sqlat->unparse($_) : $_ } ($left->[0], $right->[0], $left, $right) ); return 0; } # both are lists elsif (ref $left->[0]) { for (my $i = 0; $i <= $#$left or $i <= $#$right; $i++ ) { if (not _eq_sql ($left->[$i], $right->[$i]) ) { if (! $sql_differ or $sql_differ !~ /left\:\s .+ right:\s/xs) { $sql_differ ||= ''; $sql_differ .= "\n" unless $sql_differ =~ /\n\z/; $sql_differ .= sprintf ("left: %s\nright: %s\n", map { $sqlat->unparse($_) } ($left, $right) ); } return 0; } } return 1; } # both are ops else { # unroll parenthesis if possible/allowed unless ($parenthesis_significant) { $sqlat->_parenthesis_unroll($_) for $left, $right; } # unroll ASC order by's unless ($order_by_asc_significant) { $sqlat->_strip_asc_from_order_by($_) for $left, $right; } if ($left->[0] ne $right->[0]) { $sql_differ = sprintf "OP [$left->[0]] != [$right->[0]] in\nleft: %s\nright: %s\n", $sqlat->unparse($left), $sqlat->unparse($right) ; return 0; } # literals have a different arg-sig elsif ($left->[0] eq '-LITERAL') { (my $l = " $left->[1][0] " ) =~ s/\s+/ /g; (my $r = " $right->[1][0] ") =~ s/\s+/ /g; my $eq = $case_sensitive ? $l eq $r : uc($l) eq uc($r); $sql_differ = "[$l] != [$r]\n" if not $eq; return $eq; } # if operators are identical, compare operands else { my $eq = _eq_sql($left->[1], $right->[1]); $sql_differ ||= sprintf ("left: %s\nright: %s\n", map { $sqlat->unparse($_) } ($left, $right) ) if not $eq; return $eq; } } } sub parse { $sqlat->parse(@_) } 1; __END__ =head1 NAME SQL::Abstract::Test - Helper function for testing SQL::Abstract =head1 SYNOPSIS use SQL::Abstract; use Test::More; use SQL::Abstract::Test import => [qw/ is_same_sql_bind is_same_sql is_same_bind eq_sql_bind eq_sql eq_bind /]; my ($sql, @bind) = SQL::Abstract->new->select(%args); is_same_sql_bind($given_sql, \@given_bind, $expected_sql, \@expected_bind, $test_msg); is_same_sql($given_sql, $expected_sql, $test_msg); is_same_bind(\@given_bind, \@expected_bind, $test_msg); my $is_same = eq_sql_bind($given_sql, \@given_bind, $expected_sql, \@expected_bind); my $sql_same = eq_sql($given_sql, $expected_sql); my $bind_same = eq_bind(\@given_bind, \@expected_bind); =head1 DESCRIPTION This module is only intended for authors of tests on L and related modules; it exports functions for comparing two SQL statements and their bound values. The SQL comparison is performed on I, ignoring differences in spaces or in levels of parentheses. Therefore the tests will pass as long as the semantics is preserved, even if the surface syntax has changed. B : the semantic equivalence handling is pretty limited. A lot of effort goes into distinguishing significant from non-significant parenthesis, including AND/OR operator associativity. Currently this module does not support commutativity and more intelligent transformations like L, etc. For a good overview of what this test framework is currently capable of refer to C =head1 FUNCTIONS =head2 is_same_sql_bind is_same_sql_bind( $given_sql, \@given_bind, $expected_sql, \@expected_bind, $test_msg ); is_same_sql_bind( \[$given_sql, @given_bind], \[$expected_sql, @expected_bind], $test_msg ); is_same_sql_bind( $dbic_rs->as_query $expected_sql, \@expected_bind, $test_msg ); Compares given and expected pairs of C<($sql, \@bind)> by unpacking C<@_> as shown in the examples above and passing the arguments to L and L. Calls L with the combined result, with C<$test_msg> as message. If the test fails, a detailed diagnostic is printed. =head2 is_same_sql is_same_sql( $given_sql, $expected_sql, $test_msg ); Compares given and expected SQL statements via L, and calls L on the result, with C<$test_msg> as message. If the test fails, a detailed diagnostic is printed. =head2 is_same_bind is_same_bind( \@given_bind, \@expected_bind, $test_msg ); Compares given and expected bind values via L, and calls L on the result, with C<$test_msg> as message. If the test fails, a detailed diagnostic is printed. =head2 eq_sql_bind my $is_same = eq_sql_bind( $given_sql, \@given_bind, $expected_sql, \@expected_bind, ); my $is_same = eq_sql_bind( \[$given_sql, @given_bind], \[$expected_sql, @expected_bind], ); my $is_same = eq_sql_bind( $dbic_rs->as_query $expected_sql, \@expected_bind, ); Unpacks C<@_> depending on the given arguments and calls L and L, returning their combined result. =head2 eq_sql my $is_same = eq_sql($given_sql, $expected_sql); Compares the abstract syntax of two SQL statements. Similar to L, but it just returns a boolean value and does not print diagnostics or talk to L. If the result is false, the global variable L will contain the SQL portion where a difference was encountered; this is useful for printing diagnostics. =head2 eq_bind my $is_same = eq_sql(\@given_bind, \@expected_bind); Compares two lists of bind values, taking into account the fact that some of the values may be arrayrefs (see L). Similar to L, but it just returns a boolean value and does not print diagnostics or talk to L. =head1 GLOBAL VARIABLES =head2 $case_sensitive If true, SQL comparisons will be case-sensitive. Default is false; =head2 $parenthesis_significant If true, SQL comparison will preserve and report difference in nested parenthesis. Useful while testing C vs C. Defaults to false; =head2 $order_by_asc_significant If true SQL comparison will consider C and C to be different. Default is false; =head2 $sql_differ When L returns false, the global variable C<$sql_differ> contains the SQL portion where a difference was encountered. =head1 SEE ALSO L, L, L. =head1 AUTHORS Laurent Dami Norbert Buchmuller Peter Rabbitson =head1 COPYRIGHT AND LICENSE Copyright 2008 by Laurent Dami. This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. SQL-Abstract-1.85/lib/SQL/Abstract.pm0000644000000000000000000027625613233057011017170 0ustar00rootroot00000000000000package SQL::Abstract; # see doc at end of file use strict; use warnings; use Carp (); use List::Util (); use Scalar::Util (); use Exporter 'import'; our @EXPORT_OK = qw(is_plain_value is_literal_value); BEGIN { if ($] < 5.009_005) { require MRO::Compat; } else { require mro; } *SQL::Abstract::_ENV_::DETECT_AUTOGENERATED_STRINGIFICATION = $ENV{SQLA_ISVALUE_IGNORE_AUTOGENERATED_STRINGIFICATION} ? sub () { 0 } : sub () { 1 } ; } #====================================================================== # GLOBALS #====================================================================== our $VERSION = '1.85'; # This would confuse some packagers $VERSION = eval $VERSION if $VERSION =~ /_/; # numify for warning-free dev releases our $AUTOLOAD; # special operators (-in, -between). May be extended/overridden by user. # See section WHERE: BUILTIN SPECIAL OPERATORS below for implementation my @BUILTIN_SPECIAL_OPS = ( {regex => qr/^ (?: not \s )? between $/ix, handler => '_where_field_BETWEEN'}, {regex => qr/^ (?: not \s )? in $/ix, handler => '_where_field_IN'}, {regex => qr/^ ident $/ix, handler => '_where_op_IDENT'}, {regex => qr/^ value $/ix, handler => '_where_op_VALUE'}, {regex => qr/^ is (?: \s+ not )? $/ix, handler => '_where_field_IS'}, ); # unaryish operators - key maps to handler my @BUILTIN_UNARY_OPS = ( # the digits are backcompat stuff { regex => qr/^ and (?: [_\s]? \d+ )? $/xi, handler => '_where_op_ANDOR' }, { regex => qr/^ or (?: [_\s]? \d+ )? $/xi, handler => '_where_op_ANDOR' }, { regex => qr/^ nest (?: [_\s]? \d+ )? $/xi, handler => '_where_op_NEST' }, { regex => qr/^ (?: not \s )? bool $/xi, handler => '_where_op_BOOL' }, { regex => qr/^ ident $/xi, handler => '_where_op_IDENT' }, { regex => qr/^ value $/xi, handler => '_where_op_VALUE' }, ); #====================================================================== # DEBUGGING AND ERROR REPORTING #====================================================================== sub _debug { return unless $_[0]->{debug}; shift; # a little faster my $func = (caller(1))[3]; warn "[$func] ", @_, "\n"; } sub belch (@) { my($func) = (caller(1))[3]; Carp::carp "[$func] Warning: ", @_; } sub puke (@) { my($func) = (caller(1))[3]; Carp::croak "[$func] Fatal: ", @_; } sub is_literal_value ($) { ref $_[0] eq 'SCALAR' ? [ ${$_[0]} ] : ( ref $_[0] eq 'REF' and ref ${$_[0]} eq 'ARRAY' ) ? [ @${ $_[0] } ] : undef; } # FIXME XSify - this can be done so much more efficiently sub is_plain_value ($) { no strict 'refs'; ! length ref $_[0] ? \($_[0]) : ( ref $_[0] eq 'HASH' and keys %{$_[0]} == 1 and exists $_[0]->{-value} ) ? \($_[0]->{-value}) : ( # reuse @_ for even moar speedz defined ( $_[1] = Scalar::Util::blessed $_[0] ) and # deliberately not using Devel::OverloadInfo - the checks we are # intersted in are much more limited than the fullblown thing, and # this is a very hot piece of code ( # simply using ->can('(""') can leave behind stub methods that # break actually using the overload later (see L and the source of overload::mycan()) # # either has stringification which DBI SHOULD prefer out of the box grep { *{ (qq[${_}::(""]) }{CODE} } @{ $_[2] = mro::get_linear_isa( $_[1] ) } or # has nummification or boolification, AND fallback is *not* disabled ( SQL::Abstract::_ENV_::DETECT_AUTOGENERATED_STRINGIFICATION and ( grep { *{"${_}::(0+"}{CODE} } @{$_[2]} or grep { *{"${_}::(bool"}{CODE} } @{$_[2]} ) and ( # no fallback specified at all ! ( ($_[3]) = grep { *{"${_}::()"}{CODE} } @{$_[2]} ) or # fallback explicitly undef ! defined ${"$_[3]::()"} or # explicitly true !! ${"$_[3]::()"} ) ) ) ) ? \($_[0]) : undef; } #====================================================================== # NEW #====================================================================== sub new { my $self = shift; my $class = ref($self) || $self; my %opt = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_; # choose our case by keeping an option around delete $opt{case} if $opt{case} && $opt{case} ne 'lower'; # default logic for interpreting arrayrefs $opt{logic} = $opt{logic} ? uc $opt{logic} : 'OR'; # how to return bind vars $opt{bindtype} ||= 'normal'; # default comparison is "=", but can be overridden $opt{cmp} ||= '='; # try to recognize which are the 'equality' and 'inequality' ops # (temporary quickfix (in 2007), should go through a more seasoned API) $opt{equality_op} = qr/^( \Q$opt{cmp}\E | \= )$/ix; $opt{inequality_op} = qr/^( != | <> )$/ix; $opt{like_op} = qr/^ (is\s+)? r?like $/xi; $opt{not_like_op} = qr/^ (is\s+)? not \s+ r?like $/xi; # SQL booleans $opt{sqltrue} ||= '1=1'; $opt{sqlfalse} ||= '0=1'; # special operators $opt{special_ops} ||= []; # regexes are applied in order, thus push after user-defines push @{$opt{special_ops}}, @BUILTIN_SPECIAL_OPS; # unary operators $opt{unary_ops} ||= []; push @{$opt{unary_ops}}, @BUILTIN_UNARY_OPS; # rudimentary sanity-check for user supplied bits treated as functions/operators # If a purported function matches this regular expression, an exception is thrown. # Literal SQL is *NOT* subject to this check, only functions (and column names # when quoting is not in effect) # FIXME # need to guard against ()'s in column names too, but this will break tons of # hacks... ideas anyone? $opt{injection_guard} ||= qr/ \; | ^ \s* go \s /xmi; return bless \%opt, $class; } sub _assert_pass_injection_guard { if ($_[1] =~ $_[0]->{injection_guard}) { my $class = ref $_[0]; puke "Possible SQL injection attempt '$_[1]'. If this is indeed a part of the " . "desired SQL use literal SQL ( \'...' or \[ '...' ] ) or supply your own " . "{injection_guard} attribute to ${class}->new()" } } #====================================================================== # INSERT methods #====================================================================== sub insert { my $self = shift; my $table = $self->_table(shift); my $data = shift || return; my $options = shift; my $method = $self->_METHOD_FOR_refkind("_insert", $data); my ($sql, @bind) = $self->$method($data); $sql = join " ", $self->_sqlcase('insert into'), $table, $sql; if ($options->{returning}) { my ($s, @b) = $self->_insert_returning($options); $sql .= $s; push @bind, @b; } return wantarray ? ($sql, @bind) : $sql; } # So that subclasses can override INSERT ... RETURNING separately from # UPDATE and DELETE (e.g. DBIx::Class::SQLMaker::Oracle does this) sub _insert_returning { shift->_returning(@_) } sub _returning { my ($self, $options) = @_; my $f = $options->{returning}; my $fieldlist = $self->_SWITCH_refkind($f, { ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$f;}, SCALAR => sub {$self->_quote($f)}, SCALARREF => sub {$$f}, }); return $self->_sqlcase(' returning ') . $fieldlist; } sub _insert_HASHREF { # explicit list of fields and then values my ($self, $data) = @_; my @fields = sort keys %$data; my ($sql, @bind) = $self->_insert_values($data); # assemble SQL $_ = $self->_quote($_) foreach @fields; $sql = "( ".join(", ", @fields).") ".$sql; return ($sql, @bind); } sub _insert_ARRAYREF { # just generate values(?,?) part (no list of fields) my ($self, $data) = @_; # no names (arrayref) so can't generate bindtype $self->{bindtype} ne 'columns' or belch "can't do 'columns' bindtype when called with arrayref"; my (@values, @all_bind); foreach my $value (@$data) { my ($values, @bind) = $self->_insert_value(undef, $value); push @values, $values; push @all_bind, @bind; } my $sql = $self->_sqlcase('values')." ( ".join(", ", @values)." )"; return ($sql, @all_bind); } sub _insert_ARRAYREFREF { # literal SQL with bind my ($self, $data) = @_; my ($sql, @bind) = @${$data}; $self->_assert_bindval_matches_bindtype(@bind); return ($sql, @bind); } sub _insert_SCALARREF { # literal SQL without bind my ($self, $data) = @_; return ($$data); } sub _insert_values { my ($self, $data) = @_; my (@values, @all_bind); foreach my $column (sort keys %$data) { my ($values, @bind) = $self->_insert_value($column, $data->{$column}); push @values, $values; push @all_bind, @bind; } my $sql = $self->_sqlcase('values')." ( ".join(", ", @values)." )"; return ($sql, @all_bind); } sub _insert_value { my ($self, $column, $v) = @_; my (@values, @all_bind); $self->_SWITCH_refkind($v, { ARRAYREF => sub { if ($self->{array_datatypes}) { # if array datatype are activated push @values, '?'; push @all_bind, $self->_bindtype($column, $v); } else { # else literal SQL with bind my ($sql, @bind) = @$v; $self->_assert_bindval_matches_bindtype(@bind); push @values, $sql; push @all_bind, @bind; } }, ARRAYREFREF => sub { # literal SQL with bind my ($sql, @bind) = @${$v}; $self->_assert_bindval_matches_bindtype(@bind); push @values, $sql; push @all_bind, @bind; }, # THINK : anything useful to do with a HASHREF ? HASHREF => sub { # (nothing, but old SQLA passed it through) #TODO in SQLA >= 2.0 it will die instead belch "HASH ref as bind value in insert is not supported"; push @values, '?'; push @all_bind, $self->_bindtype($column, $v); }, SCALARREF => sub { # literal SQL without bind push @values, $$v; }, SCALAR_or_UNDEF => sub { push @values, '?'; push @all_bind, $self->_bindtype($column, $v); }, }); my $sql = join(", ", @values); return ($sql, @all_bind); } #====================================================================== # UPDATE methods #====================================================================== sub update { my $self = shift; my $table = $self->_table(shift); my $data = shift || return; my $where = shift; my $options = shift; # first build the 'SET' part of the sql statement puke "Unsupported data type specified to \$sql->update" unless ref $data eq 'HASH'; my ($sql, @all_bind) = $self->_update_set_values($data); $sql = $self->_sqlcase('update ') . $table . $self->_sqlcase(' set ') . $sql; if ($where) { my($where_sql, @where_bind) = $self->where($where); $sql .= $where_sql; push @all_bind, @where_bind; } if ($options->{returning}) { my ($returning_sql, @returning_bind) = $self->_update_returning($options); $sql .= $returning_sql; push @all_bind, @returning_bind; } return wantarray ? ($sql, @all_bind) : $sql; } sub _update_set_values { my ($self, $data) = @_; my (@set, @all_bind); for my $k (sort keys %$data) { my $v = $data->{$k}; my $r = ref $v; my $label = $self->_quote($k); $self->_SWITCH_refkind($v, { ARRAYREF => sub { if ($self->{array_datatypes}) { # array datatype push @set, "$label = ?"; push @all_bind, $self->_bindtype($k, $v); } else { # literal SQL with bind my ($sql, @bind) = @$v; $self->_assert_bindval_matches_bindtype(@bind); push @set, "$label = $sql"; push @all_bind, @bind; } }, ARRAYREFREF => sub { # literal SQL with bind my ($sql, @bind) = @${$v}; $self->_assert_bindval_matches_bindtype(@bind); push @set, "$label = $sql"; push @all_bind, @bind; }, SCALARREF => sub { # literal SQL without bind push @set, "$label = $$v"; }, HASHREF => sub { my ($op, $arg, @rest) = %$v; puke 'Operator calls in update must be in the form { -op => $arg }' if (@rest or not $op =~ /^\-(.+)/); local $self->{_nested_func_lhs} = $k; my ($sql, @bind) = $self->_where_unary_op($1, $arg); push @set, "$label = $sql"; push @all_bind, @bind; }, SCALAR_or_UNDEF => sub { push @set, "$label = ?"; push @all_bind, $self->_bindtype($k, $v); }, }); } # generate sql my $sql = join ', ', @set; return ($sql, @all_bind); } # So that subclasses can override UPDATE ... RETURNING separately from # INSERT and DELETE sub _update_returning { shift->_returning(@_) } #====================================================================== # SELECT #====================================================================== sub select { my $self = shift; my $table = $self->_table(shift); my $fields = shift || '*'; my $where = shift; my $order = shift; my($where_sql, @bind) = $self->where($where, $order); my $f = (ref $fields eq 'ARRAY') ? join ', ', map { $self->_quote($_) } @$fields : $fields; my $sql = join(' ', $self->_sqlcase('select'), $f, $self->_sqlcase('from'), $table) . $where_sql; return wantarray ? ($sql, @bind) : $sql; } #====================================================================== # DELETE #====================================================================== sub delete { my $self = shift; my $table = $self->_table(shift); my $where = shift; my $options = shift; my($where_sql, @bind) = $self->where($where); my $sql = $self->_sqlcase('delete from ') . $table . $where_sql; if ($options->{returning}) { my ($returning_sql, @returning_bind) = $self->_delete_returning($options); $sql .= $returning_sql; push @bind, @returning_bind; } return wantarray ? ($sql, @bind) : $sql; } # So that subclasses can override DELETE ... RETURNING separately from # INSERT and UPDATE sub _delete_returning { shift->_returning(@_) } #====================================================================== # WHERE: entry point #====================================================================== # Finally, a separate routine just to handle WHERE clauses sub where { my ($self, $where, $order) = @_; # where ? my ($sql, @bind) = $self->_recurse_where($where); $sql = $sql ? $self->_sqlcase(' where ') . "( $sql )" : ''; # order by? if ($order) { my ($order_sql, @order_bind) = $self->_order_by($order); $sql .= $order_sql; push @bind, @order_bind; } return wantarray ? ($sql, @bind) : $sql; } sub _recurse_where { my ($self, $where, $logic) = @_; # dispatch on appropriate method according to refkind of $where my $method = $self->_METHOD_FOR_refkind("_where", $where); my ($sql, @bind) = $self->$method($where, $logic); # DBIx::Class used to call _recurse_where in scalar context # something else might too... if (wantarray) { return ($sql, @bind); } else { belch "Calling _recurse_where in scalar context is deprecated and will go away before 2.0"; return $sql; } } #====================================================================== # WHERE: top-level ARRAYREF #====================================================================== sub _where_ARRAYREF { my ($self, $where, $logic) = @_; $logic = uc($logic || $self->{logic}); $logic eq 'AND' or $logic eq 'OR' or puke "unknown logic: $logic"; my @clauses = @$where; my (@sql_clauses, @all_bind); # need to use while() so can shift() for pairs while (@clauses) { my $el = shift @clauses; $el = undef if (defined $el and ! length $el); # switch according to kind of $el and get corresponding ($sql, @bind) my ($sql, @bind) = $self->_SWITCH_refkind($el, { # skip empty elements, otherwise get invalid trailing AND stuff ARRAYREF => sub {$self->_recurse_where($el) if @$el}, ARRAYREFREF => sub { my ($s, @b) = @$$el; $self->_assert_bindval_matches_bindtype(@b); ($s, @b); }, HASHREF => sub {$self->_recurse_where($el, 'and') if %$el}, SCALARREF => sub { ($$el); }, SCALAR => sub { # top-level arrayref with scalars, recurse in pairs $self->_recurse_where({$el => shift(@clauses)}) }, UNDEF => sub {puke "Supplying an empty left hand side argument is not supported in array-pairs" }, }); if ($sql) { push @sql_clauses, $sql; push @all_bind, @bind; } } return $self->_join_sql_clauses($logic, \@sql_clauses, \@all_bind); } #====================================================================== # WHERE: top-level ARRAYREFREF #====================================================================== sub _where_ARRAYREFREF { my ($self, $where) = @_; my ($sql, @bind) = @$$where; $self->_assert_bindval_matches_bindtype(@bind); return ($sql, @bind); } #====================================================================== # WHERE: top-level HASHREF #====================================================================== sub _where_HASHREF { my ($self, $where) = @_; my (@sql_clauses, @all_bind); for my $k (sort keys %$where) { my $v = $where->{$k}; # ($k => $v) is either a special unary op or a regular hashpair my ($sql, @bind) = do { if ($k =~ /^-./) { # put the operator in canonical form my $op = $k; $op = substr $op, 1; # remove initial dash $op =~ s/^\s+|\s+$//g;# remove leading/trailing space $op =~ s/\s+/ /g; # compress whitespace # so that -not_foo works correctly $op =~ s/^not_/NOT /i; $self->_debug("Unary OP(-$op) within hashref, recursing..."); my ($s, @b) = $self->_where_unary_op($op, $v); # top level vs nested # we assume that handled unary ops will take care of their ()s $s = "($s)" unless ( List::Util::first {$op =~ $_->{regex}} @{$self->{unary_ops}} or ( defined $self->{_nested_func_lhs} and $self->{_nested_func_lhs} eq $k ) ); ($s, @b); } else { if (! length $k) { if (is_literal_value ($v) ) { belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead'; } else { puke "Supplying an empty left hand side argument is not supported in hash-pairs"; } } my $method = $self->_METHOD_FOR_refkind("_where_hashpair", $v); $self->$method($k, $v); } }; push @sql_clauses, $sql; push @all_bind, @bind; } return $self->_join_sql_clauses('and', \@sql_clauses, \@all_bind); } sub _where_unary_op { my ($self, $op, $rhs) = @_; # top level special ops are illegal in general # this includes the -ident/-value ops (dual purpose unary and special) puke "Illegal use of top-level '-$op'" if ! defined $self->{_nested_func_lhs} and List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}}; if (my $op_entry = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) { my $handler = $op_entry->{handler}; if (not ref $handler) { if ($op =~ s/ [_\s]? \d+ $//x ) { belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. ' . "You probably wanted ...-and => [ -$op => COND1, -$op => COND2 ... ]"; } return $self->$handler($op, $rhs); } elsif (ref $handler eq 'CODE') { return $handler->($self, $op, $rhs); } else { puke "Illegal handler for operator $op - expecting a method name or a coderef"; } } $self->_debug("Generic unary OP: $op - recursing as function"); $self->_assert_pass_injection_guard($op); my ($sql, @bind) = $self->_SWITCH_refkind($rhs, { SCALAR => sub { puke "Illegal use of top-level '-$op'" unless defined $self->{_nested_func_lhs}; return ( $self->_convert('?'), $self->_bindtype($self->{_nested_func_lhs}, $rhs) ); }, FALLBACK => sub { $self->_recurse_where($rhs) }, }); $sql = sprintf('%s %s', $self->_sqlcase($op), $sql, ); return ($sql, @bind); } sub _where_op_ANDOR { my ($self, $op, $v) = @_; $self->_SWITCH_refkind($v, { ARRAYREF => sub { return $self->_where_ARRAYREF($v, $op); }, HASHREF => sub { return ($op =~ /^or/i) ? $self->_where_ARRAYREF([ map { $_ => $v->{$_} } (sort keys %$v) ], $op) : $self->_where_HASHREF($v); }, SCALARREF => sub { puke "-$op => \\\$scalar makes little sense, use " . ($op =~ /^or/i ? '[ \$scalar, \%rest_of_conditions ] instead' : '-and => [ \$scalar, \%rest_of_conditions ] instead' ); }, ARRAYREFREF => sub { puke "-$op => \\[...] makes little sense, use " . ($op =~ /^or/i ? '[ \[...], \%rest_of_conditions ] instead' : '-and => [ \[...], \%rest_of_conditions ] instead' ); }, SCALAR => sub { # permissively interpreted as SQL puke "-$op => \$value makes little sense, use -bool => \$value instead"; }, UNDEF => sub { puke "-$op => undef not supported"; }, }); } sub _where_op_NEST { my ($self, $op, $v) = @_; $self->_SWITCH_refkind($v, { SCALAR => sub { # permissively interpreted as SQL belch "literal SQL should be -nest => \\'scalar' " . "instead of -nest => 'scalar' "; return ($v); }, UNDEF => sub { puke "-$op => undef not supported"; }, FALLBACK => sub { $self->_recurse_where($v); }, }); } sub _where_op_BOOL { my ($self, $op, $v) = @_; my ($s, @b) = $self->_SWITCH_refkind($v, { SCALAR => sub { # interpreted as SQL column $self->_convert($self->_quote($v)); }, UNDEF => sub { puke "-$op => undef not supported"; }, FALLBACK => sub { $self->_recurse_where($v); }, }); $s = "(NOT $s)" if $op =~ /^not/i; ($s, @b); } sub _where_op_IDENT { my $self = shift; my ($op, $rhs) = splice @_, -2; if (! defined $rhs or length ref $rhs) { puke "-$op requires a single plain scalar argument (a quotable identifier)"; } # in case we are called as a top level special op (no '=') my $lhs = shift; $_ = $self->_convert($self->_quote($_)) for ($lhs, $rhs); return $lhs ? "$lhs = $rhs" : $rhs ; } sub _where_op_VALUE { my $self = shift; my ($op, $rhs) = splice @_, -2; # in case we are called as a top level special op (no '=') my $lhs = shift; # special-case NULL if (! defined $rhs) { return defined $lhs ? $self->_convert($self->_quote($lhs)) . ' IS NULL' : undef ; } my @bind = $self->_bindtype( (defined $lhs ? $lhs : $self->{_nested_func_lhs}), $rhs, ) ; return $lhs ? ( $self->_convert($self->_quote($lhs)) . ' = ' . $self->_convert('?'), @bind ) : ( $self->_convert('?'), @bind, ) ; } sub _where_hashpair_ARRAYREF { my ($self, $k, $v) = @_; if (@$v) { my @v = @$v; # need copy because of shift below $self->_debug("ARRAY($k) means distribute over elements"); # put apart first element if it is an operator (-and, -or) my $op = ( (defined $v[0] && $v[0] =~ /^ - (?: AND|OR ) $/ix) ? shift @v : '' ); my @distributed = map { {$k => $_} } @v; if ($op) { $self->_debug("OP($op) reinjected into the distributed array"); unshift @distributed, $op; } my $logic = $op ? substr($op, 1) : ''; return $self->_recurse_where(\@distributed, $logic); } else { $self->_debug("empty ARRAY($k) means 0=1"); return ($self->{sqlfalse}); } } sub _where_hashpair_HASHREF { my ($self, $k, $v, $logic) = @_; $logic ||= 'and'; local $self->{_nested_func_lhs} = defined $self->{_nested_func_lhs} ? $self->{_nested_func_lhs} : $k ; my ($all_sql, @all_bind); for my $orig_op (sort keys %$v) { my $val = $v->{$orig_op}; # put the operator in canonical form my $op = $orig_op; # FIXME - we need to phase out dash-less ops $op =~ s/^-//; # remove possible initial dash $op =~ s/^\s+|\s+$//g;# remove leading/trailing space $op =~ s/\s+/ /g; # compress whitespace $self->_assert_pass_injection_guard($op); # fixup is_not $op =~ s/^is_not/IS NOT/i; # so that -not_foo works correctly $op =~ s/^not_/NOT /i; # another retarded special case: foo => { $op => { -value => undef } } if (ref $val eq 'HASH' and keys %$val == 1 and exists $val->{-value} and ! defined $val->{-value} ) { $val = undef; } my ($sql, @bind); # CASE: col-value logic modifiers if ($orig_op =~ /^ \- (and|or) $/xi) { ($sql, @bind) = $self->_where_hashpair_HASHREF($k, $val, $1); } # CASE: special operators like -in or -between elsif (my $special_op = List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}}) { my $handler = $special_op->{handler}; if (! $handler) { puke "No handler supplied for special operator $orig_op"; } elsif (not ref $handler) { ($sql, @bind) = $self->$handler($k, $op, $val); } elsif (ref $handler eq 'CODE') { ($sql, @bind) = $handler->($self, $k, $op, $val); } else { puke "Illegal handler for special operator $orig_op - expecting a method name or a coderef"; } } else { $self->_SWITCH_refkind($val, { ARRAYREF => sub { # CASE: col => {op => \@vals} ($sql, @bind) = $self->_where_field_op_ARRAYREF($k, $op, $val); }, ARRAYREFREF => sub { # CASE: col => {op => \[$sql, @bind]} (literal SQL with bind) my ($sub_sql, @sub_bind) = @$$val; $self->_assert_bindval_matches_bindtype(@sub_bind); $sql = join ' ', $self->_convert($self->_quote($k)), $self->_sqlcase($op), $sub_sql; @bind = @sub_bind; }, UNDEF => sub { # CASE: col => {op => undef} : sql "IS (NOT)? NULL" my $is = $op =~ /^not$/i ? 'is not' # legacy : $op =~ $self->{equality_op} ? 'is' : $op =~ $self->{like_op} ? belch("Supplying an undefined argument to '@{[ uc $op]}' is deprecated") && 'is' : $op =~ $self->{inequality_op} ? 'is not' : $op =~ $self->{not_like_op} ? belch("Supplying an undefined argument to '@{[ uc $op]}' is deprecated") && 'is not' : puke "unexpected operator '$orig_op' with undef operand"; $sql = $self->_quote($k) . $self->_sqlcase(" $is null"); }, FALLBACK => sub { # CASE: col => {op/func => $stuff} ($sql, @bind) = $self->_where_unary_op($op, $val); $sql = join(' ', $self->_convert($self->_quote($k)), $self->{_nested_func_lhs} eq $k ? $sql : "($sql)", # top level vs nested ); }, }); } ($all_sql) = (defined $all_sql and $all_sql) ? $self->_join_sql_clauses($logic, [$all_sql, $sql], []) : $sql; push @all_bind, @bind; } return ($all_sql, @all_bind); } sub _where_field_IS { my ($self, $k, $op, $v) = @_; my ($s) = $self->_SWITCH_refkind($v, { UNDEF => sub { join ' ', $self->_convert($self->_quote($k)), map { $self->_sqlcase($_)} ($op, 'null') }, FALLBACK => sub { puke "$op can only take undef as argument"; }, }); $s; } sub _where_field_op_ARRAYREF { my ($self, $k, $op, $vals) = @_; my @vals = @$vals; #always work on a copy if (@vals) { $self->_debug(sprintf '%s means multiple elements: [ %s ]', $vals, join(', ', map { defined $_ ? "'$_'" : 'NULL' } @vals ), ); # see if the first element is an -and/-or op my $logic; if (defined $vals[0] && $vals[0] =~ /^ - (AND|OR) $/ix) { $logic = uc $1; shift @vals; } # a long standing API wart - an attempt to change this behavior during # the 1.50 series failed *spectacularly*. Warn instead and leave the # behavior as is if ( @vals > 1 and (!$logic or $logic eq 'OR') and ($op =~ $self->{inequality_op} or $op =~ $self->{not_like_op}) ) { my $o = uc($op); belch "A multi-element arrayref as an argument to the inequality op '$o' " . 'is technically equivalent to an always-true 1=1 (you probably wanted ' . "to say ...{ \$inequality_op => [ -and => \@values ] }... instead)" ; } # distribute $op over each remaining member of @vals, append logic if exists return $self->_recurse_where([map { {$k => {$op, $_}} } @vals], $logic); } else { # try to DWIM on equality operators return $op =~ $self->{equality_op} ? $self->{sqlfalse} : $op =~ $self->{like_op} ? belch("Supplying an empty arrayref to '@{[ uc $op]}' is deprecated") && $self->{sqlfalse} : $op =~ $self->{inequality_op} ? $self->{sqltrue} : $op =~ $self->{not_like_op} ? belch("Supplying an empty arrayref to '@{[ uc $op]}' is deprecated") && $self->{sqltrue} : puke "operator '$op' applied on an empty array (field '$k')"; } } sub _where_hashpair_SCALARREF { my ($self, $k, $v) = @_; $self->_debug("SCALAR($k) means literal SQL: $$v"); my $sql = $self->_quote($k) . " " . $$v; return ($sql); } # literal SQL with bind sub _where_hashpair_ARRAYREFREF { my ($self, $k, $v) = @_; $self->_debug("REF($k) means literal SQL: @${$v}"); my ($sql, @bind) = @$$v; $self->_assert_bindval_matches_bindtype(@bind); $sql = $self->_quote($k) . " " . $sql; return ($sql, @bind ); } # literal SQL without bind sub _where_hashpair_SCALAR { my ($self, $k, $v) = @_; $self->_debug("NOREF($k) means simple key=val: $k $self->{cmp} $v"); my $sql = join ' ', $self->_convert($self->_quote($k)), $self->_sqlcase($self->{cmp}), $self->_convert('?'); my @bind = $self->_bindtype($k, $v); return ($sql, @bind); } sub _where_hashpair_UNDEF { my ($self, $k, $v) = @_; $self->_debug("UNDEF($k) means IS NULL"); my $sql = $self->_quote($k) . $self->_sqlcase(' is null'); return ($sql); } #====================================================================== # WHERE: TOP-LEVEL OTHERS (SCALARREF, SCALAR, UNDEF) #====================================================================== sub _where_SCALARREF { my ($self, $where) = @_; # literal sql $self->_debug("SCALAR(*top) means literal SQL: $$where"); return ($$where); } sub _where_SCALAR { my ($self, $where) = @_; # literal sql $self->_debug("NOREF(*top) means literal SQL: $where"); return ($where); } sub _where_UNDEF { my ($self) = @_; return (); } #====================================================================== # WHERE: BUILTIN SPECIAL OPERATORS (-in, -between) #====================================================================== sub _where_field_BETWEEN { my ($self, $k, $op, $vals) = @_; my ($label, $and, $placeholder); $label = $self->_convert($self->_quote($k)); $and = ' ' . $self->_sqlcase('and') . ' '; $placeholder = $self->_convert('?'); $op = $self->_sqlcase($op); my $invalid_args = "Operator '$op' requires either an arrayref with two defined values or expressions, or a single literal scalarref/arrayref-ref"; my ($clause, @bind) = $self->_SWITCH_refkind($vals, { ARRAYREFREF => sub { my ($s, @b) = @$$vals; $self->_assert_bindval_matches_bindtype(@b); ($s, @b); }, SCALARREF => sub { return $$vals; }, ARRAYREF => sub { puke $invalid_args if @$vals != 2; my (@all_sql, @all_bind); foreach my $val (@$vals) { my ($sql, @bind) = $self->_SWITCH_refkind($val, { SCALAR => sub { return ($placeholder, $self->_bindtype($k, $val) ); }, SCALARREF => sub { return $$val; }, ARRAYREFREF => sub { my ($sql, @bind) = @$$val; $self->_assert_bindval_matches_bindtype(@bind); return ($sql, @bind); }, HASHREF => sub { my ($func, $arg, @rest) = %$val; puke "Only simple { -func => arg } functions accepted as sub-arguments to BETWEEN" if (@rest or $func !~ /^ \- (.+)/x); $self->_where_unary_op($1 => $arg); }, FALLBACK => sub { puke $invalid_args, }, }); push @all_sql, $sql; push @all_bind, @bind; } return ( (join $and, @all_sql), @all_bind ); }, FALLBACK => sub { puke $invalid_args, }, }); my $sql = "( $label $op $clause )"; return ($sql, @bind) } sub _where_field_IN { my ($self, $k, $op, $vals) = @_; # backwards compatibility : if scalar, force into an arrayref $vals = [$vals] if defined $vals && ! ref $vals; my ($label) = $self->_convert($self->_quote($k)); my ($placeholder) = $self->_convert('?'); $op = $self->_sqlcase($op); my ($sql, @bind) = $self->_SWITCH_refkind($vals, { ARRAYREF => sub { # list of choices if (@$vals) { # nonempty list my (@all_sql, @all_bind); for my $val (@$vals) { my ($sql, @bind) = $self->_SWITCH_refkind($val, { SCALAR => sub { return ($placeholder, $val); }, SCALARREF => sub { return $$val; }, ARRAYREFREF => sub { my ($sql, @bind) = @$$val; $self->_assert_bindval_matches_bindtype(@bind); return ($sql, @bind); }, HASHREF => sub { my ($func, $arg, @rest) = %$val; puke "Only simple { -func => arg } functions accepted as sub-arguments to IN" if (@rest or $func !~ /^ \- (.+)/x); $self->_where_unary_op($1 => $arg); }, UNDEF => sub { puke( 'SQL::Abstract before v1.75 used to generate incorrect SQL when the ' . "-$op operator was given an undef-containing list: !!!AUDIT YOUR CODE " . 'AND DATA!!! (the upcoming Data::Query-based version of SQL::Abstract ' . 'will emit the logically correct SQL instead of raising this exception)' ); }, }); push @all_sql, $sql; push @all_bind, @bind; } return ( sprintf('%s %s ( %s )', $label, $op, join(', ', @all_sql) ), $self->_bindtype($k, @all_bind), ); } else { # empty list : some databases won't understand "IN ()", so DWIM my $sql = ($op =~ /\bnot\b/i) ? $self->{sqltrue} : $self->{sqlfalse}; return ($sql); } }, SCALARREF => sub { # literal SQL my $sql = $self->_open_outer_paren($$vals); return ("$label $op ( $sql )"); }, ARRAYREFREF => sub { # literal SQL with bind my ($sql, @bind) = @$$vals; $self->_assert_bindval_matches_bindtype(@bind); $sql = $self->_open_outer_paren($sql); return ("$label $op ( $sql )", @bind); }, UNDEF => sub { puke "Argument passed to the '$op' operator can not be undefined"; }, FALLBACK => sub { puke "special op $op requires an arrayref (or scalarref/arrayref-ref)"; }, }); return ($sql, @bind); } # Some databases (SQLite) treat col IN (1, 2) different from # col IN ( (1, 2) ). Use this to strip all outer parens while # adding them back in the corresponding method sub _open_outer_paren { my ($self, $sql) = @_; while (my ($inner) = $sql =~ /^ \s* \( (.*) \) \s* $/xs) { # there are closing parens inside, need the heavy duty machinery # to reevaluate the extraction starting from $sql (full reevaluation) if ($inner =~ /\)/) { require Text::Balanced; my (undef, $remainder) = do { # idiotic design - writes to $@ but *DOES NOT* throw exceptions local $@; Text::Balanced::extract_bracketed($sql, '()', qr/\s*/); }; # the entire expression needs to be a balanced bracketed thing # (after an extract no remainder sans trailing space) last if defined $remainder and $remainder =~ /\S/; } $sql = $inner; } $sql; } #====================================================================== # ORDER BY #====================================================================== sub _order_by { my ($self, $arg) = @_; my (@sql, @bind); for my $c ($self->_order_by_chunks($arg) ) { $self->_SWITCH_refkind($c, { SCALAR => sub { push @sql, $c }, ARRAYREF => sub { push @sql, shift @$c; push @bind, @$c }, }); } my $sql = @sql ? sprintf('%s %s', $self->_sqlcase(' order by'), join(', ', @sql) ) : '' ; return wantarray ? ($sql, @bind) : $sql; } sub _order_by_chunks { my ($self, $arg) = @_; return $self->_SWITCH_refkind($arg, { ARRAYREF => sub { map { $self->_order_by_chunks($_ ) } @$arg; }, ARRAYREFREF => sub { my ($s, @b) = @$$arg; $self->_assert_bindval_matches_bindtype(@b); [ $s, @b ]; }, SCALAR => sub {$self->_quote($arg)}, UNDEF => sub {return () }, SCALARREF => sub {$$arg}, # literal SQL, no quoting HASHREF => sub { # get first pair in hash my ($key, $val, @rest) = %$arg; return () unless $key; if (@rest or not $key =~ /^-(desc|asc)/i) { puke "hash passed to _order_by must have exactly one key (-desc or -asc)"; } my $direction = $1; my @ret; for my $c ($self->_order_by_chunks($val)) { my ($sql, @bind); $self->_SWITCH_refkind($c, { SCALAR => sub { $sql = $c; }, ARRAYREF => sub { ($sql, @bind) = @$c; }, }); $sql = $sql . ' ' . $self->_sqlcase($direction); push @ret, [ $sql, @bind]; } return @ret; }, }); } #====================================================================== # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES) #====================================================================== sub _table { my $self = shift; my $from = shift; $self->_SWITCH_refkind($from, { ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$from;}, SCALAR => sub {$self->_quote($from)}, SCALARREF => sub {$$from}, }); } #====================================================================== # UTILITY FUNCTIONS #====================================================================== # highly optimized, as it's called way too often sub _quote { # my ($self, $label) = @_; return '' unless defined $_[1]; return ${$_[1]} if ref($_[1]) eq 'SCALAR'; $_[0]->{quote_char} or ($_[0]->_assert_pass_injection_guard($_[1]), return $_[1]); my $qref = ref $_[0]->{quote_char}; my ($l, $r) = !$qref ? ($_[0]->{quote_char}, $_[0]->{quote_char}) : ($qref eq 'ARRAY') ? @{$_[0]->{quote_char}} : puke "Unsupported quote_char format: $_[0]->{quote_char}"; my $esc = $_[0]->{escape_char} || $r; # parts containing * are naturally unquoted return join($_[0]->{name_sep}||'', map +( $_ eq '*' ? $_ : do { (my $n = $_) =~ s/(\Q$esc\E|\Q$r\E)/$esc$1/g; $l . $n . $r } ), ( $_[0]->{name_sep} ? split (/\Q$_[0]->{name_sep}\E/, $_[1] ) : $_[1] ) ); } # Conversion, if applicable sub _convert { #my ($self, $arg) = @_; if ($_[0]->{convert}) { return $_[0]->_sqlcase($_[0]->{convert}) .'(' . $_[1] . ')'; } return $_[1]; } # And bindtype sub _bindtype { #my ($self, $col, @vals) = @_; # called often - tighten code return $_[0]->{bindtype} eq 'columns' ? map {[$_[1], $_]} @_[2 .. $#_] : @_[2 .. $#_] ; } # Dies if any element of @bind is not in [colname => value] format # if bindtype is 'columns'. sub _assert_bindval_matches_bindtype { # my ($self, @bind) = @_; my $self = shift; if ($self->{bindtype} eq 'columns') { for (@_) { if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) { puke "bindtype 'columns' selected, you need to pass: [column_name => bind_value]" } } } } sub _join_sql_clauses { my ($self, $logic, $clauses_aref, $bind_aref) = @_; if (@$clauses_aref > 1) { my $join = " " . $self->_sqlcase($logic) . " "; my $sql = '( ' . join($join, @$clauses_aref) . ' )'; return ($sql, @$bind_aref); } elsif (@$clauses_aref) { return ($clauses_aref->[0], @$bind_aref); # no parentheses } else { return (); # if no SQL, ignore @$bind_aref } } # Fix SQL case, if so requested sub _sqlcase { # LDNOTE: if $self->{case} is true, then it contains 'lower', so we # don't touch the argument ... crooked logic, but let's not change it! return $_[0]->{case} ? $_[1] : uc($_[1]); } #====================================================================== # DISPATCHING FROM REFKIND #====================================================================== sub _refkind { my ($self, $data) = @_; return 'UNDEF' unless defined $data; # blessed objects are treated like scalars my $ref = (Scalar::Util::blessed $data) ? '' : ref $data; return 'SCALAR' unless $ref; my $n_steps = 1; while ($ref eq 'REF') { $data = $$data; $ref = (Scalar::Util::blessed $data) ? '' : ref $data; $n_steps++ if $ref; } return ($ref||'SCALAR') . ('REF' x $n_steps); } sub _try_refkind { my ($self, $data) = @_; my @try = ($self->_refkind($data)); push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF'; push @try, 'FALLBACK'; return \@try; } sub _METHOD_FOR_refkind { my ($self, $meth_prefix, $data) = @_; my $method; for (@{$self->_try_refkind($data)}) { $method = $self->can($meth_prefix."_".$_) and last; } return $method || puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data); } sub _SWITCH_refkind { my ($self, $data, $dispatch_table) = @_; my $coderef; for (@{$self->_try_refkind($data)}) { $coderef = $dispatch_table->{$_} and last; } puke "no dispatch entry for ".$self->_refkind($data) unless $coderef; $coderef->(); } #====================================================================== # VALUES, GENERATE, AUTOLOAD #====================================================================== # LDNOTE: original code from nwiger, didn't touch code in that section # I feel the AUTOLOAD stuff should not be the default, it should # only be activated on explicit demand by user. sub values { my $self = shift; my $data = shift || return; puke "Argument to ", __PACKAGE__, "->values must be a \\%hash" unless ref $data eq 'HASH'; my @all_bind; foreach my $k (sort keys %$data) { my $v = $data->{$k}; $self->_SWITCH_refkind($v, { ARRAYREF => sub { if ($self->{array_datatypes}) { # array datatype push @all_bind, $self->_bindtype($k, $v); } else { # literal SQL with bind my ($sql, @bind) = @$v; $self->_assert_bindval_matches_bindtype(@bind); push @all_bind, @bind; } }, ARRAYREFREF => sub { # literal SQL with bind my ($sql, @bind) = @${$v}; $self->_assert_bindval_matches_bindtype(@bind); push @all_bind, @bind; }, SCALARREF => sub { # literal SQL without bind }, SCALAR_or_UNDEF => sub { push @all_bind, $self->_bindtype($k, $v); }, }); } return @all_bind; } sub generate { my $self = shift; my(@sql, @sqlq, @sqlv); for (@_) { my $ref = ref $_; if ($ref eq 'HASH') { for my $k (sort keys %$_) { my $v = $_->{$k}; my $r = ref $v; my $label = $self->_quote($k); if ($r eq 'ARRAY') { # literal SQL with bind my ($sql, @bind) = @$v; $self->_assert_bindval_matches_bindtype(@bind); push @sqlq, "$label = $sql"; push @sqlv, @bind; } elsif ($r eq 'SCALAR') { # literal SQL without bind push @sqlq, "$label = $$v"; } else { push @sqlq, "$label = ?"; push @sqlv, $self->_bindtype($k, $v); } } push @sql, $self->_sqlcase('set'), join ', ', @sqlq; } elsif ($ref eq 'ARRAY') { # unlike insert(), assume these are ONLY the column names, i.e. for SQL for my $v (@$_) { my $r = ref $v; if ($r eq 'ARRAY') { # literal SQL with bind my ($sql, @bind) = @$v; $self->_assert_bindval_matches_bindtype(@bind); push @sqlq, $sql; push @sqlv, @bind; } elsif ($r eq 'SCALAR') { # literal SQL without bind # embedded literal SQL push @sqlq, $$v; } else { push @sqlq, '?'; push @sqlv, $v; } } push @sql, '(' . join(', ', @sqlq) . ')'; } elsif ($ref eq 'SCALAR') { # literal SQL push @sql, $$_; } else { # strings get case twiddled push @sql, $self->_sqlcase($_); } } my $sql = join ' ', @sql; # this is pretty tricky # if ask for an array, return ($stmt, @bind) # otherwise, s/?/shift @sqlv/ to put it inline if (wantarray) { return ($sql, @sqlv); } else { 1 while $sql =~ s/\?/my $d = shift(@sqlv); ref $d ? $d->[1] : $d/e; return $sql; } } sub DESTROY { 1 } sub AUTOLOAD { # This allows us to check for a local, then _form, attr my $self = shift; my($name) = $AUTOLOAD =~ /.*::(.+)/; return $self->generate($name, @_); } 1; __END__ =head1 NAME SQL::Abstract - Generate SQL from Perl data structures =head1 SYNOPSIS use SQL::Abstract; my $sql = SQL::Abstract->new; my($stmt, @bind) = $sql->select($source, \@fields, \%where, $order); my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values); my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where); my($stmt, @bind) = $sql->delete($table, \%where); # Then, use these in your DBI statements my $sth = $dbh->prepare($stmt); $sth->execute(@bind); # Just generate the WHERE clause my($stmt, @bind) = $sql->where(\%where, $order); # Return values in the same order, for hashed queries # See PERFORMANCE section for more details my @bind = $sql->values(\%fieldvals); =head1 DESCRIPTION This module was inspired by the excellent L. However, in using that module I found that what I really wanted to do was generate SQL, but still retain complete control over my statement handles and use the DBI interface. So, I set out to create an abstract SQL generation module. While based on the concepts used by L, there are several important differences, especially when it comes to WHERE clauses. I have modified the concepts used to make the SQL easier to generate from Perl data structures and, IMO, more intuitive. The underlying idea is for this module to do what you mean, based on the data structures you provide it. The big advantage is that you don't have to modify your code every time your data changes, as this module figures it out. To begin with, an SQL INSERT is as easy as just specifying a hash of C pairs: my %data = ( name => 'Jimbo Bobson', phone => '123-456-7890', address => '42 Sister Lane', city => 'St. Louis', state => 'Louisiana', ); The SQL can then be generated with this: my($stmt, @bind) = $sql->insert('people', \%data); Which would give you something like this: $stmt = "INSERT INTO people (address, city, name, phone, state) VALUES (?, ?, ?, ?, ?)"; @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson', '123-456-7890', 'Louisiana'); These are then used directly in your DBI code: my $sth = $dbh->prepare($stmt); $sth->execute(@bind); =head2 Inserting and Updating Arrays If your database has array types (like for example Postgres), activate the special option C<< array_datatypes => 1 >> when creating the C object. Then you may use an arrayref to insert and update database array types: my $sql = SQL::Abstract->new(array_datatypes => 1); my %data = ( planets => [qw/Mercury Venus Earth Mars/] ); my($stmt, @bind) = $sql->insert('solar_system', \%data); This results in: $stmt = "INSERT INTO solar_system (planets) VALUES (?)" @bind = (['Mercury', 'Venus', 'Earth', 'Mars']); =head2 Inserting and Updating SQL In order to apply SQL functions to elements of your C<%data> you may specify a reference to an arrayref for the given hash value. For example, if you need to execute the Oracle C function on a value, you can say something like this: my %data = ( name => 'Bill', date_entered => \[ "to_date(?,'MM/DD/YYYY')", "03/02/2003" ], ); The first value in the array is the actual SQL. Any other values are optional and would be included in the bind values array. This gives you: my($stmt, @bind) = $sql->insert('people', \%data); $stmt = "INSERT INTO people (name, date_entered) VALUES (?, to_date(?,'MM/DD/YYYY'))"; @bind = ('Bill', '03/02/2003'); An UPDATE is just as easy, all you change is the name of the function: my($stmt, @bind) = $sql->update('people', \%data); Notice that your C<%data> isn't touched; the module will generate the appropriately quirky SQL for you automatically. Usually you'll want to specify a WHERE clause for your UPDATE, though, which is where handling C<%where> hashes comes in handy... =head2 Complex where statements This module can generate pretty complicated WHERE statements easily. For example, simple C pairs are taken to mean equality, and if you want to see if a field is within a set of values, you can use an arrayref. Let's say we wanted to SELECT some data based on this criteria: my %where = ( requestor => 'inna', worker => ['nwiger', 'rcwe', 'sfz'], status => { '!=', 'completed' } ); my($stmt, @bind) = $sql->select('tickets', '*', \%where); The above would give you something like this: $stmt = "SELECT * FROM tickets WHERE ( requestor = ? ) AND ( status != ? ) AND ( worker = ? OR worker = ? OR worker = ? )"; @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz'); Which you could then use in DBI code like so: my $sth = $dbh->prepare($stmt); $sth->execute(@bind); Easy, eh? =head1 METHODS The methods are simple. There's one for every major SQL operation, and a constructor you use first. The arguments are specified in a similar order for each method (table, then fields, then a where clause) to try and simplify things. =head2 new(option => 'value') The C function takes a list of options and values, and returns a new B object which can then be used to generate SQL through the methods below. The options accepted are: =over =item case If set to 'lower', then SQL will be generated in all lowercase. By default SQL is generated in "textbook" case meaning something like: SELECT a_field FROM a_table WHERE some_field LIKE '%someval%' Any setting other than 'lower' is ignored. =item cmp This determines what the default comparison operator is. By default it is C<=>, meaning that a hash like this: %where = (name => 'nwiger', email => 'nate@wiger.org'); Will generate SQL like this: WHERE name = 'nwiger' AND email = 'nate@wiger.org' However, you may want loose comparisons by default, so if you set C to C you would get SQL such as: WHERE name like 'nwiger' AND email like 'nate@wiger.org' You can also override the comparison on an individual basis - see the huge section on L at the bottom. =item sqltrue, sqlfalse Expressions for inserting boolean values within SQL statements. By default these are C<1=1> and C<1=0>. They are used by the special operators C<-in> and C<-not_in> for generating correct SQL even when the argument is an empty array (see below). =item logic This determines the default logical operator for multiple WHERE statements in arrays or hashes. If absent, the default logic is "or" for arrays, and "and" for hashes. This means that a WHERE array of the form: @where = ( event_date => {'>=', '2/13/99'}, event_date => {'<=', '4/24/03'}, ); will generate SQL like this: WHERE event_date >= '2/13/99' OR event_date <= '4/24/03' This is probably not what you want given this query, though (look at the dates). To change the "OR" to an "AND", simply specify: my $sql = SQL::Abstract->new(logic => 'and'); Which will change the above C to: WHERE event_date >= '2/13/99' AND event_date <= '4/24/03' The logic can also be changed locally by inserting a modifier in front of an arrayref : @where = (-and => [event_date => {'>=', '2/13/99'}, event_date => {'<=', '4/24/03'} ]); See the L section for explanations. =item convert This will automatically convert comparisons using the specified SQL function for both column and value. This is mostly used with an argument of C or C, so that the SQL will have the effect of case-insensitive "searches". For example, this: $sql = SQL::Abstract->new(convert => 'upper'); %where = (keywords => 'MaKe iT CAse inSeNSItive'); Will turn out the following SQL: WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive') The conversion can be C, C, or any other SQL function that can be applied symmetrically to fields (actually B does not validate this option; it will just pass through what you specify verbatim). =item bindtype This is a kludge because many databases suck. For example, you can't just bind values using DBI's C for Oracle C or C fields. Instead, you have to use C: $sth->bind_param(1, 'reg data'); $sth->bind_param(2, $lots, {ora_type => ORA_CLOB}); The problem is, B will normally just return a C<@bind> array, which loses track of which field each slot refers to. Fear not. If you specify C in new, you can determine how C<@bind> is returned. Currently, you can specify either C (default) or C. If you specify C, you will get an array that looks like this: my $sql = SQL::Abstract->new(bindtype => 'columns'); my($stmt, @bind) = $sql->insert(...); @bind = ( [ 'column1', 'value1' ], [ 'column2', 'value2' ], [ 'column3', 'value3' ], ); You can then iterate through this manually, using DBI's C. $sth->prepare($stmt); my $i = 1; for (@bind) { my($col, $data) = @$_; if ($col eq 'details' || $col eq 'comments') { $sth->bind_param($i, $data, {ora_type => ORA_CLOB}); } elsif ($col eq 'image') { $sth->bind_param($i, $data, {ora_type => ORA_BLOB}); } else { $sth->bind_param($i, $data); } $i++; } $sth->execute; # execute without @bind now Now, why would you still use B if you have to do this crap? Basically, the advantage is still that you don't have to care which fields are or are not included. You could wrap that above C loop in a simple sub called C or something and reuse it repeatedly. You still get a layer of abstraction over manual SQL specification. Note that if you set L to C, the C<\[ $sql, @bind ]> construct (see L) will expect the bind values in this format. =item quote_char This is the character that a table or column name will be quoted with. By default this is an empty string, but you could set it to the character C<`>, to generate SQL like this: SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%' Alternatively, you can supply an array ref of two items, the first being the left hand quote character, and the second the right hand quote character. For example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes that generates SQL like this: SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%' Quoting is useful if you have tables or columns names that are reserved words in your database's SQL dialect. =item escape_char This is the character that will be used to escape Ls appearing in an identifier before it has been quoted. The parameter default in case of a single L character is the quote character itself. When opening-closing-style quoting is used (L is an arrayref) this parameter defaults to the B L. Occurrences of the B L within the identifier are currently left untouched. The default for opening-closing-style quotes may change in future versions, thus you are B to specify the escape character explicitly. =item name_sep This is the character that separates a table and column name. It is necessary to specify this when the C option is selected, so that tables and column names can be individually quoted like this: SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1 =item injection_guard A regular expression C that is applied to any C<-function> and unquoted column name specified in a query structure. This is a safety mechanism to avoid injection attacks when mishandling user input e.g.: my %condition_as_column_value_pairs = get_values_from_user(); $sqla->select( ... , \%condition_as_column_value_pairs ); If the expression matches an exception is thrown. Note that literal SQL supplied via C<\'...'> or C<\['...']> is B checked in any way. Defaults to checking for C<;> and the C keyword (TransactSQL) =item array_datatypes When this option is true, arrayrefs in INSERT or UPDATE are interpreted as array datatypes and are passed directly to the DBI layer. When this option is false, arrayrefs are interpreted as literal SQL, just like refs to arrayrefs (but this behavior is for backwards compatibility; when writing new queries, use the "reference to arrayref" syntax for literal SQL). =item special_ops Takes a reference to a list of "special operators" to extend the syntax understood by L. See section L for details. =item unary_ops Takes a reference to a list of "unary operators" to extend the syntax understood by L. See section L for details. =back =head2 insert($table, \@values || \%fieldvals, \%options) This is the simplest function. You simply give it a table name and either an arrayref of values or hashref of field/value pairs. It returns an SQL INSERT statement and a list of bind values. See the sections on L and L for information on how to insert with those data types. The optional C<\%options> hash reference may contain additional options to generate the insert SQL. Currently supported options are: =over 4 =item returning Takes either a scalar of raw SQL fields, or an array reference of field names, and adds on an SQL C statement at the end. This allows you to return data generated by the insert statement (such as row IDs) without performing another C