Pastebin is 300% more awesome when you are logged in. Sign Up, it's FREE!
Guest

ActiveRecord PostgreSQL automatic timestamps

By: a guest on Feb 25th, 2011  |  syntax: Ruby  |  size: 1.88 KB  |  hits: 159  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
This paste has a previous version, view the difference. Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #
  2. # File:  RAILS_APP_ROOT/lib/extensions/postgres_timestamps.rb
  3. #
  4. # What:  Hack up Rails/AR 3 postgresql adapter to do the following:
  5. #
  6. #          1. Always qualify timestamp types WITH TIME ZONE
  7. #          2. Assign DEFAULT CURRENT_TIMESTAMP to created_at, updated_at
  8. #          3. Assign a special updated_at trigger to tables with that column
  9. #
  10. # Note:  XXX This logic assumes that a pg FUNCTION "ar_trg_updated_at()"
  11. #        exists in the target database !!!
  12. #
  13. #        See also http://stackoverflow.com/questions/5098339/activerecord-pg-support-automatic-timestamps-in-ddl
  14. #
  15. #  How:  This file is require'd in "config/environment.rb" if and only
  16. #        if our connection class' ADAPTER_NAME == 'PostgreSQL'
  17. #
  18.  
  19. module ActiveRecord
  20.   module ConnectionAdapters
  21.  
  22.     class PostgreSQLAdapter
  23.       [:datetime, :timestamp].each do |type|
  24.         NATIVE_DATABASE_TYPES[type] = 'TIMESTAMP WITH TIME ZONE'
  25.       end
  26.     end
  27.  
  28.     class ColumnDefinition
  29.       alias :original_to_sql :to_sql
  30.       def to_sql
  31.         if ['created_at', 'updated_at'].include?(name.to_s)
  32.           "#{base.quote_column_name(name)} #{sql_type} DEFAULT CURRENT_TIMESTAMP"
  33.         else
  34.           original_to_sql
  35.         end
  36.       end
  37.     end
  38.  
  39.     module SchemaStatements
  40.       alias :original_create_table :create_table
  41.       def create_table(table_name, options = {})
  42.         block = Proc.new rescue Proc.new {|*args| }
  43.         ret = original_create_table(table_name, options, &block)
  44.         if column_exists?(table_name, :updated_at)
  45.           execute <<-eotrigger
  46.             CREATE TRIGGER ar_trg_updated_at
  47.                     BEFORE UPDATE
  48.                         ON #{quote_table_name(table_name)}
  49.               FOR EACH ROW
  50.          EXECUTE PROCEDURE ar_trg_updated_at()
  51.           eotrigger
  52.         end
  53.         ret
  54.       end
  55.     end
  56.  
  57.   end # -- ConnectionAdapters
  58. end # -- ActiveRecord