-
-
Notifications
You must be signed in to change notification settings - Fork 400
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Generate migration file to set the default precision for datetime columns in the database
- Loading branch information
1 parent
4e5282a
commit 90bed18
Showing
1 changed file
with
32 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
# frozen_string_literal: true | ||
|
||
class AddPrecisionToTimestamps < ActiveRecord::Migration[7.1] | ||
SKIP_TABLES = [:schema_migrations, :ar_internal_metadata].freeze | ||
|
||
def up | ||
migrate_precision(precision: 6) | ||
end | ||
|
||
def down | ||
migrate_precision(precision: nil) | ||
end | ||
|
||
def migrate_precision(precision:) | ||
table_names = ActiveRecord::Base.connection.tables.map(&:to_sym) | ||
table_names.each do |table| | ||
next if SKIP_TABLES.include?(table) | ||
|
||
ActiveRecord::Base.connection.columns(table).each do |column| | ||
next unless datetime_column?(column) | ||
|
||
change_column(table, column.name, :datetime, precision:) | ||
end | ||
end | ||
end | ||
|
||
private | ||
|
||
def datetime_column?(column) | ||
column.sql_type_metadata.type == :datetime | ||
end | ||
end |