diff --git a/src/Db/Table/Column.php b/src/Db/Table/Column.php index c3a0cf3a..eb92f1c2 100644 --- a/src/Db/Table/Column.php +++ b/src/Db/Table/Column.php @@ -9,6 +9,7 @@ namespace Migrations\Db\Table; use Cake\Core\Configure; +use Cake\Database\Expression\QueryExpression; use Migrations\Db\Adapter\AdapterInterface; use Migrations\Db\Adapter\PostgresAdapter; use Migrations\Db\Literal; @@ -814,7 +815,7 @@ public function toArray(): array { $default = $this->getDefault(); if ($default instanceof Literal) { - $default = (string)$default; + $default = new QueryExpression((string)$default); } $type = $this->getType(); diff --git a/tests/TestCase/Db/Adapter/MysqlAdapterTest.php b/tests/TestCase/Db/Adapter/MysqlAdapterTest.php index 5be6d088..457cb225 100644 --- a/tests/TestCase/Db/Adapter/MysqlAdapterTest.php +++ b/tests/TestCase/Db/Adapter/MysqlAdapterTest.php @@ -735,11 +735,14 @@ public function testAddColumnWithDefaultLiteral() { $table = new Table('table1', [], $this->adapter); $table->save(); - $table->addColumn('default_ts', 'timestamp', ['null' => false, 'default' => Literal::from('CURRENT_TIMESTAMP')]) - ->save(); + $table + ->addColumn('default_ts', 'timestamp', ['null' => false, 'default' => Literal::from('CURRENT_TIMESTAMP')]) + ->addColumn('char_default', 'string', ['null' => false, 'default' => Literal::from('"oh hi"')]) + ->save(); $rows = $this->adapter->fetchAll('SHOW COLUMNS FROM table1'); // MariaDB returns current_timestamp() - $this->assertTrue($rows[1]['Default'] === 'CURRENT_TIMESTAMP' || $rows[1]['Default'] === 'current_timestamp()'); + $this->assertContains($rows[1]['Default'], ['CURRENT_TIMESTAMP', 'current_timestamp()']); + $this->assertTrue($rows[2]['Default'] === 'oh hi'); } public function testAddColumnFirst() diff --git a/tests/TestCase/Db/Table/ColumnTest.php b/tests/TestCase/Db/Table/ColumnTest.php index c3a5bf69..b333ee7f 100644 --- a/tests/TestCase/Db/Table/ColumnTest.php +++ b/tests/TestCase/Db/Table/ColumnTest.php @@ -4,6 +4,9 @@ namespace Migrations\Test\TestCase\Db\Table; use Cake\Core\Configure; +use Cake\Database\Expression\QueryExpression; +use Cake\Database\ValueBinder; +use Migrations\Db\Literal; use Migrations\Db\Table\Column; use PHPUnit\Framework\Attributes\RunInSeparateProcess; use PHPUnit\Framework\TestCase; @@ -42,4 +45,15 @@ public function testColumnNullFeatureFlag() $column = new Column(); $this->assertFalse($column->isNull()); } + + public function testToArrayDefaultLiteralValue(): void + { + $column = new Column(); + $column->setName('created') + ->setType('datetime') + ->setDefault(new Literal('CURRENT_TIMESTAMP')); + $result = $column->toArray(); + $this->assertInstanceOf(QueryExpression::class, $result['default']); + $this->assertEquals('CURRENT_TIMESTAMP', $result['default']->sql(new ValueBinder())); + } }