Skip to content

Commit

Permalink
Add ColumnDefinitionBuilder::getDefaultUuidExpression() method
Browse files Browse the repository at this point in the history
  • Loading branch information
Tigrov committed Dec 11, 2024
1 parent 498fb19 commit 33c11f2
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/Column/ColumnDefinitionBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@
use Yiisoft\Db\QueryBuilder\AbstractColumnDefinitionBuilder;
use Yiisoft\Db\Schema\Column\ColumnSchemaInterface;

use function version_compare;

final class ColumnDefinitionBuilder extends AbstractColumnDefinitionBuilder
{
protected const GENERATE_UUID_EXPRESSION = 'gen_random_uuid()';

protected const TYPES_WITH_SIZE = [
'bit',
'bit varying',
Expand Down Expand Up @@ -90,4 +90,16 @@ protected function getDbType(ColumnSchemaInterface $column): string
default => 'varchar',
};
}

protected function getDefaultUuidExpression(): string
{
$serverVersion = $this->queryBuilder->getServerInfo()->getVersion();

if (version_compare($serverVersion, '12', '<')) {
return "uuid_in(overlay(overlay(md5(now()::text || random()::text) placing '4' from 13) placing"
. ' to_hex(floor(4 * random() + 8)::int)::text from 17)::cstring)';

Check warning on line 100 in src/Column/ColumnDefinitionBuilder.php

View check run for this annotation

Codecov / codecov/patch

src/Column/ColumnDefinitionBuilder.php#L99-L100

Added lines #L99 - L100 were not covered by tests
}

return 'gen_random_uuid()';
}
}
14 changes: 14 additions & 0 deletions tests/Provider/QueryBuilderProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Yiisoft\Db\Tests\Support\TraversableObject;

use function array_replace;
use function version_compare;

final class QueryBuilderProvider extends \Yiisoft\Db\Tests\Provider\QueryBuilderProvider
{
Expand Down Expand Up @@ -622,6 +623,19 @@ public static function buildColumnDefinition(): array
$values['scale(2)'][0] = 'numeric(10,2)';
$values['integer(8)->scale(2)'][0] = 'integer';

$db = self::getDb();
$serverVersion = self::getDb()->getServerInfo()->getVersion();
$db->close();

if (version_compare($serverVersion, '12', '<')) {
$uuidExpression = "uuid_in(overlay(overlay(md5(now()::text || random()::text) placing '4' from 13) placing"
. ' to_hex(floor(4 * random() + 8)::int)::text from 17)::cstring)';

$values[PseudoType::UUID_PK][0] = "uuid PRIMARY KEY DEFAULT $uuidExpression";
$values[PseudoType::UUID_PK_SEQ][0] = "uuid PRIMARY KEY DEFAULT $uuidExpression";
$values['uuidPrimaryKey()'][0] = "uuid PRIMARY KEY DEFAULT $uuidExpression";
}

return $values;
}

Expand Down

0 comments on commit 33c11f2

Please sign in to comment.