Skip to content

Commit b367b78

Browse files
committed
Fix PostgreSQL schema dump for timestamptz
1 parent 0a863c8 commit b367b78

File tree

1 file changed

+36
-5
lines changed

1 file changed

+36
-5
lines changed

config/initializers/active_record_data_types.rb

+36-5
Original file line numberDiff line numberDiff line change
@@ -4,20 +4,51 @@
44
if Gitlab::Database.postgresql?
55
require 'active_record/connection_adapters/postgresql_adapter'
66

7-
module ActiveRecord
8-
module ConnectionAdapters
9-
class PostgreSQLAdapter
10-
NATIVE_DATABASE_TYPES.merge!(datetime_with_timezone: { name: 'timestamptz' })
7+
module ActiveRecord::ConnectionAdapters::PostgreSQL::OID
8+
# Add the class `DateTimeWithTimeZone` so we can map `timestamptz` to it.
9+
class DateTimeWithTimeZone < DateTime
10+
def type
11+
:datetime_with_timezone
12+
end
13+
end
14+
end
15+
16+
module RegisterDateTimeWithTimeZone
17+
# Run original `initialize_type_map` and then register `timestamptz` as a
18+
# `DateTimeWithTimeZone`.
19+
#
20+
# Apparently it does not matter that the original `initialize_type_map`
21+
# aliases `timestamptz` to `timestamp`.
22+
#
23+
# When schema dumping, `timestamptz` columns will be output as
24+
# `t.datetime_with_timezone`.
25+
def initialize_type_map(mapping)
26+
super mapping
27+
28+
mapping.register_type 'timestamptz' do |_, _, sql_type|
29+
precision = extract_precision(sql_type)
30+
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::OID::DateTimeWithTimeZone.new(precision: precision)
1131
end
1232
end
1333
end
34+
35+
class ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
36+
prepend RegisterDateTimeWithTimeZone
37+
38+
# Add column type `datetime_with_timezone` so we can do this in
39+
# migrations:
40+
#
41+
# add_column(:users, :datetime_with_timezone)
42+
#
43+
NATIVE_DATABASE_TYPES[:datetime_with_timezone] = { name: 'timestamptz' }
44+
end
1445
elsif Gitlab::Database.mysql?
1546
require 'active_record/connection_adapters/mysql2_adapter'
1647

1748
module ActiveRecord
1849
module ConnectionAdapters
1950
class AbstractMysqlAdapter
20-
NATIVE_DATABASE_TYPES.merge!(datetime_with_timezone: { name: 'timestamp' })
51+
NATIVE_DATABASE_TYPES[:datetime_with_timezone] = { name: 'timestamp' }
2152
end
2253
end
2354
end

0 commit comments

Comments
 (0)