Skip to content

Commit

Permalink
ADOdb pgsql fix: AlterColumnSQL conversion from int to bool
Browse files Browse the repository at this point in the history
When changing type of a column from integer to boolean, PostgreSQL does
not provide implicit type cast, so the library needs to specify it via
USING statement when generating the SQL·

Reverse problem of 3fc6200

This issue exists in ADOdb <= 5.17. Upstream bug report
http://phplens.com/lens/lensforum/msgs.php?id=19204
  • Loading branch information
dregad committed Jun 21, 2012
1 parent 0dfd3f0 commit 8ad7cdb
Showing 1 changed file with 19 additions and 9 deletions.
28 changes: 19 additions & 9 deletions library/adodb/datadict/datadict-postgres.inc.php
Expand Up @@ -204,16 +204,26 @@ function AlterColumnSQL($tabname, $flds, $tableflds='',$tableoptions='')
if (preg_match('/^([^ ]+) .*DEFAULT (\'[^\']+\'|\"[^\"]+\"|[^ ]+)/',$v,$matches)) {
$existing = $this->MetaColumns($tabname);
list(,$colname,$default) = $matches;
$old_coltype = $this->connection->MetaType($existing[strtoupper($colname)]);
$v = preg_replace('/^' . preg_quote($colname) . '\s/', '', $v);
$t = trim(str_replace('DEFAULT '.$default,'',$v));

// Type change from bool to int
if ( $existing[strtoupper($colname)]->type == 'bool' && $t == 'INTEGER' ) {
$sql[] = 'ALTER TABLE '.$tabname.' ALTER COLUMN '.$colname.' DROP DEFAULT';
$sql[] = $alter . $colname . ' TYPE ' . $t . ' USING (' . $colname . '::BOOL)::INT ';
$sql[] = 'ALTER TABLE '.$tabname.' ALTER COLUMN '.$colname.' SET DEFAULT ' . $default;
} else {
$sql[] = $alter . $colname . ' TYPE ' . $t;
$sql[] = 'ALTER TABLE '.$tabname.' ALTER COLUMN '.$colname.' SET DEFAULT ' . $default;
if ( $old_coltype == 'L' && $t == 'INTEGER' ) {
$sql[] = $alter . $colname . ' DROP DEFAULT';
$sql[] = $alter . $colname . " TYPE $t USING ($colname::BOOL)::INT";
$sql[] = $alter . $colname . " SET DEFAULT $default";
}
// Type change from int to bool
else if ( $old_coltype == 'I' && $t == 'BOOLEAN' ) {
$sql[] = $alter . $colname . ' DROP DEFAULT';
$sql[] = $alter . $colname . " TYPE $t USING CASE WHEN $colname = 0 THEN false ELSE true END";
$sql[] = $alter . $colname . " SET DEFAULT " . $this->connection->qstr($default);
}
// Any other column types conversion
else {
$sql[] = $alter . $colname . " TYPE $t";
$sql[] = $alter . $colname . " SET DEFAULT $default";
}
}
else {
Expand All @@ -225,11 +235,11 @@ function AlterColumnSQL($tabname, $flds, $tableflds='',$tableoptions='')

if ($not_null) {
// this does not error out if the column is already not null
$sql[] = 'ALTER TABLE '.$tabname.' ALTER COLUMN '.$colname.' SET NOT NULL';
$sql[] = $alter . $colname . ' SET NOT NULL';
}
if ($set_null) {
// this does not error out if the column is already null
$sql[] = 'ALTER TABLE '.$tabname.' ALTER COLUMN '.$colname.' DROP NOT NULL';
$sql[] = $alter . $colname . ' DROP NOT NULL';
}
}
return $sql;
Expand Down

0 comments on commit 8ad7cdb

Please sign in to comment.