Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use new column definition builder #332

Merged
merged 4 commits into from
Dec 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
- Enh #328: Refactor `Schema::normalizeDefaultValue()` method and move it to `ColumnFactory` class (@Tigrov)
- Enh #331: Refactor according to changes #902 in `yiisoft/db` package (@Tigrov)
- Chg #333: Update `QueryBuilder` constructor (@Tigrov)
- Enh #332: Use `ColumnDefinitionBuilder` to generate table column SQL representation (@Tigrov)

## 1.2.0 March 21, 2024

Expand Down
1 change: 1 addition & 0 deletions psalm.xml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
</ignoreFiles>
</projectFiles>
<issueHandlers>
<MixedAssignment errorLevel="suppress" />
<RiskyTruthyFalsyComparison errorLevel="suppress" />
</issueHandlers>
</psalm>
5 changes: 5 additions & 0 deletions src/Column.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use Yiisoft\Db\Expression\Expression;
use Yiisoft\Db\Schema\Builder\AbstractColumn;
use Yiisoft\Db\Schema\Column\StringColumnSchema;

/**
* Provides a convenient way to create column schema for use with {@see Schema} for MSSQL Server.
Expand All @@ -21,6 +22,10 @@
*
* Provides a fluent interface, which means that the methods can be chained together to create a column schema with
* many properties in a single line of code.
*
* @psalm-suppress DeprecatedClass
*
* @deprecated Use {@see StringColumnSchema} or other column classes instead. Will be removed in 2.0.0.
*/
final class Column extends AbstractColumn
{
Expand Down
14 changes: 12 additions & 2 deletions src/Column/ColumnDefinitionBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ final class ColumnDefinitionBuilder extends AbstractColumnDefinitionBuilder
{
protected const AUTO_INCREMENT_KEYWORD = 'IDENTITY';

protected const GENERATE_UUID_EXPRESSION = 'newid()';

protected const TYPES_WITH_SIZE = [
'decimal',
'numeric',
Expand Down Expand Up @@ -49,6 +47,13 @@ public function build(ColumnSchemaInterface $column): string
. $this->buildExtra($column);
}

public function buildAlter(ColumnSchemaInterface $column): string
{
return $this->buildType($column)
. $this->buildNotNull($column)
. $this->buildExtra($column);
}

protected function getDbType(ColumnSchemaInterface $column): string
{
$size = $column->getSize();
Expand Down Expand Up @@ -96,4 +101,9 @@ protected function getDbType(ColumnSchemaInterface $column): string
default => $dbType,
};
}

protected function getDefaultUuidExpression(): string
{
return 'newid()';
}
}
66 changes: 34 additions & 32 deletions src/DDLQueryBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@
use Throwable;
use Yiisoft\Db\Exception\InvalidArgumentException;
use Yiisoft\Db\Exception\NotSupportedException;
use Yiisoft\Db\Expression\Expression;
use Yiisoft\Db\QueryBuilder\AbstractDDLQueryBuilder;
use Yiisoft\Db\Schema\Builder\ColumnInterface;
use Yiisoft\Db\Schema\Column\ColumnSchemaInterface;

use function array_diff;
use function implode;
use function preg_replace;

/**
* Implements a (Data Definition Language) SQL statements for MSSQL Server.
Expand Down Expand Up @@ -51,45 +53,45 @@
/**
* @throws Exception
*/
public function alterColumn(string $table, string $column, ColumnInterface|string $type): string
public function alterColumn(string $table, string $column, ColumnInterface|ColumnSchemaInterface|string $type): string
{
$sqlAfter = [];
$columnName = $this->quoter->quoteColumnName($column);
$tableName = $this->quoter->quoteTableName($table);
$constraintBase = preg_replace('/[^a-z0-9_]/i', '', $table . '_' . $column);
$constraintBase = preg_replace('/\W/', '', $table . '_' . $column);

if ($type instanceof ColumnInterface) {
$type->setFormat('{type}{length}{notnull}{append}');

/** @psalm-var mixed $defaultValue */
$defaultValue = $type->getDefault();
if ($defaultValue !== null || $type->isNotNull() === false) {
$sqlAfter[] = $this->addDefaultValue(
$table,
"DF_{$constraintBase}",
$column,
$defaultValue instanceof Expression ? $defaultValue : new Expression((string)$defaultValue)
);
}

$checkValue = $type->getCheck();
if ($checkValue !== null) {
$sqlAfter[] = "ALTER TABLE {$tableName} ADD CONSTRAINT " .
$this->quoter->quoteColumnName("CK_{$constraintBase}") .
' CHECK (' . ($defaultValue instanceof Expression ? $checkValue : new Expression($checkValue)) . ')';
}

if ($type->isUnique()) {
$sqlAfter[] = "ALTER TABLE {$tableName} ADD CONSTRAINT " . $this->quoter->quoteColumnName("UQ_{$constraintBase}") . " UNIQUE ({$columnName})";
}
$type = $type->asString();

Check warning on line 63 in src/DDLQueryBuilder.php

View check run for this annotation

Codecov / codecov/patch

src/DDLQueryBuilder.php#L63

Added line #L63 was not covered by tests
}

/** @psalm-suppress DeprecatedMethod */
return implode("\n", [
if (is_string($type)) {
$type = $this->schema->getColumnFactory()->fromDefinition($type);
}

$columnDefinitionBuilder = $this->queryBuilder->getColumnDefinitionBuilder();
$statements = [
$this->dropConstraintsForColumn($table, $column, 'D'),
"ALTER TABLE $tableName ALTER COLUMN $columnName {$this->queryBuilder->getColumnType($type)}",
...$sqlAfter,
]);
"ALTER TABLE $tableName ALTER COLUMN $columnName " . $columnDefinitionBuilder->buildAlter($type),
];

if ($type->hasDefaultValue()) {
$defaultValue = $type->dbTypecast($type->getDefaultValue());
$statements[] = $this->addDefaultValue($table, "DF_$constraintBase", $column, $defaultValue);
}

$checkValue = $type->getCheck();
if (!empty($checkValue)) {
$statements[] = "ALTER TABLE $tableName ADD CONSTRAINT "
. $this->quoter->quoteColumnName("CK_$constraintBase")
. " CHECK ($checkValue)";
}

if ($type->isUnique()) {
$statements[] = "ALTER TABLE $tableName ADD CONSTRAINT "
. $this->quoter->quoteColumnName("UQ_$constraintBase")
. " UNIQUE ($columnName)";
}

return implode("\n", $statements);
}

/**
Expand Down
6 changes: 1 addition & 5 deletions src/Schema.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ final class Schema extends AbstractPdoSchema
/** @deprecated Use {@see ColumnBuilder} instead. Will be removed in 2.0. */
public function createColumn(string $type, array|int|string|null $length = null): ColumnInterface
{
/** @psalm-suppress DeprecatedClass */
return new Column($type, $length);
}

Expand Down Expand Up @@ -229,7 +230,6 @@ protected function loadTableSchema(string $name): TableSchemaInterface|null
*/
protected function loadTablePrimaryKey(string $tableName): Constraint|null
{
/** @psalm-var mixed $tablePrimaryKey */
$tablePrimaryKey = $this->loadTableConstraints($tableName, self::PRIMARY_KEY);
return $tablePrimaryKey instanceof Constraint ? $tablePrimaryKey : null;
}
Expand All @@ -247,7 +247,6 @@ protected function loadTablePrimaryKey(string $tableName): Constraint|null
*/
protected function loadTableForeignKeys(string $tableName): array
{
/** @psalm-var mixed $tableForeignKeys */
$tableForeignKeys = $this->loadTableConstraints($tableName, self::FOREIGN_KEYS);
return is_array($tableForeignKeys) ? $tableForeignKeys : [];
}
Expand Down Expand Up @@ -320,7 +319,6 @@ protected function loadTableIndexes(string $tableName): array
*/
protected function loadTableUniques(string $tableName): array
{
/** @psalm-var mixed $tableUniques */
$tableUniques = $this->loadTableConstraints($tableName, self::UNIQUES);
return is_array($tableUniques) ? $tableUniques : [];
}
Expand All @@ -338,7 +336,6 @@ protected function loadTableUniques(string $tableName): array
*/
protected function loadTableChecks(string $tableName): array
{
/** @psalm-var mixed $tableCheck */
$tableCheck = $this->loadTableConstraints($tableName, self::CHECKS);
return is_array($tableCheck) ? $tableCheck : [];
}
Expand All @@ -356,7 +353,6 @@ protected function loadTableChecks(string $tableName): array
*/
protected function loadTableDefaultValues(string $tableName): array
{
/** @psalm-var mixed $tableDefault */
$tableDefault = $this->loadTableConstraints($tableName, self::DEFAULTS);
return is_array($tableDefault) ? $tableDefault : [];
}
Expand Down
8 changes: 0 additions & 8 deletions tests/ColumnSchemaBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,4 @@
final class ColumnSchemaBuilderTest extends CommonColumnSchemaBuilderTest
{
use TestTrait;

/**
* @dataProvider \Yiisoft\Db\Mssql\Tests\Provider\ColumnSchemaBuilderProvider::createColumnTypes()
*/
public function testCreateColumnTypes(string $expected, string $type, ?int $length, array $calls): void
{
parent::testCreateColumnTypes($expected, $type, $length, $calls);
}
}
29 changes: 0 additions & 29 deletions tests/Provider/ColumnSchemaBuilderProvider.php

This file was deleted.

Loading
Loading