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

Disallow create_table without primary key #1391

Open
kapcod opened this issue Dec 1, 2024 · 0 comments
Open

Disallow create_table without primary key #1391

kapcod opened this issue Dec 1, 2024 · 0 comments

Comments

@kapcod
Copy link

kapcod commented Dec 1, 2024

Is your feature request related to a problem? Please describe.

Currently Rubocop doesn't check if primary key is defined on the table and before Rails 7.1 there was no documented way of creating custom primary keys, so people used id: :false and later alter_table. However since Rails 7.1 there's a convenient way to define primary keys and it's, IMHO, the most readable and convenient way. Creating tables without primary keys can lead to performance issues and unexpected issues with ActiveRecord behavior. Some people create unique indexes instead, but sometimes make them NULLable by mistake which breaks uniqueness and thus cannot be used as real primary key by the DB.

Describe the solution you'd like

I suggest to create cop that forbids id parameter (including id: false) in favor of primary_key: :my_key to create standard autoincremented bigint called "my_key" or primary_key: [:my_key] to just make one or more keys primary key, assuming they're defined in the table block.
By just disallowing id we ensure there is some primary key because there's no other way to prevent the table from having it.

Describe alternatives you've considered

I considered allowing id: false in the options of create_table but only if inside there's a column with primary_key: true option, or t.primary_key :my_key line, but this seems more complicated relative to just preventing id: false.

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

1 participant