Skip to content

Commit

Permalink
Use matching current timestamp precision on AR 7.0+
Browse files Browse the repository at this point in the history
Starting from Active Record 7.0, the precision of timestamp columns
defaults to 6, where it was previously undefined. MySQL requires that
the precision of the CURRENT_TIMESTAMP default value matches the column
type precision, otherwise it throws errors. So, we make that change.

Fixes #159
  • Loading branch information
janko committed Sep 19, 2022
1 parent 4a080ae commit 7db38af
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## HEAD

* Use matching precision for current timestamp default values in Active Record 7.0+ migrations on MySQL (@janko)

## 1.6.1 (2022-09-19)

* Fix argument error when calling `RodauthMailer` in default configuration (@janko)
Expand Down
14 changes: 12 additions & 2 deletions lib/generators/rodauth/migration_generator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,19 @@ def default_primary_key_type

def current_timestamp
if ActiveRecord.version >= Gem::Version.new("5.0")
%(-> { "CURRENT_TIMESTAMP" })
%(-> { "#{current_timestamp_literal}" })
else
%(OpenStruct.new(quoted_id: "CURRENT_TIMESTAMP"))
%(OpenStruct.new(quoted_id: "#{current_timestamp_literal}"))
end
end

# Active Record 7+ sets default precision to 6 for timestamp columns,
# so we need to ensure we match this when setting the default value.
def current_timestamp_literal
if ActiveRecord.version >= Gem::Version.new("7.0") && activerecord_adapter == "mysql2" && ActiveRecord::Base.connection.supports_datetime_with_precision?
"CURRENT_TIMESTAMP(6)"
else
"CURRENT_TIMESTAMP"
end
end
else # Sequel
Expand Down

0 comments on commit 7db38af

Please sign in to comment.