Skip to content

A unversal way to work with UUIDsΒ #1152

@samdark

Description

@samdark

Proposed new feature or change

Currently you can't work universally with UUIDs:

<?php

declare(strict_types=1);

namespace App\Migration;

use Yiisoft\Db\Migration\MigrationBuilder;
use Yiisoft\Db\Migration\RevertibleMigrationInterface;

final class M251102141707Page implements RevertibleMigrationInterface
{
    public function up(MigrationBuilder $b): void
    {
        $column = $b->columnBuilder();

        $b->createTable('page', [
            'id' => $column::uuidPrimaryKey(),
            'title' => $column::string()->notNull(),
            'slug' => $column::string()->notNull()->unique(),
            'text' => $column::text()->notNull(),
            'created_at' => $column::dateTime(),
            'updated_at' => $column::dateTime(),
        ]);
    }

    public function down(MigrationBuilder $b): void
    {
        $b->dropTable('page');
    }
}

Creates a proper column for PostgreSQL and MySQL but then if you want to insert UUID, there's no universal way to do so:

$this->connection->createCommand()->insert('{{%page}}', [
            'id' => Uuid::uuid7()->getBytes(), // MySQL
            // 'id' => Uuid::uuid7()->toString(), // PostgreSQL
            'title' => 'title',
            'slug' => 'slug',
            'text' => 'text',
            'created_at' => new DateTimeImmutable(),
            'updated_at' => new DateTimeImmutable(),
        ])->execute();

MySQL accepts bytes and errors with strings. PostgreSQL accepts strings and errors with bytes.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions