# # File: RAILS_APP_ROOT/lib/extensions/postgres_timestamps.rb # # What: Hack up Rails/AR 3 postgresql adapter to do the following: # # 1. Always qualify timestamp types WITH TIME ZONE # 2. Assign DEFAULT CURRENT_TIMESTAMP to created_at, updated_at # 3. Assign a special updated_at trigger to tables with that column # # Note: XXX This logic assumes that a pg FUNCTION "ar_trg_updated_at()" # exists in the target database !!! # # See also http://stackoverflow.com/questions/5098339/activerecord-pg-support-automatic-timestamps-in-ddl # # How: This file is require'd in "config/environment.rb" if and only # if our connection class' ADAPTER_NAME == 'PostgreSQL' # module ActiveRecord module ConnectionAdapters class PostgreSQLAdapter [:datetime, :timestamp].each do |type| NATIVE_DATABASE_TYPES[type] = 'TIMESTAMP WITH TIME ZONE' end end class ColumnDefinition alias :original_to_sql :to_sql def to_sql if ['created_at', 'updated_at'].include?(name.to_s) "#{base.quote_column_name(name)} #{sql_type} DEFAULT CURRENT_TIMESTAMP" else original_to_sql end end end module SchemaStatements alias :original_create_table :create_table def create_table(table_name, options = {}) block = Proc.new rescue Proc.new {|*args| } ret = original_create_table(table_name, options, &block) if column_exists?(table_name, :updated_at) execute <<-eotrigger CREATE TRIGGER ar_trg_updated_at BEFORE UPDATE ON #{quote_table_name(table_name)} FOR EACH ROW EXECUTE PROCEDURE ar_trg_updated_at() eotrigger end ret end end end # -- ConnectionAdapters end # -- ActiveRecord