Permalink
Browse files

Fix: Changing boolean to integer for Postgres

  • Loading branch information...
1 parent e5b36f6 commit 59549b7ebef94f16f79f990f23ce2f36d388032e @rchavik rchavik committed Jan 31, 2014
@@ -528,29 +528,41 @@ public function alterSchema($compare, $table = null) {
}
break;
case 'change':
+ $schema = $this->describe($curTable);
foreach ($column as $field => $col) {
if (!isset($col['name'])) {
$col['name'] = $field;
}
+ $original = $schema[$field];
$fieldName = $this->name($field);
$default = isset($col['default']) ? $col['default'] : null;
$nullable = isset($col['null']) ? $col['null'] : null;
+ $boolToInt = $original['type'] == 'boolean' && $col['type'] == 'integer';
unset($col['default'], $col['null']);
if ($field !== $col['name']) {
$newName = $this->name($col['name']);
$out .= "\tRENAME {$fieldName} TO {$newName};\n";
$out .= 'ALTER TABLE ' . $this->fullTableName($curTable) . " \n";
$fieldName = $newName;
}
- $colList[] = 'ALTER COLUMN ' . $fieldName . ' TYPE ' . str_replace(array($fieldName, 'NOT NULL'), '', $this->buildColumn($col));
+
+ if ($boolToInt) {
+ $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 (isset($nullable)) {
$nullable = ($nullable) ? 'DROP NOT NULL' : 'SET NOT NULL';
$colList[] = 'ALTER COLUMN ' . $fieldName . ' ' . $nullable;
}
if (isset($default)) {
- $colList[] = 'ALTER COLUMN ' . $fieldName . ' SET DEFAULT ' . $this->value($default, $col['type']);
+ if (!$boolToInt) {
+ $colList[] = 'ALTER COLUMN ' . $fieldName . ' SET DEFAULT ' . $this->value($default, $col['type']);
+ }
} else {
$colList[] = 'ALTER COLUMN ' . $fieldName . ' DROP DEFAULT';
}
@@ -696,6 +696,34 @@ public function testAlterSchema() {
}
/**
+ * Test the alterSchema changing boolean to integer
+ *
+ * @return void
+ */
+ public function testAlterSchemaBooleanToIntegerField() {
+ $default = array(
+ 'connection' => 'test',
+ 'name' => 'BoolField',
+ 'bool_fields' => array(
+ 'id' => array('type' => 'integer', 'key' => 'primary'),
+ 'name' => array('type' => 'string', 'length' => 50),
+ 'active' => array('type' => 'boolean', 'null' => false),
+ )
+ );
+ $Old = new CakeSchema($default);
+ $result = $this->Dbo->query($this->Dbo->createSchema($Old));
+ $this->assertTrue($result);
+
+ $modified = $default;
+ $modified['bool_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
*
* @return void

0 comments on commit 59549b7

Please sign in to comment.