Skip to content
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 @@ -65,6 +65,7 @@
- Enh #373: Adapt to `DQLQueryBuilderInterface::buildWithQueries()` signature changes in `yiisoft/db` package (@vjik)
- Chg #378: Throw exception on "unsigned" column usage (@vjik)
- Bug #383: Fix column definition parsing in cases with parentheses (@vjik)
- New #382: Add enumeration column type support (@vjik)

## 1.3.0 March 21, 2024

Expand Down
48 changes: 34 additions & 14 deletions src/Column/ColumnDefinitionBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,16 @@

namespace Yiisoft\Db\Oracle\Column;

use LogicException;
use Yiisoft\Db\Constant\ColumnType;
use Yiisoft\Db\Constant\ReferentialAction;
use Yiisoft\Db\Exception\NotSupportedException;
use Yiisoft\Db\QueryBuilder\AbstractColumnDefinitionBuilder;
use Yiisoft\Db\Schema\Column\ColumnInterface;
use Yiisoft\Db\Schema\Column\EnumColumn;

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

Expand Down Expand Up @@ -61,23 +64,20 @@ protected function buildCheck(ColumnInterface $column): string

if (empty($check)) {
$name = $column->getName();

if (empty($name)) {
return '';
if (!empty($name)) {
$type = $column->getType();
if (in_array($type, [ColumnType::ARRAY, ColumnType::STRUCTURED, ColumnType::JSON], true)) {
return version_compare($this->queryBuilder->getServerInfo()->getVersion(), '21', '<')
? ' CHECK (' . $this->queryBuilder->getQuoter()->quoteSimpleColumnName($name) . ' IS JSON)'
: '';
}
if ($type === ColumnType::BOOLEAN) {
return ' CHECK (' . $this->queryBuilder->getQuoter()->quoteSimpleColumnName($name) . ' IN (0,1))';
}
}

return match ($column->getType()) {
ColumnType::ARRAY, ColumnType::STRUCTURED, ColumnType::JSON
=> version_compare($this->queryBuilder->getServerInfo()->getVersion(), '21', '<')
? ' CHECK (' . $this->queryBuilder->getQuoter()->quoteSimpleColumnName($name) . ' IS JSON)'
: '',
ColumnType::BOOLEAN
=> ' CHECK (' . $this->queryBuilder->getQuoter()->quoteSimpleColumnName($name) . ' IN (0,1))',
default => '',
};
}

return " CHECK ($check)";
return parent::buildCheck($column);
}

protected function buildOnDelete(string $onDelete): string
Expand Down Expand Up @@ -133,6 +133,7 @@ protected function getDbType(ColumnInterface $column): string
=> version_compare($this->queryBuilder->getServerInfo()->getVersion(), '21', '>=')
? 'json'
: 'clob',
ColumnType::ENUM => 'varchar2(' . $this->calcEnumSize($column) . ' BYTE)',
default => 'varchar2',
},
'timestamp with time zone' => 'timestamp' . ($size !== null ? "($size)" : '') . ' with time zone',
Expand All @@ -146,4 +147,23 @@ protected function getDefaultUuidExpression(): string
{
return 'sys_guid()';
}

private function calcEnumSize(ColumnInterface $column): int
{
$size = $column->getSize();
if ($size !== null) {
return $size;
}

if ($column instanceof EnumColumn) {
return max(
array_map(
strlen(...),
$column->getValues(),
),
);
}

throw new LogicException('Cannot calculate enum size. Set the size explicitly or use `EnumColumn` instance.');
}
}
27 changes: 27 additions & 0 deletions src/Schema.php
Original file line number Diff line number Diff line change
Expand Up @@ -457,6 +457,7 @@ private function loadColumn(array $info): ColumnInterface
'size' => $info['size'] !== null ? (int) $info['size'] : null,
'table' => $info['table'],
'unique' => $info['constraint_type'] === 'U',
'values' => $this->tryGetEnumValuesFromCheck($info['column_name'], $info['check']),
];

if ($dbType === 'timestamp with local time zone') {
Expand Down Expand Up @@ -544,4 +545,30 @@ private function loadTableConstraints(string $tableName, string $returnType): ar

return $result[$returnType];
}

/**
* @psalm-return list<string>|null
*/
private function tryGetEnumValuesFromCheck(string $columnName, ?string $check): ?array
{
if ($check === null) {
return null;
}

$quotedColumnName = preg_quote($columnName, '~');
if (!preg_match(
"~^\s*(?:\"$quotedColumnName\"|$quotedColumnName)\s+IN\s*\(\s*(('(?:''|[^'])*')(?:,\s*(?2))*)\s*\)\s*$~i",
$check,
$block,
)) {
return null;
}

preg_match_all("~'((?:''|[^'])*)'~", $block[1], $matches);

return array_map(
static fn($v) => str_replace("''", "'", $v),
$matches[1],
);
}
}
68 changes: 68 additions & 0 deletions tests/Column/EnumColumnTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<?php

declare(strict_types=1);

namespace Yiisoft\Db\Oracle\Tests\Column;

use PHPUnit\Framework\Attributes\TestWith;
use Yiisoft\Db\Oracle\Tests\Support\IntegrationTestTrait;
use Yiisoft\Db\Schema\Column\EnumColumn;
use Yiisoft\Db\Tests\Common\CommonEnumColumnTest;

final class EnumColumnTest extends CommonEnumColumnTest
{
use IntegrationTestTrait;

#[TestWith(['INTEGER CHECK ("status" IN (1, 2, 3))'])]
#[TestWith(["VARCHAR2(10) CHECK (\"status\" != 'abc')"])]
#[TestWith(["VARCHAR2(10) CHECK (\"status\" NOT IN ('a', 'b', 'c'))"])]
#[TestWith(["VARCHAR2(10) CHECK (\"status\" IN ('a', 'b', 'c') OR \"status\" = 'x')"])]
#[TestWith(["VARCHAR2(10) CHECK (\"status\" IN ('a', 'b', 'c') OR \"status\" IN ('x', 'y', 'z'))"])]
public function testNonEnumCheck(string $columnDefinition): void
{
$this->dropTable('test_enum_table');
$this->executeStatements(
<<<SQL
CREATE TABLE "test_enum_table" (
"id" INTEGER,
"status" $columnDefinition
)
SQL,
);

$db = $this->getSharedConnection();
$column = $db->getTableSchema('test_enum_table')->getColumn('status');

$this->assertNotInstanceOf(EnumColumn::class, $column);

$this->dropTable('test_enum_table');
}

protected function createDatabaseObjectsStatements(): array
{
return [
<<<SQL
CREATE TABLE "tbl_enum" (
"id" NUMBER,
"status" NVARCHAR2(8) CHECK ("status" IN ('pending', 'unactive', 'active'))
)
SQL,
];
}

protected function dropDatabaseObjectsStatements(): array
{
return [
<<<SQL
BEGIN
EXECUTE IMMEDIATE 'DROP TABLE "tbl_enum"';
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -942 THEN
RAISE;
END IF;
END;
SQL,
];
}
}
17 changes: 17 additions & 0 deletions tests/Support/IntegrationTestTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,23 @@ protected function parseDump(string $content): array
);
}

protected function dropTable(string $table): void
{
$db = TestConnection::getShared();
$table = $db->getQuoter()->quoteTableName($table);
$sql = <<<SQL
BEGIN
EXECUTE IMMEDIATE 'DROP TABLE $table';
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -942 THEN
RAISE;
END IF;
END;
SQL;
$db->createCommand($sql)->execute();
}

protected function dropView(ConnectionInterface $db, string $view): void
{
$view = $db->getQuoter()->quoteTableName($view);
Expand Down
Loading