i'm wondering if there's way create table statement migration. instead of run rake db:migrate, if can write invoke migration , instead of running or down, able run instead of getting table created, create table statement instead.
something createfootable.up , able specific if want create table statement sqlite or mysql, etc. possible?
these 2 separate questions:
- can generate query string (or set of query strings) migration?
- can select adapter use when running migrations (or generating queries them)?
the short answer both of these "yes, can".
class createfoostable < activerecord::migration def create_table :foo |t| t.int :bar t.string :baz end end end
to answer second question first, can switch adapter changing activerecord configuration used establish connection:
mysql_config = { adapter: "mysql", host: "localhost", username: "myuser", password: "mypass", database: "somedatabase" } sqlite_config = { adapter: "sqlite", database: "path/to/dbfile" } require "db/migrate/20130711000000_create_foos_table.rb" activerecord::base.establish_connection(mysql_config) createfoostable.up # run against mysql activerecord::base.establish_connection(sqlite_config) createfoostable.up # run against sqlite
now first question, how can generate sql instead of executing it?
the simplest way override execute
method output whatever passed in:
# replace 'sqliteadapter' abstractmysqladapter same mysql activerecord::connectionadapters::sqliteadapter.class_eval def execute(sql, name=nil) puts sql end end
running createfoostable.up
should output sql console. if want capture sql strings variable, replace puts sql
whatever logic suits needs.
note while overriding execute
work create_table
, won't job modifying existing tables. because execute
needed determine existing schema before generating modification sql. in case, you're better off aliasing , checking if query starts create
, alter
, or drop
before proceeding.
Comments
Post a Comment