SQL-Abstract-More-1.17000755000000000000 012173130603 15065 5ustar00unknownunknown000000000000SQL-Abstract-More-1.17/Build.PL000444000000000000 165612075346615 16543 0ustar00unknownunknown000000000000use strict; use warnings; use Module::Build; my $builder = Module::Build->new( module_name => 'SQL::Abstract::More', license => 'perl', dist_author => q{Laurent Dami }, dist_version_from => 'lib/SQL/Abstract/More.pm', requires => { 'MRO::Compat' => 0, 'SQL::Abstract' => 1.73, 'Params::Validate' => 0, 'Scalar::Does' => 0, 'parent' => 0, 'namespace::clean' => 0, }, build_requires => { 'Test::More' => 0, 'Test::Exception' => 0, 'SQL::Abstract::Test' => 0, }, add_to_cleanup => [ 'SQL-Abstract-More-*' ], create_makefile_pl => 'traditional', meta_merge => { resources => { repository => 'https://github.com/damil/SQL-Abstract-More', } }, ); $builder->create_build_script(); SQL-Abstract-More-1.17/Changes000444000000000000 463312173130543 16526 0ustar00unknownunknown000000000000Revision history for SQL-Abstract-More 1.17 22.07.2013 - fixed incorrect treatment of -limit for "RowNum" dialect (used by Oracle) 1.16 16.07.2013 - fixed doc for join() (description of the return value) - fix for RT 86895 (incorrect treatment of -order_by / -group_by) 1.15 18.04.2013 - bind values with types : dropped syntax [$value, \%type] because of conflicts with "OR" clauses of shape [$condition1, \%condition2]; so only DBIx::Class-like syntax will be accepted 1.14 14.04.2013 - fix bug introduced in v1.13 (return "" instead of return ()) 1.13 14.04.2013 - "looks_like_ternary_bind_param" renamed as "is_bind_value_with_type" - support for DBIx::Class syntax of bind values with types 1.12 08.04.2013 - fix missing bits for supporting arrayrefs in insert(), update() - improvements in doc 1.11 07.04.2013 - bind_params supports 3-args form of DBI::bind_param() - values in select(), insert(), update() can be arrayrefs [$value, \%type] 1.10 15.01.2013 - support for -desc/-asc in -order_by (compatibility with SQL::Abstract) 1.09 08.12.2012 - dependency on SQL::Abstract 1.73 because of -ident/-value 1.08 30.11.2012 - [rt.cpan.org #81305] replace \'=foo.bar' by {'=' => {-ident => 'foo.bar'}} - [rt.cpan.org #81485] systematically order "keys %hash" for perl 5.17.6 1.07 20.10.2012 - replace reftype tests by Scalar::Does - no longer warns on -where => {field => {-in => $scalar}} 1.06 02.08.2012 - fix in test that no longer passed with SQL::Abstract::Test v1.73 1.05 31.05.2012 - forgot dependency on MRO::Compat 1.04 29.05.2012 - [rt.cpan.org #77374] Use namespace::clean instead of namespace::autoclean - added support for set operators (UNION/INTERSECT/MINUS/etc.) 1.03 17.03.2012 - added support for Oracle INSERT ... RETURNING .. INTO .. - croak() instead of die() upon errors 1.02 13.03.2012 - unbless arrayrefs passed to _where_field_IN, to make SQLA happy 1.01 08.03.2012 - fixed sql_dialect for Oracle : no 'AS' keyword in table aliases 1.00 15.12.2011 - added methods insert(), update(), delete() 0.06 13.12.2011 - new parameter 'max_members_IN' 0.05 07.10.2011 - limit_offset dialect "RowNum", for @§%#! Oracle 0.04 28.08.2011 - doc fix, thanks to Terrence Brannon 0.03 07.08.2011 - added dependency on 'parent.pm' in Build.PL 0.02 03.08.2011 - Fixed stupid pod test 0.01 31.07.2011 - First release (code extracted and refactored from DBIx::DataModel) SQL-Abstract-More-1.17/Makefile.PL000444000000000000 130312173130603 17171 0ustar00unknownunknown000000000000# Note: this file was auto-generated by Module::Build::Compat version 0.4004 use ExtUtils::MakeMaker; WriteMakefile ( 'NAME' => 'SQL::Abstract::More', 'VERSION_FROM' => 'lib/SQL/Abstract/More.pm', 'PREREQ_PM' => { 'MRO::Compat' => 0, 'Params::Validate' => 0, 'SQL::Abstract' => '1.73', 'SQL::Abstract::Test' => 0, 'Scalar::Does' => 0, 'Test::Exception' => 0, 'Test::More' => 0, 'namespace::clean' => 0, 'parent' => 0 }, 'INSTALLDIRS' => 'site', 'EXE_FILES' => [], 'PL_FILES' => {} ) ; SQL-Abstract-More-1.17/MANIFEST000444000000000000 26312170207262 16337 0ustar00unknownunknown000000000000Build.PL Changes lib/SQL/Abstract/More.pm Makefile.PL MANIFEST META.json META.yml README t/01-sql_abstract_more.t t/02-order-by.t t/pod.t t/rt_084972.t t/rt_086895.t SQL-Abstract-More-1.17/META.json000444000000000000 267512173130603 16655 0ustar00unknownunknown000000000000{ "abstract" : "extension of SQL::Abstract with more constructs and more flexible API", "author" : [ "Laurent Dami " ], "dynamic_config" : 1, "generated_by" : "Module::Build version 0.4004, CPAN::Meta::Converter version 2.120921", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "SQL-Abstract-More", "prereqs" : { "build" : { "requires" : { "SQL::Abstract::Test" : "0", "Test::Exception" : "0", "Test::More" : "0" } }, "configure" : { "requires" : { "Module::Build" : "0.40" } }, "runtime" : { "requires" : { "MRO::Compat" : "0", "Params::Validate" : "0", "SQL::Abstract" : "1.73", "Scalar::Does" : "0", "namespace::clean" : "0", "parent" : "0" } } }, "provides" : { "SQL::Abstract::More" : { "file" : "lib/SQL/Abstract/More.pm", "version" : "1.17" } }, "release_status" : "stable", "resources" : { "license" : [ "http://dev.perl.org/licenses/" ], "repository" : { "url" : "https://github.com/damil/SQL-Abstract-More" } }, "version" : "1.17" } SQL-Abstract-More-1.17/META.yml000444000000000000 153012173130603 16472 0ustar00unknownunknown000000000000--- abstract: 'extension of SQL::Abstract with more constructs and more flexible API' author: - 'Laurent Dami ' build_requires: SQL::Abstract::Test: 0 Test::Exception: 0 Test::More: 0 configure_requires: Module::Build: 0.40 dynamic_config: 1 generated_by: 'Module::Build version 0.4004, CPAN::Meta::Converter version 2.120921' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: 1.4 name: SQL-Abstract-More provides: SQL::Abstract::More: file: lib/SQL/Abstract/More.pm version: 1.17 requires: MRO::Compat: 0 Params::Validate: 0 SQL::Abstract: 1.73 Scalar::Does: 0 namespace::clean: 0 parent: 0 resources: license: http://dev.perl.org/licenses/ repository: https://github.com/damil/SQL-Abstract-More version: 1.17 SQL-Abstract-More-1.17/README000444000000000000 243011711661701 16106 0ustar00unknownunknown000000000000SQL-Abstract-More This subclass of L handles a few additional SQL constructs, and provides an improved API with named parameters instead of positional parameters. It was designed for the specific needs of L but is published as a separate distribution, because it may possibly be useful for other needs. INSTALLATION To install this module, run the following commands: perl Build.PL ./Build ./Build test ./Build install SUPPORT AND DOCUMENTATION After installing, you can find documentation for this module with the perldoc command. perldoc SQL::Abstract::More You can also look for information at: RT, CPAN's request tracker http://rt.cpan.org/NoAuth/Bugs.html?Dist=SQL-Abstract-More AnnoCPAN, Annotated CPAN documentation http://annocpan.org/dist/SQL-Abstract-More CPAN Ratings http://cpanratings.perl.org/d/SQL-Abstract-More Search CPAN http://search.cpan.org/dist/SQL-Abstract-More/ LICENSE AND COPYRIGHT Copyright (C) 2011 Laurent Dami This program is free software; you can redistribute it and/or modify it under the terms of either: the GNU General Public License as published by the Free Software Foundation; or the Artistic License. See http://dev.perl.org/licenses/ for more information. SQL-Abstract-More-1.17/lib000755000000000000 012173130603 15633 5ustar00unknownunknown000000000000SQL-Abstract-More-1.17/lib/SQL000755000000000000 012173130603 16272 5ustar00unknownunknown000000000000SQL-Abstract-More-1.17/lib/SQL/Abstract000755000000000000 012173130603 20035 5ustar00unknownunknown000000000000SQL-Abstract-More-1.17/lib/SQL/Abstract/More.pm000444000000000000 14447612173130515 21514 0ustar00unknownunknown000000000000package SQL::Abstract::More; use strict; use warnings; use SQL::Abstract 1.73; use parent 'SQL::Abstract'; use MRO::Compat; use mro 'c3'; # implements next::method use Params::Validate qw/validate SCALAR SCALARREF CODEREF ARRAYREF HASHREF UNDEF BOOLEAN/; use Scalar::Util qw/blessed/; use Scalar::Does qw/does/; use Carp; use namespace::clean; our $VERSION = '1.17'; # builtin methods for "Limit-Offset" dialects my %limit_offset_dialects = ( LimitOffset => sub {my ($self, $limit, $offset) = @_; $offset ||= 0; return "LIMIT ? OFFSET ?", $limit, $offset;}, LimitXY => sub {my ($self, $limit, $offset) = @_; $offset ||= 0; return "LIMIT ?, ?", $offset, $limit;}, LimitYX => sub {my ($self, $limit, $offset) = @_; $offset ||= 0; return "LIMIT ?, ?", $limit, $offset;}, RowNum => sub { my ($self, $limit, $offset) = @_; # HACK below borrowed from SQL::Abstract::Limit. Not perfect, though, # because it brings back an additional column. Should borrow from # DBIx::Class::SQLMaker::LimitDialects, which does the proper job ... # but it says : "!!! THIS IS ALSO HORRIFIC !!! /me ashamed"; so # I'll only take it as last resort; still exploring other ways. # See also L : within that ORM an additional layer is # added to take advantage of Oracle scrollable cursors. my $sql = "SELECT * FROM (" . "SELECT subq_A.*, ROWNUM rownum__index FROM (%s) subq_A " . "WHERE ROWNUM <= ?" . ") subq_B WHERE rownum__index >= ?"; no warnings 'uninitialized'; # in case $limit or $offset is undef # row numbers start at 1 return $sql, $offset + $limit, $offset + 1; }, ); # builtin join operators with associated sprintf syntax my %common_join_syntax = ( '<=>' => '%s INNER JOIN %s ON %s', '=>' => '%s LEFT OUTER JOIN %s ON %s', '<=' => '%s RIGHT JOIN %s ON %s', '==' => '%s NATURAL JOIN %s', ); my %right_assoc_join_syntax = %common_join_syntax; s/JOIN %s/JOIN (%s)/ foreach values %right_assoc_join_syntax; # specification of parameters accepted by the new() method my %params_for_new = ( table_alias => {type => SCALAR|CODEREF, default => '%s AS %s'}, column_alias => {type => SCALAR|CODEREF, default => '%s AS %s'}, limit_offset => {type => SCALAR|CODEREF, default => 'LimitOffset'}, join_syntax => {type => HASHREF, default => \%common_join_syntax}, join_assoc_right => {type => BOOLEAN, default => 0}, max_members_IN => {type => SCALAR, optional => 1}, sql_dialect => {type => SCALAR, optional => 1}, ); # builtin collection of parameters, for various databases my %sql_dialects = ( MsAccess => { join_assoc_right => 1, join_syntax => \%right_assoc_join_syntax}, BasisJDBC => { column_alias => "%s %s", max_members_IN => 255 }, MySQL_old => { limit_offset => "LimitXY" }, Oracle => { limit_offset => "RowNum", max_members_IN => 999, table_alias => '%s %s', column_alias => '%s %s', }, ); # operators for compound queries my @set_operators = qw/union union_all intersect minus except/; # specification of parameters accepted by select, insert, update, delete my %params_for_select = ( -columns => {type => SCALAR|ARRAYREF, default => '*'}, -from => {type => SCALAR|SCALARREF|ARRAYREF}, -where => {type => SCALAR|ARRAYREF|HASHREF, optional => 1}, (map {-$_ => {type => ARRAYREF, optional => 1}} @set_operators), -group_by => {type => SCALAR|ARRAYREF, optional => 1}, -having => {type => SCALAR|ARRAYREF|HASHREF, optional => 1, depends => '-group_by'}, -order_by => {type => SCALAR|ARRAYREF|HASHREF, optional => 1}, -page_size => {type => SCALAR, optional => 1}, -page_index => {type => SCALAR, optional => 1, depends => '-page_size'}, -limit => {type => SCALAR, optional => 1}, -offset => {type => SCALAR, optional => 1, depends => '-limit'}, -for => {type => SCALAR|UNDEF, optional => 1}, -want_details => {type => BOOLEAN, optional => 1}, ); my %params_for_insert = ( -into => {type => SCALAR}, -values => {type => SCALAR|ARRAYREF|HASHREF}, -returning => {type => SCALAR|ARRAYREF|HASHREF, optional => 1}, ); my %params_for_update = ( -table => {type => SCALAR}, -set => {type => HASHREF}, -where => {type => SCALAR|ARRAYREF|HASHREF, optional => 1}, ); my %params_for_delete = ( -from => {type => SCALAR}, -where => {type => SCALAR|ARRAYREF|HASHREF, optional => 1}, ); #---------------------------------------------------------------------- # object creation #---------------------------------------------------------------------- sub new { my ($class, %params) = @_; # extract params for this subclass my %more_params; foreach my $key (keys %params_for_new) { $more_params{$key} = delete $params{$key} if exists $params{$key}; } # import params from SQL dialect, if any my $dialect = delete $more_params{sql_dialect}; if ($dialect) { my $dialect_params = $sql_dialects{$dialect} or croak "no such sql dialect: $dialect"; $more_params{$_} ||= $dialect_params->{$_} foreach keys %$dialect_params; } # check parameters my @more_params = %more_params; my $more_self = validate(@more_params, \%params_for_new); # call parent constructor my $self = $class->next::method(%params); # inject into $self $self->{$_} = $more_self->{$_} foreach keys %$more_self; # arguments supplied as scalars are transformed into coderefs ref $self->{column_alias} or $self->_make_AS_through_sprintf('column_alias'); ref $self->{table_alias} or $self->_make_AS_through_sprintf('table_alias'); ref $self->{limit_offset} or $self->_choose_LIMIT_OFFSET_dialect; # regex for parsing join specifications my @join_ops = sort {length($b) <=> length($a) || $a cmp $b} keys %{$self->{join_syntax}}; my $joined_ops = join '|', map quotemeta, @join_ops; $self->{join_regex} = qr[ ^ # initial anchor ($joined_ops)? # $1: join operator (i.e. '<=>', '=>', etc.)) ([[{])? # $2: opening '[' or '{' (.*?) # $3: content of brackets []}]? # closing ']' or '}' $ # final anchor ]x; return $self; } #---------------------------------------------------------------------- # the select method #---------------------------------------------------------------------- sub select { my $self = shift; # if got positional args, this is not our job, just delegate to the parent return $self->next::method(@_) if !&_called_with_named_args; # declare variables and parse arguments; my ($join_info, %aliased_columns); my %args = validate(@_, \%params_for_select); # compute join info if the datasource is a join if (ref $args{-from} eq 'ARRAY' && $args{-from}[0] eq '-join') { my @join_args = @{$args{-from}}; shift @join_args; # drop initial '-join' $join_info = $self->join(@join_args); $args{-from} = \($join_info->{sql}); } # reorganize columns; initial members starting with "-" are extracted # into a separate list @post_select, later re-injected into the SQL my @cols = ref $args{-columns} ? @{$args{-columns}} : $args{-columns}; my @post_select; push @post_select, shift @cols while @cols && $cols[0] =~ s/^-//; foreach my $col (@cols) { # extract alias, if any (recognized as "column|alias") ($col, my $alias) = split /\|/, $col, 2; if ($alias) { $aliased_columns{$alias} = $col; $col = $self->column_alias($col, $alias); } } $args{-columns} = \@cols; # reorganize pagination if ($args{-page_index} || $args{-page_size}) { not exists $args{$_} or croak "-page_size conflicts with $_" for qw/-limit -offset/; $args{-limit} = $args{-page_size}; if ($args{-page_index}) { $args{-offset} = ($args{-page_index} - 1) * $args{-page_size}; } } # generate initial ($sql, @bind), without -order_by (will be handled later) my @old_API_args = @args{qw/-from -columns -where/}; # my ($sql, @bind) = $self->next::method(@old_API_args); unshift @bind, @{$join_info->{bind}} if $join_info; # add @post_select clauses if needed (for ex. -distinct) my $post_select = join " ", @post_select; $sql =~ s[^SELECT ][SELECT $post_select ]i if $post_select; # add set operators (UNION, INTERSECT, etc) if needed foreach my $set_op (@set_operators) { if ($args{-$set_op}) { my %sub_args = @{$args{-$set_op}}; $sub_args{$_} ||= $args{$_} for qw/-columns -from/; my ($sql1, @bind1) = $self->select(%sub_args); (my $sql_op = uc($set_op)) =~ s/_/ /g; $sql .= " $sql_op $sql1"; push @bind, @bind1; } } # add GROUP BY/HAVING if needed if ($args{-group_by}) { my $sql_grp = $self->where(undef, $args{-group_by}); $sql_grp =~ s/\bORDER\b/GROUP/; if ($args{-having}) { my ($sql_having, @bind_having) = $self->where($args{-having}); $sql_having =~ s/\bWHERE\b/HAVING/; $sql_grp .= " $sql_having"; push @bind, @bind_having; } $sql .= $sql_grp; } # add ORDER BY if needed if (my $order = $args{-order_by}) { # force scalar into an arrayref $order = [$order] if not ref $order; # restructure array data if (ref $order eq 'ARRAY') { my @clone = @$order; # because we will modify items # '-' and '+' prefixes are translated into {-desc/asc => } hashrefs foreach my $item (@clone) { next if !$item or ref $item; $item =~ s/^-// and $item = {-desc => $item} and next; $item =~ s/^\+// and $item = {-asc => $item}; } $order = \@clone; } my $sql_order = $self->where(undef, $order); $sql .= $sql_order; } # add LIMIT/OFFSET if needed if ($args{-limit}) { my ($limit_sql, @limit_bind) = $self->limit_offset(@args{qw/-limit -offset/}); $sql = $limit_sql =~ /%s/ ? sprintf $limit_sql, $sql : "$sql $limit_sql"; push @bind, @limit_bind; } # add FOR if needed $sql .= " FOR $args{-for}" if $args{-for}; if ($args{-want_details}) { return {sql => $sql, bind => \@bind, aliased_tables => ($join_info && $join_info->{aliased_tables}), aliased_columns => \%aliased_columns }; } else { return ($sql, @bind); } } #---------------------------------------------------------------------- # insert, update and delete methods #---------------------------------------------------------------------- sub insert { my $self = shift; my @old_API_args; my $returning_into; if (&_called_with_named_args) { # extract named args and translate to old SQLA API my %args = validate(@_, \%params_for_insert); @old_API_args = @args{qw/-into -values/}; # if present, "-returning" may be a scalar, arrayref or hashref; the latter # is interpreted as .. RETURNING ... INTO ... if (my $returning = $args{-returning}) { if (does($returning, 'HASH')) { my @keys = sort keys %$returning or croak "-returning => {} : the hash is empty"; push @old_API_args, {returning => \@keys}; $returning_into = [@{$returning}{@keys}]; } else { push @old_API_args, {returning => $returning}; } } } else { @old_API_args = @_; } # get results from parent method my ($sql, @bind) = $self->next::method(@old_API_args); # inject more stuff if using Oracle's "RETURNING ... INTO ..." if ($returning_into) { $sql .= ' INTO ' . join(", ", ("?") x @$returning_into); push @bind, @$returning_into; } return ($sql, @bind); } sub update { my $self = shift; my @old_API_args; if (&_called_with_named_args) { my %args = validate(@_, \%params_for_update); @old_API_args = @args{qw/-table -set -where/}; } else { @old_API_args = @_; } # return $self->next::method(@old_API_args); return $self->_overridden_update(@old_API_args); } sub delete { my $self = shift; my @old_API_args; if (&_called_with_named_args) { my %args = validate(@_, \%params_for_delete); @old_API_args = @args{qw/-from -where/}; } else { @old_API_args = @_; } return $self->next::method(@old_API_args); } #---------------------------------------------------------------------- # other public methods #---------------------------------------------------------------------- # same pattern for 3 invocation methods foreach my $attr (qw/table_alias column_alias limit_offset/) { no strict 'refs'; *{$attr} = sub { my $self = shift; my $method = $self->{$attr}; # grab reference to method body $self->$method(@_); # invoke }; } # invocation method for 'join' sub join { my $self = shift; # start from the right if right-associative @_ = reverse @_ if $self->{join_assoc_right}; # shift first single item (a table) before reducing pairs (op, table) my $combined = shift; $combined = $self->_parse_table($combined) unless ref $combined; # reduce pairs (op, table) while (@_) { # shift 2 items : next join specification and next table my $join_spec = shift; my $table_spec = shift or croak "join(): improper number of operands"; $join_spec = $self->_parse_join_spec($join_spec) unless ref $join_spec; $table_spec = $self->_parse_table($table_spec) unless ref $table_spec; $combined = $self->_single_join($combined, $join_spec, $table_spec); } return $combined; # {sql=> .., bind => [..], aliased_tables => {..}} } # utility for merging several "where" clauses sub merge_conditions { my $self = shift; my %merged; foreach my $cond (@_) { if (does($cond, 'HASH')) { foreach my $col (sort keys %$cond) { $merged{$col} = $merged{$col} ? [-and => $merged{$col}, $cond->{$col}] : $cond->{$col}; } } elsif (does($cond, 'ARRAY')) { $merged{-nest} = $merged{-nest} ? {-and => [$merged{-nest}, $cond]} : $cond; } elsif ($cond) { $merged{$cond} = \""; } } return \%merged; } # utility for calling either bind_param or bind_param_inout our $INOUT_MAX_LEN = 99; # chosen arbitrarily; see L sub bind_params { my ($self, $sth, @bind) = @_; $sth->isa('DBI::st') or croak "sth argument is not a DBI statement handle"; foreach my $i (0 .. $#bind) { my $val = $bind[$i]; my $ref = ref $val || ''; if ($ref eq 'SCALAR') { # a scalarref is interpreted as an INOUT parameter $sth->bind_param_inout($i+1, $val, $INOUT_MAX_LEN); } elsif ($ref eq 'ARRAY' and my ($bind_meth, @args) = $self->is_bind_value_with_type($val)) { # either 'bind_param' or 'bind_param_inout', with 2 or 3 args $sth->$bind_meth($i+1, @args); } else { # other cases are passed directly to DBI::bind_param $sth->bind_param($i+1, $val); } } } sub is_bind_value_with_type { my ($self, $val) = @_; # compatibility with DBIx::Class syntax of shape [\%args => $val], # see L if ( @$val == 2 && does($val->[0], 'HASH') && grep {$val->[0]{$_}} qw/dbd_attrs sqlt_size sqlt_datatype dbic_colname/) { my $args = $val->[0]; if (my $attrs = $args->{dbd_attrs}) { return (bind_param => $val->[1], $attrs); } elsif (my $size = $args->{sqlt_size}) { return (bind_param_inout => $val, $size); } # other options like 'sqlt_datatype', 'dbic_colname' are not supported else { croak "unsupported options for bind type : " . CORE::join(", ", sort keys %$args); } # NOTE : the following DBIx::Class shortcuts are not supported # [ $name => $val ] === [ { dbic_colname => $name }, $val ] # [ \$dt => $val ] === [ { sqlt_datatype => $dt }, $val ] # [ undef, $val ] === [ {}, $val ] } # in all other cases, this is not a bind value with type return (); } #---------------------------------------------------------------------- # private utility methods for 'join' #---------------------------------------------------------------------- sub _parse_table { my ($self, $table) = @_; # extract alias, if any (recognized as "table|alias") ($table, my $alias) = split /\|/, $table, 2; # build a table spec return { sql => $self->table_alias($table, $alias), bind => [], name => ($alias || $table), aliased_tables => {$alias ? ($alias => $table) : ()}, }; } sub _parse_join_spec { my ($self, $join_spec) = @_; # parse the join specification $join_spec or croak "empty join specification"; my ($op, $bracket, $cond_list) = ($join_spec =~ $self->{join_regex}) or croak "incorrect join specification : $join_spec\n$self->{join_regex}"; $op ||= '<=>'; $bracket ||= '{'; $cond_list ||= ''; # find join syntax corresponding to the join operator $self->{join_syntax}{$op} or croak "unknown join operator : $op"; # accumulate conditions as pairs ($left => \"$op $right") my @conditions; foreach my $cond (split /,/, $cond_list) { # parse the comparison operator (left and right operands + cmp op) my ($left, $cmp, $right) = split /([<>=!^]{1,2})/, $cond or croak "can't parse join condition: $cond"; # if operands are not qualified by table/alias name, add placeholders $left = "%1\$s.$left" unless $left =~ /\./; $right = "%2\$s.$right" unless $right =~ /\./; # add this pair into the list push @conditions, $left, {$cmp => {-ident => $right}}; } # list becomes an arrayref or hashref (for SQLA->where()) my $join_on = $bracket eq '[' ? [@conditions] : {@conditions}; # return a new join spec return {operator => $op, condition => $join_on}; } sub _single_join { my $self = shift; # if right-associative, restore proper left-right order in pair @_ = reverse @_ if $self->{join_assoc_right}; my ($left, $join_spec, $right) = @_; # compute the "ON" clause (assuming it contains '%1$s', '%2$s' for # left/right tables) my ($sql, @bind) = $self->where($join_spec->{condition}); $sql =~ s/^\s*WHERE\s+//; $sql = sprintf $sql, $left->{name}, $right->{name}; # assemble all elements my $syntax = $self->{join_syntax}{$join_spec->{operator}}; $sql = sprintf $syntax, $left->{sql}, $right->{sql}, $sql; unshift @bind, @{$left->{bind}}, @{$right->{bind}}; # build result and return my %result = (sql => $sql, bind => \@bind); $result{name} = ($self->{join_assoc_right} ? $left : $right)->{name}; $result{aliased_tables} = $left->{aliased_tables}; foreach my $alias (keys %{$right->{aliased_tables}}) { $result{aliased_tables}{$alias} = $right->{aliased_tables}{$alias}; } return \%result; } #---------------------------------------------------------------------- # override of parent's "_where_field_IN" #---------------------------------------------------------------------- sub _where_field_IN { my ($self, $k, $op, $vals) = @_; my $max_members_IN = $self->{max_members_IN}; if ($max_members_IN && does($vals, 'ARRAY') && @$vals > $max_members_IN) { my @vals = @$vals; my @slices; while (my @slice = splice(@vals, 0, $max_members_IN)) { push @slices, \@slice; } my @clauses = map {{-$op, $_}} @slices; my $connector = $op =~ /^not/i ? '-and' : '-or'; unshift @clauses, $connector; my ($sql, @bind) = $self->where({$k => \@clauses}); $sql =~ s/\s*where\s*\((.*)\)/$1/i; return ($sql, @bind); } else { $vals = [@$vals] if blessed $vals; # because SQLA dies on blessed arrayrefs return $self->next::method($k, $op, $vals); } } #---------------------------------------------------------------------- # override of parent's methods for decoding arrayrefs #---------------------------------------------------------------------- sub _where_hashpair_ARRAYREF { my ($self, $k, $v) = @_; if ($self->is_bind_value_with_type($v)) { $self->_assert_no_bindtype_columns; my $sql = CORE::join ' ', $self->_convert($self->_quote($k)), $self->_sqlcase($self->{cmp}), $self->_convert('?'); my @bind = ($v); return ($sql, @bind); } else { return $self->next::method($k, $v); } } sub _where_field_op_ARRAYREF { my ($self, $k, $op, $vals) = @_; if ($self->is_bind_value_with_type($vals)) { $self->_assert_no_bindtype_columns; my $sql = CORE::join ' ', $self->_convert($self->_quote($k)), $self->_sqlcase($op), $self->_convert('?'); my @bind = ($vals); return ($sql, @bind); } else { return $self->next::method($k, $op, $vals); } } sub _assert_no_bindtype_columns { my ($self) = @_; $self->{bindtype} ne 'columns' or croak 'values of shape [$val, \%type] are not compatible' . 'with ...->new(bindtype => "columns")'; } sub _insert_values { # unfortunately, we can't just override the ARRAYREF part, so the whole # parent method is copied here my ($self, $data) = @_; my (@values, @all_bind); foreach my $column (sort keys %$data) { my $v = $data->{$column}; $self->_SWITCH_refkind($v, { ARRAYREF => sub { if ($self->{array_datatypes} || $self->is_bind_value_with_type($v)) { # if array datatype are activated or this is a [$val, \%type] struct push @values, '?'; push @all_bind, $self->_bindtype($column, $v); } else { # otherwise, 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 SQL::Abstract::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 = $self->_sqlcase('values')." ( ".CORE::join(", ", @values)." )"; return ($sql, @all_bind); } sub _overridden_update { # unfortunately, we can't just override the ARRAYREF part, so the whole # parent method is copied here my $self = shift; my $table = $self->_table(shift); my $data = shift || return; my $where = shift; # first build the 'SET' part of the sql statement my (@set, @all_bind); SQL::Abstract::puke("Unsupported data type specified to \$sql->update") unless ref $data eq 'HASH'; 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} || $self->is_bind_value_with_type($v)) { 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; SQL::Abstract::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 = $self->_sqlcase('update') . " $table " . $self->_sqlcase('set ') . CORE::join ', ', @set; if ($where) { my($where_sql, @where_bind) = $self->where($where); $sql .= $where_sql; push @all_bind, @where_bind; } return wantarray ? ($sql, @all_bind) : $sql; } #---------------------------------------------------------------------- # method creations through closures #---------------------------------------------------------------------- sub _make_AS_through_sprintf { my ($self, $attribute) = @_; my $syntax = $self->{$attribute}; $self->{$attribute} = sub { my ($self, $name, $alias) = @_; return $alias ? sprintf($syntax, $name, $alias) : $name; }; } sub _choose_LIMIT_OFFSET_dialect { my $self = shift; my $dialect = $self->{limit_offset}; my $method = $limit_offset_dialects{$dialect} or croak "no such limit_offset dialect: $dialect"; $self->{limit_offset} = $method; }; #---------------------------------------------------------------------- # utility to decide if the method was called with named or positional args #---------------------------------------------------------------------- sub _called_with_named_args { return $_[0] && !ref $_[0] && substr($_[0], 0, 1) eq '-'; } 1; # End of SQL::Abstract::More __END__ =head1 NAME SQL::Abstract::More - extension of SQL::Abstract with more constructs and more flexible API =head1 DESCRIPTION Generates SQL from Perl datastructures. This is a subclass of L, fully compatible with the parent class, but with some additions : =over =item * additional SQL constructs like C<-union>, C<-group_by>, C, etc. =item * methods take arguments as named parameters instead of positional parameters, so that various SQL fragments are more easily identified =item * values passed to C keyword. This is especially useful for $sqla->select(..., -columns => [-DISTINCT => @columns], ...); However, it may also be useful for other purposes, like vendor-specific SQL variants : # MySQL features ->select(..., -columns => [-STRAIGHT_JOIN => @columns], ...); ->select(..., -columns => [-SQL_SMALL_RESULT => @columns], ...); # Oracle hint ->select(..., -columns => ["-/*+ FIRST_ROWS (100) */" => @columns], ...); The argument to C<-columns> can also be a string instead of an arrayref, like for example C<< "c1 AS foobar, MAX(c2) AS m_c2, COUNT(c3) AS n_c3" >>; however this is mainly for backwards compatibility. The recommended way is to use the arrayref notation as explained above : -columns => [ qw/ c1|foobar MAX(c2)|m_c2 COUNT(c3)|n_c3 / ] If omitted, C<< -columns >> takes '*' as default argument. =item C<< -from => $table || \@joined_tables >> =item C<< -where => $criteria >> Like in L, C<< $criteria >> can be a plain SQL string like C<< "col1 IN (3, 5, 7, 11) OR col2 IS NOT NULL" >>; but in most cases, it will rather be a reference to a hash or array of conditions that will be translated into SQL clauses, like for example C<< {col1 => 'val1', col2 => 'val2'} >>. The structure of that hash or array can be nested to express complex boolean combinations of criteria; see L for a detailed description. When using hashrefs or arrayrefs, leaf values can be "bind values with types"; see the L section below. =item C<< -union => [ %select_subargs ] >> =item C<< -union_all => [ %select_subargs ] >> =item C<< -intersect => [ %select_subargs ] >> =item C<< -except => [ %select_subargs ] >> =item C<< -minus => [ %select_subargs ] >> generates a compound query using set operators such as C, C, etc. The argument C<%select_subargs> contains a nested set of parameters like for the main select (i.e. C<-columns>, C<-from>, C<-where>, etc.); however, arguments C<-columns> and C<-from> can be omitted, in which case they will be copied from the main select(). Several levels of set operators can be nested. =item C<< -group_by => "string" >> or C<< -group_by => \@array >> adds a C clause in the SQL statement. Grouping columns are specified either by a plain string or by an array of strings. =item C<< -having => "string" >> or C<< -having => \%criteria >> adds a C clause in the SQL statement (only makes sense together with a C clause). This is like a C<-where> clause, except that the criteria are applied after grouping has occured. =item C<< -order_by => \@order >> C<< \@order >> is a reference to a list of columns for sorting. Columns can be prefixed by '+' or '-' for indicating sorting directions, so for example C<< -orderBy => [qw/-col1 +col2 -col3/] >> will generate the SQL clause C<< ORDER BY col1 DESC, col2 ASC, col3 DESC >>. Column names C and C are treated as exceptions to this rule, in order to preserve compatibility with L. So C<< -orderBy => [-desc => 'colA'] >> yields C<< ORDER BY colA DESC >> and not C<< ORDER BY desc DEC, colA >>. Any other syntax supported by L is also supported here; see L for examples. The whole C<< -order_by >> parameter can also be a plain SQL string like C<< "col1 DESC, col3, col2 DESC" >>. =item C<< -page_size => $page_size >> specifies how many rows will be retrieved per "page" of data. Default is unlimited (or more precisely the maximum value of a short integer on your system). When specified, this parameter automatically implies C<< -limit >>. =item C<< -page_index => $page_index >> specifies the page number (starting at 1). Default is 1. When specified, this parameter automatically implies C<< -offset >>. =item C<< -limit => $limit >> limit to the number of rows that will be retrieved. Automatically implied by C<< -page_size >>. =item C<< -offset => $offset >> Automatically implied by C<< -page_index >>. Defaults to 0. =item C<< -for => $clause >> specifies an additional clause to be added at the end of the SQL statement, like C<< -for => 'READ ONLY' >> or C<< -for => 'UPDATE' >>. =item C<< -want_details => 1 >> If true, the return value will be a hashref instead of the usual C<< ($sql, @bind) >>. The hashref contains the following keys : =over =item sql generated SQL =item bind bind values =item aliased_tables a hashref of C<< {table_alias => table_name} >> encountered while parsing the C<-from> parameter. =item aliased_columns a hashref of C<< {column_alias => column_name} >> encountered while parsing the C<-columns> parameter. =back =back =head2 insert # positional parameters, directly passed to the parent class ($sql, @bind) = $sqla->insert($table, \@values || \%fieldvals, \%options); # named parameters, handled in this class ($sql, @bind) = $sqla->insert( -into => $table, -values => {col => $val, ...}, -returning => $return_structure, ); Like for L, values assigned to columns can have associated SQL types; see L. Named parameters to the C method are just syntactic sugar for better readability of the client's code. Parameters C<-into> and C<-values> are passed verbatim to the parent method. Parameter C<-returning> is optional and only supported by some database vendors (see L); if the C<$return_structure> is =over =item * a scalar or an arrayref, it is passed directly to the parent method =item * a hashref, it is interpreted as a SQL clause "RETURNING .. INTO ..", as required in particular by Oracle. Hash keys are field names, and hash values are references to variables that will receive the results. Then it is the client code's responsability to use L for binding the variables and retrieving the results, but the L method in the present module is there for help. Example: ($sql, @bind) = $sqla->insert( -into => $table, -values => {col => $val, ...}, -returning => {key_col => \my $generated_key}, ); my $sth = $dbh->prepare($sql); $sqla->bind_params($sth, @bind); $sth->execute; print "The new key is $generated_key"; =back =head2 update # positional parameters, directly passed to the parent class ($sql, @bind) = $sqla->update($table, \%fieldvals, \%where); # named parameters, handled in this class ($sql, @bind) = $sqla->update( -table => $table, -set => {col => $val, ...}, -where => \%conditions, ); This works in the same spirit as the L method above. Named parameters to the C method are just syntactic sugar for better readability of the client's code; they are passed verbatim to the parent method. =head2 delete # positional parameters, directly passed to the parent class ($sql, @bind) = $sqla->delete($table, \%where); # named parameters, handled in this class ($sql, @bind) = $sqla->delete ( -from => $table -where => \%conditions, ); Named parameters to the C method are just syntactic sugar for better readability of the client's code; they are passed verbatim to the parent method. =head2 table_alias my $sql = $sqla->table_alias($table_name, $alias); Returns the SQL fragment for aliasing a table. If C<$alias> is empty, just returns C<$table_name>. =head2 column_alias Like C, but for column aliasing. =head2 limit_offset ($sql, @bind) = $sqla->limit_offset($limit, $offset); Generates C<($sql, @bind)> for a LIMIT-OFFSET clause. =head2 join my $join_info = $sqla->join( ... ); my $sth = $dbh->prepare($join_info->{sql}); $sth->execute(@{$join_info->{bind}}) while (my ($alias, $aliased) = each %{$join_info->{aliased_tables}}) { say "$alias is an alias for table $aliased"; } Generates join information for a JOIN clause, taking as input a collection of joined tables with their join conditions. The following example gives an idea of the available syntax : ($sql, @bind) = $sqla->join(qw[ Table1|t1 ab=cd Table2|t2 <=>{ef>gh,ij{t1.mn=op} Table4 ]); This will generate Table1 AS t1 INNER JOIN Table2 AS t2 ON t1.ab=t2.cd INNER JOIN Table3 ON t2.ef>Table3.gh AND t2.ij should be a list containing an odd number of elements, where the odd positions are I and the even positions are I. =head3 Table specifications A table specification for join is a string containing the table name, possibly followed by a vertical bar and an alias name. For example C or C are valid table specifications. These are converted into internal hashrefs with keys C, C, C, C, like this : { sql => "Table1 AS t1" bind => [], name => "t1" aliased_tables => {"t1" => "Table1"} } Such hashrefs can be passed directly as arguments, instead of the simple string representation. =head3 Join specifications A join specification is a string containing an optional I, possibly followed by a pair of curly braces or square brackets containing the I. Default builtin join operators are C<< <=> >>, C<< => >>, C<< <= >>, C<< == >>, corresponding to the following SQL JOIN clauses : '<=>' => '%s INNER JOIN %s ON %s', '=>' => '%s LEFT OUTER JOIN %s ON %s', '<=' => '%s RIGHT JOIN %s ON %s', '==' => '%s NATURAL JOIN %s', This operator table can be overridden through the C parameter of the L method. The join conditions is a comma-separated list of binary column comparisons, like for example {ab=cd,Table1.ef common conventions, if the list of comparisons is within curly braces, it will become an C; if it is within square brackets, it will become an C. Join specifications expressed as strings are converted into internal hashrefs with keys C and C, like this : { operator => '<=>', condition => { '%1$s.ab' => {'=' => {-ident => '%2$s.cd'}}, '%1$s.ef' => {'=' => {-ident => 'Table2.gh'}}}, } The C is a key into the C table; the associated value is a sprinf format string, with placeholders for the left and right operands, and the join condition. The C is a structure suitable for being passed as argument to L. Places where the names of left/right tables (or their aliases) are expected should be expressed as sprintf placeholders, i.e. respectively C<%1$s> and C<%2$s>. In most cases the right-hand side of the condition should B belong to the C<@bind> list, so this is why we need to use the C<-ident> operator from L. Hashrefs for join specifications as shown above can be passed directly as arguments, instead of the simple string representation. =head3 Return value The structure returned by C is a hashref with the following keys : =over =item sql a string containing the generated SQL =item bind an arrayref of bind values =item aliased_tables a hashref where keys are alias names and values are names of aliased tables. =back =head2 merge_conditions my $conditions = $sqla->merge_conditions($cond_A, $cond_B, ...); This utility method takes a list of "C" conditions and merges all of them in a single hashref. For example merging ( {a => 12, b => {">" => 34}}, {b => {"<" => 56}, c => 78} ) produces {a => 12, b => [-and => {">" => 34}, {"<" => 56}], c => 78}); =head2 bind_params $sqla->bind_params($sth, @bind); For each C<$value> in C<@bind>: =over =item * if the value is a scalarref, call $sth->bind_param_inout($index, $value, $INOUT_MAX_LEN) (see L). C<$INOUT_MAX_LEN> defaults to 99, which should be good enough for most uses; should you need another value, you can change it by setting local $SQL::Abstract::More::INOUT_MAX_LEN = $other_value; =item * if the value is an arrayref that matches L, then call the method and arguments returned by L. =item * for all other cases, call $sth->bind_param($index, $value); =back This method is useful either as a convenience for Oracle statements of shape C<"INSERT ... RETURNING ... INTO ..."> (see L method above), or as a way to indicate specific datatypes to the database driver. ==head2 is_bind_value_with_type my ($method, @args) = $sqla->is_bind_value_with_type($value); If C<$value> is a ref to a pair C<< [\%args, $orig_value] >> : =over =item * if C<%args> is of shape C<< {dbd_attrs => \%sql_type} >>, then return C<< ('bind_param', $orig_value, \%sql_type) >>. =item * if C<%args> is of shape C<< {sqlt_size => $num} >>, then return C<< ('bind_param_inout', $orig_value, $num) >>. =back Otherwise, return C<()>. =head1 BIND VALUES WITH TYPES At places where L would expect a plain value, C also accepts a pair, i.e. an arrayref of 2 elements, where the first element is a type specification, and the second element is the value. This is convenient when the DBD driver needs additional information about the values used in the statement. The usual type specification is a hashref C<< {dbd_attrs => \%type} >>, where C<\%type> is passed directly as third argument to L, and therefore is specific to the DBD driver. Another form of type specification is C<< {sqlt_size => $num} >>, where C<$num> will be passed as buffer size to L. Here are some examples ($sql, @bind) = $sqla->insert( -into => 'Foo', -values => {bar => [{dbd_attrs => {ora_type => ORA_XMLTYPE}}]}, ); ($sql, @bind) = $sqla->select( -from => 'Foo', -where => {d_begin => {">" => [{dbd_attrs => {ora_type => ORA_DATE}}, $some_date]}}, ); When using this feature, the C<@bind> array will contain references that cannot be passed directly to L methods; so you should use L from the present module to perform the appropriate bindings before executing the statement. =head1 TODO Future versions may include some of these features : =over =item * support for C initial clauses, and C. =item * support for Oracle-specific syntax for recursive queries (START_WITH, PRIOR, CONNECT_BY NOCYCLE, CONNECT SIBLINGS, etc.) =item * support for INSERT variants INSERT .. DEFAULT VALUES INSERT .. VALUES(), VALUES() =item * support for MySQL C =item * new constructor option ->new(..., select_implicitly_for => $string, ...) This would provide a default values for the C<-for> parameter. =back =head1 AUTHOR Laurent Dami, C<< >> =head1 BUGS Please report any bugs or feature requests to C, or through the web interface at L. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. =head1 SUPPORT You can find documentation for this module with the perldoc command. perldoc SQL::Abstract::More You can also look for information at: =over 4 =item RT: CPAN's request tracker L =item AnnoCPAN: Annotated CPAN documentation L =item CPAN Ratings L =item MetaCPAN L =back =head1 LICENSE AND COPYRIGHT Copyright 2011, 2012 Laurent Dami. This program is free software; you can redistribute it and/or modify it under the terms of either: the GNU General Public License as published by the Free Software Foundation; or the Artistic License. See http://dev.perl.org/licenses/ for more information. =cut SQL-Abstract-More-1.17/t000755000000000000 012173130603 15330 5ustar00unknownunknown000000000000SQL-Abstract-More-1.17/t/01-sql_abstract_more.t000444000000000000 3715412172003241 21622 0ustar00unknownunknown000000000000use strict; use warnings; no warnings 'qw'; use SQL::Abstract::More; use Test::More; use SQL::Abstract::Test import => [qw/is_same_sql_bind/]; use constant N_DBI_MOCK_TESTS => 2; use constant N_BASIC_TESTS => 52; plan tests => (N_BASIC_TESTS + N_DBI_MOCK_TESTS); diag( "Testing SQL::Abstract::More $SQL::Abstract::More::VERSION, Perl $], $^X" ); my $sqla = SQL::Abstract::More->new; my ($sql, @bind, $join); #---------------------------------------------------------------------- # various forms of select() #---------------------------------------------------------------------- # old API transmitted to parent ($sql, @bind) = $sqla->select('Foo', 'bar', {bar => {">" => 123}}, ['bar']); is_same_sql_bind( $sql, \@bind, "SELECT bar FROM Foo WHERE bar > ? ORDER BY bar", [123], ); # idem, new API ($sql, @bind) = $sqla->select( -columns => [qw/bar/], -from => 'Foo', -where => {bar => {">" => 123}}, -order_by => ['bar'] ); is_same_sql_bind( $sql, \@bind, "SELECT bar FROM Foo WHERE bar > ? ORDER BY bar", [123], ); # -distinct ($sql, @bind) = $sqla->select( -columns => [-DISTINCT => qw/foo bar/], -from => 'Foo', ); is_same_sql_bind( $sql, \@bind, "SELECT DISTINCT foo, bar FROM Foo", [], ); # other minus signs ($sql, @bind) = $sqla->select( -columns => [-DISTINCT => -STRAIGHT_JOIN => qw/foo bar/], -from => 'Foo', ); is_same_sql_bind( $sql, \@bind, "SELECT DISTINCT STRAIGHT_JOIN foo, bar FROM Foo", [], ); ($sql, @bind) = $sqla->select( -columns => [-SQL_SMALL_RESULT => qw/foo bar/], -from => 'Foo', ); is_same_sql_bind( $sql, \@bind, "SELECT SQL_SMALL_RESULT foo, bar FROM Foo", [], ); ($sql, @bind) = $sqla->select( -columns => ["-/*+ FIRST_ROWS (100) */" => qw/foo bar/], -from => 'Foo', ); is_same_sql_bind( $sql, \@bind, "SELECT /*+ FIRST_ROWS (100) */ foo, bar FROM Foo", [], ); # -join ($sql, @bind) = $sqla->select( -from => [-join => qw/Foo fk=pk Bar/] ); is_same_sql_bind( $sql, \@bind, "SELECT * FROM Foo INNER JOIN Bar ON Foo.fk=Bar.pk", [], ); # set operators ($sql, @bind) = $sqla->select( -columns => [qw/col1 col2/], -from => 'Foo', -where => {col1 => 123}, -intersect => [ -columns => [qw/col3 col4/], -from => 'Bar', -where => {col3 => 456}, ], ); is_same_sql_bind( $sql, \@bind, "SELECT col1, col2 FROM Foo WHERE col1 = ? " ." INTERSECT SELECT col3, col4 FROM Bar WHERE col3 = ?", [123, 456], ); ($sql, @bind) = $sqla->select( -columns => [qw/col1 col2/], -from => 'Foo', -where => {col1 => 123}, -union_all => [ -where => {col2 => 456}, -union_all => [-columns => [qw/col1 col3/], -where => {col3 => 789}, ], ], -order_by => [qw/col1 col2/], ); is_same_sql_bind( $sql, \@bind, "SELECT col1, col2 FROM Foo WHERE col1 = ? " ." UNION ALL SELECT col1, col2 FROM Foo WHERE col2 = ?" ." UNION ALL SELECT col1, col3 FROM Foo WHERE col3 = ?" ." ORDER BY col1, col2", [123, 456, 789], ); #-order_by ($sql, @bind) = $sqla->select( -from => 'Foo', -order_by => [qw/-foo +bar buz/], ); is_same_sql_bind( $sql, \@bind, "SELECT * FROM Foo ORDER BY foo DESC, bar ASC, buz", [], ); #-group_by / -having ($sql, @bind) = $sqla->select( -columns => [qw/foo SUM(bar)|sum_bar/], -from => 'Foo', -group_by => [qw/foo/], -having => {sum_bar => {">" => 10}}, ); is_same_sql_bind( $sql, \@bind, "SELECT foo, SUM(bar) AS sum_bar FROM Foo GROUP BY foo HAVING sum_bar > ?", [10], ); # NOTE : this test used to be -group_by => [qw/-foo/], generating "GROUP BY foo DESC"; # but this made no sense as SQL. #-limit alone ($sql, @bind) = $sqla->select( -from => 'Foo', -limit => 100 ); is_same_sql_bind( $sql, \@bind, "SELECT * FROM Foo LIMIT ? OFFSET ?", [100, 0], ); #-limit / -offset ($sql, @bind) = $sqla->select( -from => 'Foo', -limit => 100, -offset => 300, ); is_same_sql_bind( $sql, \@bind, "SELECT * FROM Foo LIMIT ? OFFSET ?", [100, 300], ); #-page_size / page_index ($sql, @bind) = $sqla->select( -from => 'Foo', -page_size => 50, -page_index => 2, ); is_same_sql_bind( $sql, \@bind, "SELECT * FROM Foo LIMIT ? OFFSET ?", [50, 50], ); # -for ($sql, @bind) = $sqla->select( -from => 'Foo', -for => "UPDATE", ); is_same_sql_bind( $sql, \@bind, "SELECT * FROM Foo FOR UPDATE", [], ); # -want_details my $details = $sqla->select( -columns => [ qw/f.col1|c1 b.col2|c2 /], -from => [-join => qw/Foo|f fk=pk Bar|b /], -want_details => 1, ); is_same_sql_bind( $details->{sql}, $details->{bind}, "SELECT f.col1 AS c1, b.col2 AS c2 FROM Foo AS f INNER JOIN Bar AS b ON f.fk=b.pk", [], ); is_deeply($details->{aliased_tables}, {f => 'Foo', b => 'Bar'}, "aliased tables"); is_deeply($details->{aliased_columns}, {c1 => 'f.col1', c2 => 'b.col2'}, "aliased columns"); # bind_params with SQL types ($sql, @bind) = $sqla->select( -from => 'Foo', -where => {foo => [{dbd_attrs => {ora_type => 'TEST'}}, 123]}, ); is_same_sql_bind( $sql, \@bind, "SELECT * FROM Foo WHERE foo = ?", [ [{dbd_attrs => {ora_type => 'TEST'}}, 123] ], "SQL type with implicit = operator", ); ($sql, @bind) = $sqla->select( -from => 'Foo', -where => {bar => {"<" => [{dbd_attrs => {pg_type => 999}}, 456]}}, ); is_same_sql_bind( $sql, \@bind, "SELECT * FROM Foo WHERE bar < ?", [ [{dbd_attrs => {pg_type => 999}}, 456] ], "SQL type with explicit operator", ); # should not be interpreted as bind_params with SQL types ($sql, @bind) = $sqla->select( -from => 'Foo', -where => {bar => [{"=" => undef}, {"<" => 'foo'}]} ); is_same_sql_bind( $sql, \@bind, "SELECT * FROM Foo WHERE bar IS NULL OR bar < ?", [ 'foo' ], "OR arrayref pair which is not a value/type pair", ); #---------------------------------------------------------------------- # auxiliary methods : test an instance with standard parameters #---------------------------------------------------------------------- ($sql, @bind) = $sqla->column_alias(qw/Foo f/); is_same_sql_bind( $sql, \@bind, "Foo AS f", [], ); ($sql, @bind) = $sqla->column_alias(qw/Foo/); is_same_sql_bind( $sql, \@bind, "Foo", [], ); ($sql, @bind) = $sqla->table_alias(qw/Foo f/); is_same_sql_bind( $sql, \@bind, "Foo AS f", [], ); ($sql, @bind) = $sqla->limit_offset(123, 456); is_same_sql_bind( $sql, \@bind, "LIMIT ? OFFSET ?", [123, 456] ); $join = $sqla->join(qw[Foo|f =>{fk_A=pk_A,fk_B=pk_B} Bar]); is_same_sql_bind( $join->{sql}, $join->{bind}, "Foo AS f LEFT OUTER JOIN Bar ON f.fk_A = Bar.pk_A AND f.fk_B = Bar.pk_B", [], ); $join = $sqla->join(qw[Foo <=>[A{sql}, $join->{bind}, "Foo INNER JOIN Bar ON Foo.A < Bar.B OR Foo.C < Bar.D", [], ); $join = $sqla->join(qw[Foo == Bar]); is_same_sql_bind( $join->{sql}, $join->{bind}, "Foo NATURAL JOIN Bar", [], ); $join = $sqla->join(qw[Table1|t1 ab=cd Table2|t2 <=>{ef>gh,ij{t1.mn=op} Table4]); is_same_sql_bind( $join->{sql}, $join->{bind}, "Table1 AS t1 INNER JOIN Table2 AS t2 ON t1.ab=t2.cd INNER JOIN Table3 ON t2.ef>Table3.gh AND t2.ijmerge_conditions( {a => 12, b => {">" => 34}}, {b => {"<" => 56}, c => 78}, ); is_deeply($merged, {a => 12, b => [-and => {">" => 34}, {"<" => 56}], c => 78}); #---------------------------------------------------------------------- # test a customized instance #---------------------------------------------------------------------- $sqla = SQL::Abstract::More->new(table_alias => '%1$s %2$s', limit_offset => "LimitXY", sql_dialect => "MsAccess"); $join = $sqla->join(qw[Foo|f =>{fk_A=pk_A,fk_B=pk_B} Bar]); is_same_sql_bind( $join->{sql}, $join->{bind}, "Foo f LEFT OUTER JOIN (Bar) ON f.fk_A = Bar.pk_A AND f.fk_B = Bar.pk_B", [], ); ($sql, @bind) = $sqla->limit_offset(123, 456); is_same_sql_bind( $sql, \@bind, "LIMIT ?, ?", [456, 123] ); $sqla = SQL::Abstract::More->new(sql_dialect => 'Oracle'); ($sql, @bind) = $sqla->select( -columns => [qw/col1|c1 col2|c2/], -from => [-join => qw/Foo|f fk=pk Bar|b/], ); is_same_sql_bind( $sql, \@bind, "SELECT col1 c1, col2 c2 FROM Foo f INNER JOIN Bar b ON f.fk=b.pk", [] ); ($sql, @bind) = $sqla->select( -from => 'Foo', -limit => 10, -offset => 5, ); is_same_sql_bind( $sql, \@bind, "SELECT * FROM (SELECT subq_A.*, ROWNUM rownum__index FROM (SELECT * FROM Foo) subq_A WHERE ROWNUM <= ?) subq_B WHERE rownum__index >= ?", [15, 6], ); #---------------------------------------------------------------------- # method redefinition #---------------------------------------------------------------------- $sqla = SQL::Abstract::More->new( limit_offset => sub { my ($self, $limit, $offset) = @_; defined $limit or die "NO LIMIT!"; $offset ||= 0; my $last = $offset + $limit; return ("ROWS ? TO ?", $offset, $last); # ($sql, @bind) }); ($sql, @bind) = $sqla->limit_offset(123, 456); is_same_sql_bind( $sql, \@bind, "ROWS ? TO ?", [456, 579] ); #---------------------------------------------------------------------- # max_members_IN #---------------------------------------------------------------------- $sqla = SQL::Abstract::More->new( max_members_IN => 10 ); my @vals = (1 .. 35); ($sql, @bind) = $sqla->where({foo => {-in => \@vals}}); is_same_sql_bind( $sql, \@bind, ' WHERE ( ( foo IN ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) ' . ' OR foo IN ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) ' . ' OR foo IN ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) ' . ' OR foo IN ( ?, ?, ?, ?, ?) ) )', [1 .. 35] ); ($sql, @bind) = $sqla->where({foo => {-not_in => \@vals}}); is_same_sql_bind( $sql, \@bind, ' WHERE ( ( foo NOT IN ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) ' . ' AND foo NOT IN ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) ' . ' AND foo NOT IN ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) ' . ' AND foo NOT IN ( ?, ?, ?, ?, ?) ) )', [1 .. 35] ); $sqla = SQL::Abstract::More->new( max_members_IN => 3 ); ($sql, @bind) = $sqla->where({foo => {-in => [1 .. 5]}, bar => {-not_in => [6 .. 10]}}); is_same_sql_bind( $sql, \@bind, ' WHERE ( ( bar NOT IN ( ?, ?, ? ) AND bar NOT IN ( ?, ? ) )' . ' AND ( foo IN ( ?, ?, ? ) OR foo IN ( ?, ? ) ) )', [6 .. 10, 1 .. 5] ); # test old API : passing a plain scalar value to -in ($sql, @bind) = $sqla->where({foo => {-in => 123}}); is_same_sql_bind( $sql, \@bind, ' WHERE ( foo IN (?) )', [123], ); #---------------------------------------------------------------------- # -in with objects #---------------------------------------------------------------------- my $vals = bless [1, 2], 'Array::PseudoScalar'; # doesn't matter if not loaded ($sql, @bind) = $sqla->where({foo => {-in => $vals}, bar => {-not_in => $vals}}); is_same_sql_bind( $sql, \@bind, ' WHERE ( bar NOT IN ( ?, ? ) AND foo IN ( ?, ? ) )', [1, 2, 1, 2], ); #---------------------------------------------------------------------- # insert #---------------------------------------------------------------------- # usual, hashref syntax ($sql, @bind) = $sqla->insert( -into => 'Foo', -values => {foo => 1, bar => 2}, ); is_same_sql_bind( $sql, \@bind, 'INSERT INTO Foo(bar, foo) VALUES (?, ?)', [2, 1], ); # arrayref syntax ($sql, @bind) = $sqla->insert( -into => 'Foo', -values => [1, 2], ); is_same_sql_bind( $sql, \@bind, 'INSERT INTO Foo VALUES (?, ?)', [1, 2], ); # old API ($sql, @bind) = $sqla->insert('Foo', {foo => 1, bar => 2}); is_same_sql_bind( $sql, \@bind, 'INSERT INTO Foo(bar, foo) VALUES (?, ?)', [2, 1], ); ($sql, @bind) = eval {$sqla->insert(-foo => 3); }; ok($@, 'unknown arg to insert()'); # returning ($sql, @bind) = $sqla->insert( -into => 'Foo', -values => {foo => 1, bar => 2}, -returning => 'key', ); is_same_sql_bind( $sql, \@bind, 'INSERT INTO Foo(bar, foo) VALUES (?, ?) RETURNING key', [2, 1], ); ($sql, @bind) = $sqla->insert( -into => 'Foo', -values => {foo => 1, bar => 2}, -returning => [qw/k1 k2/], ); is_same_sql_bind( $sql, \@bind, 'INSERT INTO Foo(bar, foo) VALUES (?, ?) RETURNING k1, k2', [2, 1], ); ($sql, @bind) = $sqla->insert( -into => 'Foo', -values => {foo => 1, bar => 2}, -returning => {k1 => \my $k1, k2 => \my $k2}, ); is_same_sql_bind( $sql, \@bind, 'INSERT INTO Foo(bar, foo) VALUES (?, ?) RETURNING k1, k2 INTO ?, ?', [2, 1, \$k2, \$k1], ); # bind_params SKIP: { eval "use DBD::Mock; 1" or skip "DBD::Mock does not seem to be installed", N_DBI_MOCK_TESTS; { # DIRTY HACK: remote surgery into DBD::Mock::st to compensate for the # missing support for ternary form of bind_param(). require DBD::Mock::st; no warnings 'redefine'; my $orig = \&DBD::Mock::st::bind_param; *DBD::Mock::st::bind_param = sub { my ( $sth, $param_num, $val, $attr ) = @_; $val = [$val, $attr] if $attr; return $sth->$orig($param_num, $val); }; } my $dbh = DBI->connect('DBI:Mock:', '', '', {RaiseError => 1}); my $sth = $dbh->prepare($sql); $sqla->bind_params($sth, @bind); my $mock_params = $sth->{mock_params}; is_deeply($sth->{mock_params}, [2, 1, \$k2, \$k1], "bind_param_inout"); # test 3-args form of bind_param $sth = $dbh->prepare('INSERT INTO Foo(bar, foo) VALUES (?, ?)'); @bind= ([123, {pg_type => 99}], [456, {ora_type => 88}]); $sqla->bind_params($sth, @bind); $mock_params = $sth->{mock_params}; is_deeply($mock_params, \@bind, 'bind_param($val, \%type)'); } #---------------------------------------------------------------------- # update #---------------------------------------------------------------------- # complete syntax ($sql, @bind) = $sqla->update( -table => 'Foo', -set => {foo => 1, bar => 2}, -where => {buz => 3}, ); is_same_sql_bind( $sql, \@bind, 'UPDATE Foo SET bar = ?, foo = ? WHERE buz = ?', [2, 1, 3], ); # without where ($sql, @bind) = $sqla->update( -table => 'Foo', -set => {foo => 1, bar => 2}, ); is_same_sql_bind( $sql, \@bind, 'UPDATE Foo SET bar = ?, foo = ?', [2, 1], ); # old API ($sql, @bind) = $sqla->update('Foo', {foo => 1, bar => 2}, {buz => 3}); is_same_sql_bind( $sql, \@bind, 'UPDATE Foo SET bar = ?, foo = ? WHERE buz = ?', [2, 1, 3], ); #---------------------------------------------------------------------- # delete #---------------------------------------------------------------------- # complete syntax ($sql, @bind) = $sqla->delete( -from => 'Foo', -where => {buz => 3}, ); is_same_sql_bind( $sql, \@bind, 'DELETE FROM Foo WHERE buz = ?', [3], ); # old API ($sql, @bind) = $sqla->delete('Foo', {buz => 3}); is_same_sql_bind( $sql, \@bind, 'DELETE FROM Foo WHERE buz = ?', [3], ); SQL-Abstract-More-1.17/t/02-order-by.t000444000000000000 1024312075351375 17650 0ustar00unknownunknown000000000000use strict; use warnings; use Test::More; use Test::Exception; use SQL::Abstract::More; use SQL::Abstract::Test import => ['is_same_sql_bind']; # This test code is just copied from SQLA, in order to check if all # edge cases are still compatible. my @cases = ( { given => \'colA DESC', expects => ' ORDER BY colA DESC', expects_quoted => ' ORDER BY colA DESC', }, { given => 'colA', expects => ' ORDER BY colA', expects_quoted => ' ORDER BY `colA`', }, { # it may look odd, but this is the desired behaviour (mst) given => 'colA DESC', expects => ' ORDER BY colA DESC', expects_quoted => ' ORDER BY `colA DESC`', }, { given => [qw/colA colB/], expects => ' ORDER BY colA, colB', expects_quoted => ' ORDER BY `colA`, `colB`', }, { # it may look odd, but this is the desired behaviour (mst) given => ['colA ASC', 'colB DESC'], expects => ' ORDER BY colA ASC, colB DESC', expects_quoted => ' ORDER BY `colA ASC`, `colB DESC`', }, { given => {-asc => 'colA'}, expects => ' ORDER BY colA ASC', expects_quoted => ' ORDER BY `colA` ASC', }, { given => {-desc => 'colB'}, expects => ' ORDER BY colB DESC', expects_quoted => ' ORDER BY `colB` DESC', }, { given => [{-asc => 'colA'}, {-desc => 'colB'}], expects => ' ORDER BY colA ASC, colB DESC', expects_quoted => ' ORDER BY `colA` ASC, `colB` DESC', }, { given => ['colA', {-desc => 'colB'}], expects => ' ORDER BY colA, colB DESC', expects_quoted => ' ORDER BY `colA`, `colB` DESC', }, { given => undef, expects => '', expects_quoted => '', }, { given => [{-desc => [ qw/colA colB/ ] }], expects => ' ORDER BY colA DESC, colB DESC', expects_quoted => ' ORDER BY `colA` DESC, `colB` DESC', }, { given => [{-desc => [ qw/colA colB/ ] }, {-asc => 'colC'}], expects => ' ORDER BY colA DESC, colB DESC, colC ASC', expects_quoted => ' ORDER BY `colA` DESC, `colB` DESC, `colC` ASC', }, { given => [{-desc => [ qw/colA colB/ ] }, {-asc => [ qw/colC colD/ ] }], expects => ' ORDER BY colA DESC, colB DESC, colC ASC, colD ASC', expects_quoted => ' ORDER BY `colA` DESC, `colB` DESC, `colC` ASC, `colD` ASC', }, { given => [{-desc => [ qw/colA colB/ ] }, {-desc => 'colC' }], expects => ' ORDER BY colA DESC, colB DESC, colC DESC', expects_quoted => ' ORDER BY `colA` DESC, `colB` DESC, `colC` DESC', }, { given => [{ -asc => 'colA' }, { -desc => [qw/colB/] }, { -asc => [qw/colC colD/] }], expects => ' ORDER BY colA ASC, colB DESC, colC ASC, colD ASC', expects_quoted => ' ORDER BY `colA` ASC, `colB` DESC, `colC` ASC, `colD` ASC', }, { given => { -desc => \['colA LIKE ?', 'test'] }, expects => ' ORDER BY colA LIKE ? DESC', expects_quoted => ' ORDER BY colA LIKE ? DESC', bind => ['test'], }, { given => \['colA LIKE ? DESC', 'test'], expects => ' ORDER BY colA LIKE ? DESC', expects_quoted => ' ORDER BY colA LIKE ? DESC', bind => ['test'], }, { given => [ { -asc => \['colA'] }, { -desc => \['colB LIKE ?', 'test'] }, { -asc => \['colC LIKE ?', 'tost'] }], expects => ' ORDER BY colA ASC, colB LIKE ? DESC, colC LIKE ? ASC', expects_quoted => ' ORDER BY colA ASC, colB LIKE ? DESC, colC LIKE ? ASC', bind => [qw/test tost/], }, ); plan tests => (scalar(@cases) * 2) + 2; my $sql = SQL::Abstract::More->new; my $sqlq = SQL::Abstract::More->new(quote_char => '`'); for my $case( @cases) { my ($stat, @bind); ($stat, @bind) = $sql->_order_by($case->{given}); is_same_sql_bind ( $stat, \@bind, $case->{expects}, $case->{bind} || [], ); ($stat, @bind) = $sqlq->_order_by($case->{given}); is_same_sql_bind ( $stat, \@bind, $case->{expects_quoted}, $case->{bind} || [], ); } throws_ok ( sub { $sql->_order_by({-desc => 'colA', -asc => 'colB' }) }, qr/hash passed .+ must have exactly one key/, 'Undeterministic order exception', ); throws_ok ( sub { $sql->_order_by({-desc => [ qw/colA colB/ ], -asc => [ qw/colC colD/ ] }) }, qr/hash passed .+ must have exactly one key/, 'Undeterministic order exception', ); SQL-Abstract-More-1.17/t/pod.t000444000000000000 35011711661701 16417 0ustar00unknownunknown000000000000#!perl -T use strict; use warnings; use Test::More; # Ensure a recent version of Test::Pod my $min_tp = 1.22; eval "use Test::Pod $min_tp"; plan skip_all => "Test::Pod $min_tp required for testing POD" if $@; all_pod_files_ok(); SQL-Abstract-More-1.17/t/rt_084972.t000444000000000000 235212140641040 17132 0ustar00unknownunknown000000000000use strict; use warnings; use Test::More; use Test::Exception; use SQL::Abstract::More; use SQL::Abstract::Test import => ['eq_sql']; use List::MoreUtils qw/any/; plan tests => 2; my $sqla = SQL::Abstract::More->new; my $result = $sqla->join( 'table', { operator => '=>', condition => { '%1$s.table_id' => {-ident => '%2$s.table_id'}, '%2$s.date' => {'>' => {-ident => '%1$s.date'}}, '%2$s.event_id' => 1}}, 'table_log' ); # we don't know the order of conditions generated by SQL::Abstract; # but unfortunately, SQL::Abstract::Test is not clever enough to apply # commutativity on AND, so we have to do it by hand my @conditions = ( 'table_log.date > table.date', 'table.table_id = table_log.table_id', 'table_log.event_id = ?', ); my @possible_SQL = map {"table LEFT OUTER JOIN table_log ON " . join(' AND ', @$_) } permutations(@conditions); ok (any { eq_sql($result->{sql}, $_) } @possible_SQL); is_deeply ($result->{bind}, [1]); sub permutations { return \@_ if @_ < 2; my @result; for my $i (0 .. $#_) { my @tail = @_; my $head = splice(@tail, $i, 1); push @result, map {[$head, @$_ ]} permutations(@tail); } return @result; } SQL-Abstract-More-1.17/t/rt_086895.t000444000000000000 170612170212317 17146 0ustar00unknownunknown000000000000use strict; use warnings; use Test::More; use Test::Exception; use SQL::Abstract::More; use SQL::Abstract::Test import => ['is_same_sql_bind']; plan tests => 2; my $sqla = SQL::Abstract::More->new(); my ($sql,@bind) = $sqla->select( -from => 't2', -where => {col => {-in => \[$sqla->select( -columns => 'some_key', -from => 't1', -order_by => 'foo', )]}}, -group_by => 'bar', ); is_same_sql_bind ( $sql, \@bind, 'SELECT * FROM t2 WHERE ( col IN ( SELECT some_key FROM t1 ORDER BY foo ) ) ' . 'GROUP BY bar', [], ); ($sql,@bind) = $sqla->select( -from => 't2', -where => {col => {-in => \[$sqla->select( -columns => 'some_key', -from => 't1', -order_by => 'foo', )]}}, -group_by => 'bar', -order_by => 'buz', ); is_same_sql_bind ( $sql, \@bind, 'SELECT * FROM t2 WHERE ( col IN ( SELECT some_key FROM t1 ORDER BY foo ) ) ' . 'GROUP BY bar ORDER BY buz', [], );