Skip to content

Commit b0eda1d

Browse files
committed
feat(database): autodetect char size by default value
1 parent e19437e commit b0eda1d

2 files changed

Lines changed: 31 additions & 4 deletions

File tree

packages/database/src/QueryStatements/CharStatement.php

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,11 @@ public function __construct(
1919
public function compile(DatabaseDialect $dialect): string
2020
{
2121
return sprintf(
22-
'%s CHAR(%s) %s %s',
22+
'%s CHAR(%s)%s%s',
2323
$dialect->quoteIdentifier($this->name),
24-
$this->size,
25-
$this->default !== null ? "DEFAULT '{$this->default}'" : '',
26-
$this->nullable ? '' : 'NOT NULL',
24+
$this->size === 1 && $this->default !== null ? mb_strlen($this->default) : $this->size,
25+
$this->default !== null ? " DEFAULT '{$this->default}'" : '',
26+
$this->nullable ? '' : ' NOT NULL',
2727
);
2828
}
2929
}

packages/database/tests/QueryStatements/CharStatementTest.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,31 @@ public function test_char(): void
2525
$this->assertSame($expectedMysql, $statement->compile(DatabaseDialect::MYSQL));
2626
$this->assertSame($expectedPgsql, $statement->compile(DatabaseDialect::POSTGRESQL));
2727
}
28+
29+
#[Test]
30+
public function test_determine_char_size(): void
31+
{
32+
$fixedSizeStatement = new CharStatement(
33+
name: 'foo',
34+
size: 10,
35+
);
36+
$expectedMysql = '`foo` CHAR(10) NOT NULL';
37+
$this->assertSame($expectedMysql, $fixedSizeStatement->compile(DatabaseDialect::MYSQL));
38+
39+
$defaultSizeStatement = new CharStatement(
40+
name: 'foo',
41+
size: 1,
42+
default: 'foo_bar',
43+
);
44+
$expectedMysql = '`foo` CHAR(7) DEFAULT \'foo_bar\' NOT NULL';
45+
$this->assertSame($expectedMysql, $defaultSizeStatement->compile(DatabaseDialect::MYSQL));
46+
47+
$fixedAndDefaultSizeStatement = new CharStatement(
48+
name: 'foo',
49+
size: 10,
50+
default: 'foo_bar',
51+
);
52+
$expectedMysql = '`foo` CHAR(10) DEFAULT \'foo_bar\' NOT NULL';
53+
$this->assertSame($expectedMysql, $fixedAndDefaultSizeStatement->compile(DatabaseDialect::MYSQL));
54+
}
2855
}

0 commit comments

Comments
 (0)