Skip to content

Commit

Permalink
fix error at change type of text field to integer in PostgreSQL
Browse files Browse the repository at this point in the history
  • Loading branch information
kaz29 committed Dec 30, 2014
1 parent 5f59b4b commit e5fc185
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
6 changes: 5 additions & 1 deletion lib/Cake/Model/Datasource/Database/Postgres.php
Expand Up @@ -558,7 +558,11 @@ public function alterSchema($compare, $table = null) {
$colList[] = 'ALTER COLUMN ' . $fieldName . ' SET DEFAULT NULL';
$colList[] = 'ALTER COLUMN ' . $fieldName . ' TYPE ' . str_replace(array($fieldName, 'NOT NULL'), '', $this->buildColumn($col)) . ' USING CASE WHEN TRUE THEN 1 ELSE 0 END';
} else {
$colList[] = 'ALTER COLUMN ' . $fieldName . ' TYPE ' . str_replace(array($fieldName, 'NOT NULL'), '', $this->buildColumn($col));
if ($original['type'] === 'text' && $col['type'] === 'integer') {
$colList[] = 'ALTER COLUMN ' . $fieldName . ' TYPE ' . str_replace(array($fieldName, 'NOT NULL'), '', $this->buildColumn($col)) . " USING cast({$fieldName} as INTEGER)";
} else {
$colList[] = 'ALTER COLUMN ' . $fieldName . ' TYPE ' . str_replace(array($fieldName, 'NOT NULL'), '', $this->buildColumn($col));
}
}

if (isset($nullable)) {
Expand Down
28 changes: 28 additions & 0 deletions lib/Cake/Test/Case/Model/Datasource/Database/PostgresTest.php
Expand Up @@ -731,6 +731,34 @@ public function testAlterSchemaBooleanToIntegerField() {
$this->Dbo->query($this->Dbo->dropSchema($Old));
}

/**
* Test the alterSchema changing text to integer
*
* @return void
*/
public function testAlterSchemaTextToIntegerField() {
$default = array(
'connection' => 'test',
'name' => 'TextField',
'text_fields' => array(
'id' => array('type' => 'integer', 'key' => 'primary'),
'name' => array('type' => 'string', 'length' => 50),
'active' => array('type' => 'text', 'null' => false),
)
);
$Old = new CakeSchema($default);
$result = $this->Dbo->query($this->Dbo->createSchema($Old));
$this->assertTrue($result);

$modified = $default;
$modified['text_fields']['active'] = array('type' => 'integer', 'null' => true);

$New = new CakeSchema($modified);
$query = $this->Dbo->alterSchema($New->compare($Old));
$result = $this->Dbo->query($query);
$this->Dbo->query($this->Dbo->dropSchema($Old));
}

/**
* Test the alter index capabilities of postgres
*
Expand Down

0 comments on commit e5fc185

Please sign in to comment.