Skip to content

Commit

Permalink
Fix SqliteSchema doesn't handle DEFAULT NULL correctly.
Browse files Browse the repository at this point in the history
  • Loading branch information
chinpei215 authored and ADmad committed Apr 29, 2016
1 parent b87b73c commit 91be4d6
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 3 deletions.
25 changes: 24 additions & 1 deletion src/Database/Schema/SqliteSchema.php
Expand Up @@ -127,7 +127,7 @@ public function convertColumnDescription(Table $table, $row)
$field = $this->_convertColumn($row['type']);
$field += [
'null' => !$row['notnull'],
'default' => $row['dflt_value'] === null ? null : trim($row['dflt_value'], "'"),
'default' => $this->_defaultValue($row['dflt_value']),
];
$primary = $table->constraint('primary');

Expand All @@ -153,6 +153,29 @@ public function convertColumnDescription(Table $table, $row)
}
}

/**
* Manipulate the default value.
*
* Sqlite includes quotes and bared NULLs in default values.
* We need to remove those.
*
* @param string|null $default The default value.
* @return string|null
*/
protected function _defaultValue($default)
{
if ($default === 'NULL') {
return null;
}

// Remove quotes
if (preg_match("/^'(.*)'$/", $default, $matches)) {
return str_replace("''", "'", $matches[1]);
}

return $default;
}

/**
* {@inheritDoc}
*/
Expand Down
24 changes: 22 additions & 2 deletions tests/TestCase/Database/Schema/SqliteSchemaTest.php
Expand Up @@ -221,11 +221,13 @@ protected function _createTables($connection)
$table = <<<SQL
CREATE TABLE schema_articles (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title VARCHAR(20) DEFAULT 'testing',
title VARCHAR(20) DEFAULT 'Let ''em eat cake',
body TEXT,
author_id INT(11) NOT NULL,
published BOOLEAN DEFAULT 0,
created DATETIME,
field1 VARCHAR(10) DEFAULT NULL,
field2 VARCHAR(10) DEFAULT 'NULL',
CONSTRAINT "title_idx" UNIQUE ("title", "body")
CONSTRAINT "author_idx" FOREIGN KEY ("author_id") REFERENCES "schema_authors" ("id") ON UPDATE CASCADE ON DELETE RESTRICT
);
Expand Down Expand Up @@ -288,7 +290,7 @@ public function testDescribeTable()
'title' => [
'type' => 'string',
'null' => true,
'default' => 'testing',
'default' => 'Let \'em eat cake',
'length' => 20,
'precision' => null,
'fixed' => null,
Expand Down Expand Up @@ -328,6 +330,24 @@ public function testDescribeTable()
'precision' => null,
'comment' => null,
],
'field1' => [
'type' => 'string',
'null' => true,
'default' => null,
'length' => 10,
'precision' => null,
'fixed' => null,
'comment' => null,
],
'field2' => [
'type' => 'string',
'null' => true,
'default' => 'NULL',
'length' => 10,
'precision' => null,
'fixed' => null,
'comment' => null,
],
];
$this->assertInstanceOf('Cake\Database\Schema\Table', $result);
$this->assertEquals(['id'], $result->primaryKey());
Expand Down

0 comments on commit 91be4d6

Please sign in to comment.