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

[Idea] Should add_unique_constraint be considered unsafe? #252

Closed
jdufresne opened this issue Jan 5, 2024 · 3 comments
Closed

[Idea] Should add_unique_constraint be considered unsafe? #252

jdufresne opened this issue Jan 5, 2024 · 3 comments

Comments

@jdufresne
Copy link
Contributor

Rails add_unique_constraint is documented at:

https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/PostgreSQL/SchemaStatements.html#method-i-add_unique_constraint

According to the PostgreSQL documentation at:

https://www.postgresql.org/docs/current/ddl-constraints.html#DDL-CONSTRAINTS-UNIQUE-CONSTRAINTS

Adding a unique constraint will automatically create a unique B-tree index on the column or group of columns listed in the constraint.

This suggests to me that it is just as unsafe as adding a unique index. However, when I use add_unique_constraint, I don't get a warning from strong_migrations like I would for an index.

One advantage of using add_unique_constraint is that it allows making the index deferred.

@ankane ankane closed this as completed in 5844236 Jan 5, 2024
@ankane
Copy link
Owner

ankane commented Jan 5, 2024

Hi @jdufresne, thanks for the suggestion! It does look to be unsafe:

CREATE TABLE t1 (value int);
INSERT INTO t1 SELECT i FROM generate_series(1,10000000) i;
ALTER TABLE t1 ADD CONSTRAINT c1 UNIQUE (value);

but can be made safe with:

CREATE UNIQUE INDEX CONCURRENTLY c1 ON t1 (value);
ALTER TABLE t1 ADD CONSTRAINT c1 UNIQUE USING INDEX c1;

Added a check in the commit above.

@jdufresne
Copy link
Contributor Author

Thanks for the quick response!

@andyatkinson
Copy link

Nice points @jdufresne and examples @ankane for the use of USING with an existing index that was created concurrently 👍

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

No branches or pull requests

3 participants