diff --git a/CHANGELOG.md b/CHANGELOG.md index f2e02afdc..ad0621a3f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## 2.0.0 under development +- Enh #320: Minor refactoring of `DDLQueryBuilder::getColumnDefinition()` method (@Tigrov) +- Bug #320: Change visibility of `DDLQueryBuilder::getColumnDefinition()` method to `private` (@Tigrov) - Enh #321: Implement `SqlParser` and `ExpressionBuilder` driver classes (@Tigrov) ## 1.2.0 March 21, 2024 diff --git a/src/DDLQueryBuilder.php b/src/DDLQueryBuilder.php index 8e3caf176..3dd1687f5 100644 --- a/src/DDLQueryBuilder.php +++ b/src/DDLQueryBuilder.php @@ -10,6 +10,7 @@ use Yiisoft\Db\QueryBuilder\AbstractDDLQueryBuilder; use function preg_match; +use function preg_quote; use function preg_replace; use function trim; @@ -167,27 +168,23 @@ public function renameColumn(string $table, string $oldName, string $newName): s * @param string $table The table name. * @param string $column The column name. * - * @throws Throwable In case when table doesn't contain a column. - * - * @return string The column definition. + * @return string The column definition or empty string in case when schema does not contain the table + * or the table doesn't contain the column. */ - public function getColumnDefinition(string $table, string $column): string + private function getColumnDefinition(string $table, string $column): string { - $result = ''; $sql = $this->schema->getTableSchema($table)?->getCreateSql(); if (empty($sql)) { return ''; } - if (preg_match_all('/^\s*([`"])(.*?)\\1\s+(.*?),?$/m', $sql, $matches) > 0) { - foreach ($matches[2] as $i => $c) { - if ($c === $column) { - $result = $matches[3][$i]; - } - } + $quotedColumn = preg_quote($column, '/'); + + if (preg_match("/^\s*([`\"])$quotedColumn\\1\s+(.*?),?$/m", $sql, $matches) !== 1) { + return ''; } - return $result; + return $matches[2]; } } diff --git a/tests/QueryBuilderTest.php b/tests/QueryBuilderTest.php index 13f7e4d05..3ee7adc93 100644 --- a/tests/QueryBuilderTest.php +++ b/tests/QueryBuilderTest.php @@ -516,7 +516,6 @@ public function testInsertInteger() public function testRenameColumn(): void { $db = $this->getConnection(); - $qb = $db->getQueryBuilder(); $this->assertSame( @@ -525,6 +524,20 @@ public function testRenameColumn(): void SQL, $qb->renameColumn('alpha', 'string_identifier', 'string_identifier_test'), ); + + $this->assertSame( + <<renameColumn('alpha', 'non_exist_column', 'new_column'), + ); + + $this->assertSame( + <<renameColumn('non_exist_table', 'non_exist_column', 'new_column'), + ); } /**