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

Add ColumnDefinitionBuilder #282

Merged
merged 9 commits into from
Oct 15, 2024
Merged
Show file tree
Hide file tree
Changes from 8 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
20 changes: 20 additions & 0 deletions src/Column/ColumnBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,26 @@

final class ColumnBuilder extends \Yiisoft\Db\Schema\Column\ColumnBuilder
{
public static function tinyint(int|null $size = 3): ColumnSchemaInterface
{
return parent::tinyint($size);
}

public static function smallint(int|null $size = 5): ColumnSchemaInterface
{
return parent::smallint($size);
}

public static function integer(int|null $size = 10): ColumnSchemaInterface
{
return parent::integer($size);
}

public static function bigint(int|null $size = 20): ColumnSchemaInterface
{
return parent::bigint($size);
}

public static function binary(int|null $size = null): ColumnSchemaInterface
{
return (new BinaryColumnSchema(ColumnType::BINARY))
Expand Down
100 changes: 100 additions & 0 deletions src/Column/ColumnDefinitionBuilder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
<?php

declare(strict_types=1);

namespace Yiisoft\Db\Oracle\Column;

use Yiisoft\Db\Constant\ColumnType;
use Yiisoft\Db\QueryBuilder\AbstractColumnDefinitionBuilder;
use Yiisoft\Db\Schema\Column\ColumnSchemaInterface;

use function ceil;
use function log10;
use function strtoupper;

final class ColumnDefinitionBuilder extends AbstractColumnDefinitionBuilder
{
protected const AUTO_INCREMENT_KEYWORD = 'GENERATED BY DEFAULT AS IDENTITY';

protected const GENERATE_UUID_EXPRESSION = 'sys_guid()';

protected const TYPES_WITH_SIZE = [
'varchar2',
'nvarchar2',
'number',
'float',
'timestamp',
'interval day(0) to second',
'raw',
'urowid',
'char',
'nchar',
];

protected const TYPES_WITH_SCALE = [
'number',
];

public function build(ColumnSchemaInterface $column): string
{
return $this->buildType($column)
. $this->buildAutoIncrement($column)
. $this->buildDefault($column)
. $this->buildPrimaryKey($column)
. $this->buildUnique($column)
. $this->buildNotNull($column)
. $this->buildCheck($column)
. $this->buildReferences($column)
. $this->buildExtra($column);
}

protected function buildOnDelete(string $onDelete): string
{
return match ($onDelete = strtoupper($onDelete)) {
'CASCADE',
'SET NULL' => " ON DELETE $onDelete",
default => '',
};
}

protected function buildOnUpdate(string $onUpdate): string
{
return '';
}

protected function getDbType(ColumnSchemaInterface $column): string
{
$size = $column->getSize();

/** @psalm-suppress DocblockTypeContradiction */
return match ($column->getType()) {
ColumnType::BOOLEAN => 'number(1)',
ColumnType::BIT => match (true) {
$size === null => 'number(38)',
$size <= 126 => 'number(' . ceil(log10(2 ** $size)) . ')',
default => 'raw(' . ceil($size / 8) . ')',
},
ColumnType::TINYINT => 'number(' . ($size ?? 3) . ')',
ColumnType::SMALLINT => 'number(' . ($size ?? 5) . ')',
ColumnType::INTEGER => 'number(' . ($size ?? 10) . ')',
ColumnType::BIGINT => 'number(' . ($size ?? 20) . ')',
ColumnType::FLOAT => 'binary_float',
ColumnType::DOUBLE => 'binary_double',
ColumnType::DECIMAL => 'number(' . ($size ?? 10) . ',' . ($column->getScale() ?? 0) . ')',
ColumnType::MONEY => 'number(' . ($size ?? 19) . ',' . ($column->getScale() ?? 4) . ')',
ColumnType::CHAR => 'char',
ColumnType::STRING => 'varchar2',
ColumnType::TEXT => 'clob',
ColumnType::BINARY => 'blob',
ColumnType::UUID => 'raw(16)',
ColumnType::DATETIME => 'timestamp',
ColumnType::TIMESTAMP => 'timestamp',
ColumnType::DATE => 'date',
ColumnType::TIME => 'interval day(0) to second',
ColumnType::ARRAY => 'json',
ColumnType::STRUCTURED => 'json',
ColumnType::JSON => 'json',
default => 'varchar2',
};
}
}
7 changes: 0 additions & 7 deletions src/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,7 @@
use Yiisoft\Db\Exception\InvalidArgumentException;
use Yiisoft\Db\Exception\InvalidCallException;
use Yiisoft\Db\Exception\InvalidConfigException;
use Yiisoft\Db\Oracle\Column\ColumnFactory;
use Yiisoft\Db\QueryBuilder\QueryBuilderInterface;
use Yiisoft\Db\Schema\Column\ColumnFactoryInterface;
use Yiisoft\Db\Schema\QuoterInterface;
use Yiisoft\Db\Schema\SchemaInterface;
use Yiisoft\Db\Transaction\TransactionInterface;
Expand Down Expand Up @@ -49,11 +47,6 @@ public function createTransaction(): TransactionInterface
return new Transaction($this);
}

public function getColumnFactory(): ColumnFactoryInterface
{
return new ColumnFactory();
}

/**
* Override base behaviour to support Oracle sequences.
*
Expand Down
1 change: 1 addition & 0 deletions src/DDLQueryBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ public function addForeignKey(

public function alterColumn(string $table, string $column, ColumnInterface|string $type): string
{
/** @psalm-suppress DeprecatedMethod */
return 'ALTER TABLE '
. $this->quoter->quoteTableName($table)
. ' MODIFY '
Expand Down
5 changes: 4 additions & 1 deletion src/QueryBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use Yiisoft\Db\Constant\ColumnType;
use Yiisoft\Db\Constant\PseudoType;
use Yiisoft\Db\Oracle\Column\ColumnDefinitionBuilder;
use Yiisoft\Db\QueryBuilder\AbstractQueryBuilder;
use Yiisoft\Db\Schema\QuoterInterface;
use Yiisoft\Db\Schema\SchemaInterface;
Expand Down Expand Up @@ -49,6 +50,8 @@ public function __construct(QuoterInterface $quoter, SchemaInterface $schema)
$ddlBuilder = new DDLQueryBuilder($this, $quoter, $schema);
$dmlBuilder = new DMLQueryBuilder($this, $quoter, $schema);
$dqlBuilder = new DQLQueryBuilder($this, $quoter);
parent::__construct($quoter, $schema, $ddlBuilder, $dmlBuilder, $dqlBuilder);
$columnDefinitionBuilder = new ColumnDefinitionBuilder($this);

parent::__construct($quoter, $schema, $ddlBuilder, $dmlBuilder, $dqlBuilder, $columnDefinitionBuilder);
}
}
10 changes: 9 additions & 1 deletion src/Schema.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@
use Yiisoft\Db\Exception\NotSupportedException;
use Yiisoft\Db\Expression\Expression;
use Yiisoft\Db\Helper\DbArrayHelper;
use Yiisoft\Db\Oracle\Column\ColumnFactory;
use Yiisoft\Db\Schema\Builder\ColumnInterface;
use Yiisoft\Db\Schema\Column\ColumnFactoryInterface;
use Yiisoft\Db\Schema\Column\ColumnSchemaInterface;
use Yiisoft\Db\Schema\TableSchemaInterface;

Expand Down Expand Up @@ -71,11 +73,17 @@ public function __construct(protected ConnectionInterface $db, SchemaCache $sche
parent::__construct($db, $schemaCache);
}

/** @deprecated Use {@see ColumnBuilder} instead. Will be removed in 2.0. */
public function createColumn(string $type, array|int|string $length = null): ColumnInterface
{
return new Column($type, $length);
}

public function getColumnFactory(): ColumnFactoryInterface
{
return new ColumnFactory();
}

protected function resolveTableName(string $name): TableSchemaInterface
{
$resolvedName = new TableSchema();
Expand Down Expand Up @@ -418,7 +426,7 @@ protected function getTableSequenceName(string $tableName): string|null
*/
private function loadColumnSchema(array $info): ColumnSchemaInterface
{
$columnFactory = $this->db->getColumnFactory();
$columnFactory = $this->db->getSchema()->getColumnFactory();

$dbType = $info['data_type'];
$column = $columnFactory->fromDbType($dbType, [
Expand Down
8 changes: 0 additions & 8 deletions tests/ConnectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
use Yiisoft\Db\Exception\Exception;
use Yiisoft\Db\Exception\InvalidConfigException;
use Yiisoft\Db\Exception\NotSupportedException;
use Yiisoft\Db\Oracle\Column\ColumnFactory;
use Yiisoft\Db\Oracle\Tests\Support\TestTrait;
use Yiisoft\Db\Tests\Common\CommonConnectionTest;
use Yiisoft\Db\Transaction\TransactionInterface;
Expand Down Expand Up @@ -131,11 +130,4 @@ public function testSerialized(): void
$this->assertEquals(123, $unserialized->createCommand('SELECT 123 FROM DUAL')->queryScalar());
$this->assertNotNull($connection->getPDO());
}

public function testGetColumnFactory(): void
{
$db = $this->getConnection();

$this->assertInstanceOf(ColumnFactory::class, $db->getColumnFactory());
}
}
23 changes: 16 additions & 7 deletions tests/Provider/ColumnBuilderProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,27 @@

namespace Yiisoft\Db\Oracle\Tests\Provider;

use Yiisoft\Db\Constant\ColumnType;
use Yiisoft\Db\Oracle\Column\BinaryColumnSchema;

class ColumnBuilderProvider extends \Yiisoft\Db\Tests\Provider\ColumnBuilderProvider
{
public static function buildingMethods(): array
{
return [
// building method, args, expected instance of, expected type, expected column method results
...parent::buildingMethods(),
['binary', [], BinaryColumnSchema::class, ColumnType::BINARY],
['binary', [8], BinaryColumnSchema::class, ColumnType::BINARY, ['getSize' => 8]],
];
$values = parent::buildingMethods();

$values['primaryKey()'][4]['getSize'] = 10;
$values['primaryKey(false)'][4]['getSize'] = 10;
$values['smallPrimaryKey()'][4]['getSize'] = 5;
$values['smallPrimaryKey(false)'][4]['getSize'] = 5;
$values['bigPrimaryKey()'][4]['getSize'] = 20;
$values['bigPrimaryKey(false)'][4]['getSize'] = 20;
$values['tinyint()'][4]['getSize'] = 3;
$values['smallint()'][4]['getSize'] = 5;
$values['integer()'][4]['getSize'] = 10;
$values['bigint()'][4]['getSize'] = 20;
$values['binary()'][2] = BinaryColumnSchema::class;
$values['binary(8)'][2] = BinaryColumnSchema::class;

return $values;
}
}
104 changes: 104 additions & 0 deletions tests/Provider/QueryBuilderProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@
namespace Yiisoft\Db\Oracle\Tests\Provider;

use Exception;
use Yiisoft\Db\Constant\PseudoType;
use Yiisoft\Db\Constraint\ForeignKeyConstraint;
use Yiisoft\Db\Expression\Expression;
use Yiisoft\Db\Oracle\Column\ColumnBuilder;
use Yiisoft\Db\Oracle\Tests\Support\TestTrait;
use Yiisoft\Db\Query\Query;
use Yiisoft\Db\Tests\Support\DbHelper;
Expand Down Expand Up @@ -235,4 +238,105 @@ public static function upsert(): array

return $upsert;
}

public static function buildColumnDefinition(): array
{
$referenceRestrict = new ForeignKeyConstraint();
$referenceRestrict->foreignColumnNames(['id']);
$referenceRestrict->foreignTableName('ref_table');
$referenceRestrict->onDelete('restrict');

$referenceSetNull = clone $referenceRestrict;
$referenceSetNull->onDelete('set null');

$values = parent::buildColumnDefinition();

$values[PseudoType::PK][0] = 'number(10) GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY';
$values[PseudoType::UPK][0] = 'number(10) GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY';
$values[PseudoType::BIGPK][0] = 'number(20) GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY';
$values[PseudoType::UBIGPK][0] = 'number(20) GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY';
$values[PseudoType::UUID_PK][0] = 'raw(16) DEFAULT sys_guid() PRIMARY KEY';
$values[PseudoType::UUID_PK_SEQ][0] = 'raw(16) DEFAULT sys_guid() PRIMARY KEY';
$values['STRING'][0] = 'varchar2';
$values['STRING(100)'][0] = 'varchar2(100)';
$values['primaryKey()'][0] = 'number(10) GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY';
$values['primaryKey(false)'][0] = 'number(10) PRIMARY KEY';
$values['smallPrimaryKey()'][0] = 'number(5) GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY';
$values['smallPrimaryKey(false)'][0] = 'number(5) PRIMARY KEY';
$values['bigPrimaryKey()'][0] = 'number(20) GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY';
$values['bigPrimaryKey(false)'][0] = 'number(20) PRIMARY KEY';
$values['uuidPrimaryKey()'][0] = 'raw(16) DEFAULT sys_guid() PRIMARY KEY';
$values['uuidPrimaryKey(false)'][0] = 'raw(16) PRIMARY KEY';
$values['boolean()'][0] = 'number(1)';
$values['boolean(100)'][0] = 'number(1)';
$values['bit()'][0] = 'number(38)';
$values['bit(1)'][0] = 'number(1)';
$values['bit(8)'][0] = 'number(3)';
$values['bit(1000)'][0] = 'raw(125)';
$values['tinyint()'][0] = 'number(3)';
$values['tinyint(2)'][0] = 'number(2)';
$values['smallint()'][0] = 'number(5)';
$values['smallint(4)'][0] = 'number(4)';
$values['integer()'][0] = 'number(10)';
$values['integer(8)'][0] = 'number(8)';
$values['bigint()'][0] = 'number(20)';
$values['bigint(15)'][0] = 'number(15)';
$values['float()'][0] = 'binary_float';
$values['float(10)'][0] = 'binary_float';
$values['float(10,2)'][0] = 'binary_float';
$values['double()'][0] = 'binary_double';
$values['double(10)'][0] = 'binary_double';
$values['double(10,2)'][0] = 'binary_double';
$values['decimal()'][0] = 'number(10,0)';
$values['decimal(5)'][0] = 'number(5,0)';
$values['decimal(5,2)'][0] = 'number(5,2)';
$values['decimal(null)'][0] = 'number(10,0)';
$values['money()'][0] = 'number(19,4)';
$values['money(10)'][0] = 'number(10,4)';
$values['money(10,2)'][0] = 'number(10,2)';
$values['money(null)'][0] = 'number(19,4)';
$values['string()'][0] = 'varchar2(255)';
$values['string(100)'][0] = 'varchar2(100)';
$values['string(null)'][0] = 'varchar2';
$values['text()'][0] = 'clob';
$values['text(1000)'][0] = 'clob';
$values['binary()'][0] = 'blob';
$values['binary(1000)'][0] = 'blob';
$values['uuid()'][0] = 'raw(16)';
$values['datetime()'][0] = 'timestamp(0)';
$values['datetime(6)'][0] = 'timestamp(6)';
$values['datetime(null)'][0] = 'timestamp';
$values['time()'][0] = 'interval day(0) to second(0)';
$values['time(6)'][0] = 'interval day(0) to second(6)';
$values['time(null)'][0] = 'interval day(0) to second';
$values["comment('comment')"][0] = 'varchar2(255)';
$values["comment('')"][0] = 'varchar2(255)';
$values['comment(null)'][0] = 'varchar2(255)';
$values["extra('bar')"][0] = 'varchar2(255) bar';
$values["extra('')"][0] = 'varchar2(255)';
$values["check('value > 5')"][0] = 'varchar2(255) CHECK (value > 5)';
$values["check('')"][0] = 'varchar2(255)';
$values['check(null)'][0] = 'varchar2(255)';
$values["defaultValue('value')"][0] = "varchar2(255) DEFAULT 'value'";
$values["defaultValue('')"][0] = "varchar2(255) DEFAULT ''";
$values['defaultValue(null)'][0] = 'varchar2(255)';
$values['defaultValue($expression)'][0] = 'varchar2(255) DEFAULT expression';
$values['notNull()'][0] = 'varchar2(255) NOT NULL';
$values['integer()->primaryKey()'][0] = 'number(10) PRIMARY KEY';
$values["integer()->defaultValue('')"][0] = 'number(10)';
$values['size(10)'][0] = 'varchar2(10)';
$values['unique()'][0] = 'varchar2(255) UNIQUE';
$values['unsigned()'][0] = 'number(10)';
$values['scale(2)'][0] = 'number(10,2)';
$values['integer(8)->scale(2)'][0] = 'number(8)';
$values['reference($reference)'][0] = 'number(10) REFERENCES "ref_table" ("id") ON DELETE CASCADE';
$values['reference($referenceWithSchema)'][0] = 'number(10) REFERENCES "ref_schema"."ref_table" ("id") ON DELETE CASCADE';

return [
...$values,

['number(10) REFERENCES "ref_table" ("id")', ColumnBuilder::integer()->reference($referenceRestrict)],
['number(10) REFERENCES "ref_table" ("id") ON DELETE SET NULL', ColumnBuilder::integer()->reference($referenceSetNull)],
];
}
}
Loading
Loading