SQL::String
è¯ãæªãã¯ã¾ãå¥ã«ç½®ãã¨ãã¦ã
#!/usr/bin/perl use strict; use warnings; use Data::Dump qw(dump); use Perl6::Say; use SQL::String; sub ss { my ($sql, @params) = @_; SQL::String->new($sql, @params); } my ($country_min_population, $city_min_population) = (50000000, 1000000); my $sub_query = ss(q|SELECT Code FROM Country WHERE Population > ?|, $country_min_population); my $query = q|SELECT ID, Name, CountryCode, District, Population FROM City WHERE CountryCode IN (| . $sub_query . ss(q|) AND Population > ?|, $city_min_population); say dump(+{ sql => $query->sql, params => $query->params_ref, }); __END__ SELECT ID, Name, CountryCode, District, Population FROM City WHERE CountryCode IN (SELECT Code FROM Country WHERE Population > 50000000) AND Population > 1000000;
ãããªã®ãå®è¡ããã¨ã
{ params => [50000000, 1000000], sql => "SELECT ID, Name, CountryCode, District, Population FROM City WHERE CountryCode IN (SELECT Code FROM Country WHERE Population > ?) AND Population > ?", }
ã¨è¨ãæããæå³éãã«åºãã
SQL::String objects ALWAYS evaluate as true, stringify to just the SQL, and act properly in concatination, merging in other parameters in the correct order as expected.
ã¤ã¾ãã¨ãããæååã®ããã«é£çµããå ´åãbind ããçºã®ãã©ã¡ã¼ã¿ãé åºãä¿æãã¦ãã£ã¤ãã¦ããããã¼ã£ã¦äºã
ãã ãæååã®ããã«é£çµããªããã°ãã®ç¹æ§ã¯æ´»ããäºãåºæ¥ãªããå ·ä½çã«ã¯ãã®ã¾ã¾ join ã¨ããã㨠bind ã®ããã®ãã©ã¡ã¼ã¿ããã£é£ã³ã¾ãã
ãªã®ã§ããããªæãã«ãªãã®ããªã
#!/usr/bin/perl use strict; use warnings; use Data::Dump qw(dump); use Perl6::Say; use SQL::String; sub ss { SQL::String->new(@_); } sub sql_list { my @sqls = @_; ss( join(', ' => @sqls), map { UNIVERSAL::isa($_, 'SQL::String') ? $_->params : $_ } @sqls ); } sub args { my @items = @_; ss( substr('?, ' x @items, 0, -2), map { UNIVERSAL::isa($_, 'SQL::String') ? $_->params : $_ } @items ); } sub args_list { '(' . args(@_) . ')'; } sub bulk_insert { my ($table, $columns, @values) = @_; my $sql = ss('INSERT INTO ' . $table . '(' . join(', ', @$columns) . ') VALUES '); $sql .= sql_list(map { args_list(@$_) } @values); $sql; } my $sql = bulk_insert( 'foo', [qw/a b c/], ( [ 0 .. 2 ], [ 3 .. 5 ], [ 5 .. 7 ], ), ); say dump(+{ sql => $sql->sql, params => $sql->params_ref, }); __END__
çµæã¯ãããªæãã
{ params => [0, 1, 2, 3, 4, 5, 5, 6, 7], sql => "INSERT INTO foo(a, b, c) VALUES (?, ?, ?), (?, ?, ?), (?, ?, ?)", }
工夫次第ã§çµæ§ä½¿ããããããï¼ã£ã¦ææ³ã