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

Make set_unique operations respect the contract for old schema versions #118

Merged
merged 3 commits into from
Sep 22, 2023

Conversation

andrew-farries
Copy link
Collaborator

When pg-roll makes a schema change, the contract with the user is that it will leave the old version of schema unchanged.

When the operation to add a UNIQUE constraint was implemented (#53), this contract was not respected. The operation adds a unique index to the existing column, changing the behaviour for users of the old schema.

This PR changes the operation so that it follows a similar pattern to other operations that were implemented later:

  • On Start:
    • Duplicate the column.
    • Add a UNIQUE index concurrently
    • Create up and down triggers to copy values between the old and new columns.
    • Backfill values from the old column into the new using up SQL
  • On Complete
    • Create a unique constraint on the new column using the unique index.
    • Drop the old column
    • Rename the column to its old name.
    • Remove up and down triggers.

Writing correct up SQL for the operation is a little more difficult than for other operations (eg set NOT NULL) as it is up to the user to ensure uniqueness of values. The example migration in this PR appends a random suffix to each value.

Copy link
Member

@exekias exekias left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

awesome to see this!

When setting a column UNIQUE, the `up` sql should ensure that the value
written to the new schema is unique.
It is now possible to insert values that violate the uniqueness
constaint into the old version of the schema.
@andrew-farries andrew-farries force-pushed the copy-and-trigger-for-set-unique-operation branch from 66c217a to 486ec86 Compare September 22, 2023 08:48
@andrew-farries andrew-farries enabled auto-merge (squash) September 22, 2023 08:50
@andrew-farries andrew-farries merged commit f2bb2f9 into main Sep 22, 2023
8 checks passed
@andrew-farries andrew-farries deleted the copy-and-trigger-for-set-unique-operation branch September 22, 2023 08:52
andrew-farries added a commit that referenced this pull request Sep 22, 2023
Follow up to #118 to make the
`down` SQL optional.

When making an existing column unique, the `down` sql is almost always
going to be a simple copy from the new column to the old.
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.

None yet

2 participants