activerecord/pg: support automatic timestamps in DDL
Updated (to show code)
I'd like to mimic ActiveRecord's automatic timestamps directly in the database, but without explicitly adding this logic after every migration's create_table()
call.
Here's what I do now:
class开发者_开发知识库 StatusQuo < My::Migration::Subclass
def self.up
create_table :tbl do |t|
... some columns ...
t.timestamps
end
add_default_now(:tbl, :created_at) # ALTER COLUMN ... DEFAULT NOW()
add_default_now(:tbl, :updated_at) # ALTER COLUMN ... DEFAULT NOW()
add_updated_at_trigger(:tbl) # BEFORE UPDATE ON ... trg_updated_at()
end
end
By contrast, here's what I'd like to do:
class Druthers < My::Migration::Subclass
def self.up
create_table :tbl do |t|
... some columns ...
t.timestamps
end
end
end
Is there an easy or recommended way to accomplish this? Using activerecord 3, postgresql 8.4.
Here's the best I could come up with so far, full source here:
In config/environment.rb
check to see if our connection adapter is PostgreSQL. If so, require
a file that does the following:
- Wrap
ColumnDefinition#to_sql
to force defaultsForce "created_at" and "updated_at" to have DEFAULT CURRENT_TIMESTAMP
- Wrap
create_table
to conditionally apply the triggerIf the newly created table has an "updated_at" column, install a trigger referencing a database FUNCTION assumed to exist.
Not pretty (need to have maintain a FUNCTION definition outside of this code) and not complete (change_table
won't handle introducing timestamps properly), but good enough.
精彩评论