I want to use Rails migration to determine if there is a primary key.

Asked 1 years ago, Updated 1 years ago, 37 views

I'd like to create a migration where PKs that only exist in production can be created in a different environment.
https://api.rubyonrails.org/classes/ActiveRecord/Migration.html
This feels like PK-related methods are not available in the migration class
Do I have no choice but to hit raw SQL?

I think I can do it with the following SQL just to make it.

The bottleneck is that it already exists in real life. What code should I write to create something if I don't do anything?

class AddPkToApiAccessCounts<ActiveRecord::Migration
  def change
    execute 'ALTER TABLE api_access_counts ADD PRIMARY KEY(`date_string`,`group_id`,`date_time_minutes`)'
  end
end

I'm not going to change it this time, so I wish I could determine if there is a PK or not.
Thank you for your cooperation

ruby-on-rails mysql

2022-09-30 19:43

1 Answers

It's not a pretty method, but I was able to find the string in DDL and judge it.
I would appreciate it if you could point out any better methods or problems.

class AddPkToApiAccessCounts<ActiveRecord::Migration
  def change
    # Create only if PK is not present by retrieving DDL
    pk_statement='PRIMARY KEY(`date_string`,`group_id`,`date_time_minutes`)'
    result=select_one('SHOW CREATE TABLE api_access_counts')
    ddl=result ['Create Table']
    if!ddl.include?(pk_statement)
      execute "ALTER TABLE api_access_counts ADD# {pk_statement}"
    end
  end
end


2022-09-30 19:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.