Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How might you clone a database table via Rails migration?

I want a migration to create a clone of an existing table by just suffixing the name, including all the indexes from the original table.

So there's a "snapshots" table and I want to create "snapshots_temp" as an exact copy of the table (not the data, just the table schema, but including the indexes).

I could just copy and paste the block out of the schema.rb file and manually rename it.

But I'm not sure by the time this migration is applied if the definition from schema.rb will still be accurate. Another developer might have changed the table and I don't want to have to update my migration script.

So how might I get the schema of the table at runtime? Essentially, how does 'rake schema:dump' reverse engineer the table so I can do the same in my migration? (but changing the table name).

like image 697
Teflon Ted Avatar asked Oct 09 '09 13:10

Teflon Ted


People also ask

How rails db Migrate works?

When you run db:migrate, rails will check a special table in the database which contains the timestamp of the last migration applied to the database. It will then apply all of the migrations with timestamps after that date and update the database table with the timestamp of the last migration.

What is data migration in Rails?

Migrations are a feature of Active Record that allows you to evolve your database schema over time. Rather than write schema modifications in pure SQL, migrations allow you to use a Ruby DSL to describe changes to your tables.

How do I migrate a specific migration in Rails?

To run a specific migration up or down, use db:migrate:up or db:migrate:down . The version number in the above commands is the numeric prefix in the migration's filename. For example, to migrate to the migration 20160515085959_add_name_to_users. rb , you would use 20160515085959 as the version number.


1 Answers

Try doing it with pure SQL. This will do what you want:

CREATE TABLE new_tbl LIKE orig_tbl;
like image 147
zenazn Avatar answered Sep 19 '22 22:09

zenazn