Skip to content

Instantly share code, notes, and snippets.

@hatorikibble
Created November 30, 2015 20:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hatorikibble/6b3d937cd447f617f9a0 to your computer and use it in GitHub Desktop.
Save hatorikibble/6b3d937cd447f617f9a0 to your computer and use it in GitHub Desktop.
Testcase for $dbh->quote_identifier with special column names
#!/usr/bin/env perl
use strict;
use warnings;
use feature 'say';
use DBI;
use File::Temp qw/ tempfile /;
use Test::More tests => 3;
use Try::Tiny;
my ($fh,$dbfile) = tempfile();
my $dbh = DBI->connect( "dbi:SQLite:dbname=$dbfile","","" )
|| die "Cannot create handle: $DBI::errstr\n";
my $badtable = "count";
my $badcolumn = "select";
my $column = "select";
my $table = "count";
my $sth = undef;
my $sql = undef;
my $create_sql = "CREATE TABLE ".$dbh->quote_identifier($badtable).
"( ".$dbh->quote_identifier($badcolumn)." int);";
my $insert_sql = "INSERT INTO ".$dbh->quote_identifier($badtable).
"VALUES(3),(4),(15)";
diag "Population temporary SQLite DB at '$dbfile'";
$dbh->do($create_sql);
$dbh->do($insert_sql);
$sql = "SELECT max(".$dbh->quote($column).") FROM ".$dbh->quote($table);
$sth = $dbh->prepare($sql) or die $sth->errstr;
$sth->execute or die $sth->errstr;
while (my @result = $sth->fetchrow_array()){
is($result[0],15,'$dbh->quote does not work on column names');
}
my $error = 0;
try{
$sql = "SELECT max($column) FROM $table";
$sth = $dbh->prepare($sql) or die;
}catch{
$error = 1;
};
is($error,0,"select without quoting works");
$sql = "SELECT max(".$dbh->quote_identifier($column).") FROM ".$dbh->quote_identifier($table);
$sth = $dbh->prepare($sql) or die $sth->errstr;
$sth->execute or die $sth->errstr;
while (my @result = $sth->fetchrow_array()){
is ($result[0],15,'$dbh->quote_identifier gets the correct max value');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment