Preference for raw SQL in migrations?

I have observed that in a few projects (for larger enterpriseish type
companies) that folks prefer to use raw SQL in the migrations instead
of methods like add_column or create_table.

The con I see in doing this is that your project is less portable,
you’re tied to whatever database you’re using. Not too big a deal I
suppose since most databases use the same syntax to create tables, add
columns, etc.

So then my next though is, if that’s the case then why do it? It
seems less error prone to write ’
add_column :addresses, :first_name, :string’ than the SQL to do the
same thing. It’s also a lot more readable than the SQL statement is.

The one thing I don’t see migrations doing are foreign_key constraints
in the database. I suppose a lot of Rails developers depend on the
ActiveRecord associations and validations to enforce these?

I’m interested in finding out what other folks are doing in terms of
writing migrations.

ncancelliere wrote:

I have observed that in a few projects (for larger enterpriseish type
companies) that folks prefer to use raw SQL in the migrations instead
of methods like add_column or create_table.

I have seen that too. I believe that is due to not understanding the
best practices for dealing with migrations.

For example, one argument I have seen for writing SQL migrations is that
they will be more resistant to future changes in the model object.
That’s true, but if you’re running old migrations, generally something
else is wrong (that’s what rake db:schema:load is for).

The con I see in doing this is that your project is less portable,

I agree. More than a line or two of SQL in a migration is generally not
a great idea, I think.
[…]

So then my next though is, if that’s the case then why do it?

See above.

[…]

The one thing I don’t see migrations doing are foreign_key constraints
in the database.

Then you haven’t looked hard enough. :slight_smile: See
http://github.com/harukizaemon/foreign_key_migrations . I use this on
all my projects, and at some point I hope to patch it so it also deals
with check constraints.

I suppose a lot of Rails developers depend on the
ActiveRecord associations and validations to enforce these?

Probably. But the good Rails developers know better. :smiley:

I’m interested in finding out what other folks are doing in terms of
writing migrations.

Well, that’s what I think…

Best,

Marnen Laibow-Koser
http://www.marnen.org
[email protected]

Thank you so much for the thoughtful reply. I will check out that
plugin/gem you linked to.

Cheers,
Nicholas

On Jun 14, 8:58 am, Marnen Laibow-Koser <rails-mailing-l…@andreas-