Skip to content

[9.x] Add unique deferrable initially deferred constants for PostgreSQL#44127

Merged
taylorotwell merged 2 commits into
laravel:9.xfrom
markuskooche:9.x
Sep 15, 2022
Merged

[9.x] Add unique deferrable initially deferred constants for PostgreSQL#44127
taylorotwell merged 2 commits into
laravel:9.xfrom
markuskooche:9.x

Conversation

@markuskooche
Copy link
Copy Markdown
Contributor

@markuskooche markuskooche commented Sep 14, 2022

Currently it is not possible to check a unique constraint only after updating.

For this, DEFERRABLE INITIALLY DEFERRED is needed.

create table pictures
(
    id bigserial primary key,
    ...
    constraint pictures_post_id_post_type_sequence_unique
        unique (post_id, post_type, sequence)
            deferrable initially deferred
);

You can easily apply this to a foreign id with the following function:

$table->foreignId('foo')->deferrable();

This works because it is already observed in the foreign id.
https://github.com/laravel/framework/blob/9.x/src/Illuminate/Database/Schema/ForeignKeyDefinition.php#L8-L9

However, not with the UNIQUE Keys.
https://github.com/laravel/framework/blob/9.x/src//Illuminate/Database/Schema/Grammars/PostgresGrammar.php#L146-L160

This problem has already been listed in discussion #40953.

Now you can also put a DEFERRABLE INITIALLY DEFERRED or a DEFERRABLE INITIALLY IMMEDIATE on unique keys.

DEFERRABLE INITIALLY DEFERRED:

$table->unique(['post_id', 'post_type', 'sequence'])
    ->deferrable()
    ->initiallyImmediate(false);

DEFERRABLE INITIALLY IMMEDIATE

$table->unique(['post_id', 'post_type', 'sequence'])
    ->deferrable()
    ->initiallyImmediate();

@markuskooche markuskooche changed the title [9.x] Add unique deferrable initial deferred constants for PostgreSQL [9.x] Add unique deferrable initially deferred constants for PostgreSQL Sep 14, 2022
@taylorotwell taylorotwell merged commit be8f0b0 into laravel:9.x Sep 15, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants