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

[Proposal]: Make all reference constraints deferrable #42

Closed
volkanunsal opened this issue Apr 10, 2018 · 4 comments
Closed

[Proposal]: Make all reference constraints deferrable #42

volkanunsal opened this issue Apr 10, 2018 · 4 comments

Comments

@volkanunsal
Copy link

volkanunsal commented Apr 10, 2018

The foreign key constraints often raise issues when moving data, requiring the programmers to remove them to complete the data load tasks. A better approach is to make them deferrable (only in Postgres) and SET CONSTRAINTS ALL DEFERRED; in a transaction block before running your data load script.

The proposed addition would warn the user if the migration includes a non-deferrable foreign_key constraint.

@ankane
Copy link
Owner

ankane commented Apr 11, 2018

Hey @volkanunsal, thanks for the proposal 👍 Can you add an example of a migration that should raise an error, and as well as one that does it properly?

@volkanunsal
Copy link
Author

volkanunsal commented Apr 21, 2018

I don't quite know how to express the correct way of doing it. The way to alter a constraint requires knowing the name of the constraint, but that name is generated by Rails, and not easily accessible to the programmer.

Here is an attempt to show what I mean:

wrong

class AddReferenceToProject < ActiveRecord::Migration[5.1]
  def change
    add_foreign_key :users, :projects
  end
end

right

class AddReferenceToProject < ActiveRecord::Migration[5.1]
  def change
    # Naming our own foreign key. Is there a better way?
    add_foreign_key :users, :projects, name: 'foobar'
    execute("ALTER TABLE users ALTER CONSTRAINT foobar DEFERRABLE INITIALLY IMMEDIATE;")
  end
end

@ankane
Copy link
Owner

ankane commented May 1, 2018

Hey @volkanunsal, thanks for following up. I don't know if this practice is common, so don't think it makes sense to add right now. I'd like to add support for custom rules at some point, which could allow you to create your own warning around this.

@ankane ankane closed this as completed May 1, 2018
@ankane
Copy link
Owner

ankane commented Oct 13, 2018

fwiw, just added a way to write custom checks

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

2 participants