Skip to content

Commit

Permalink
Add a Date decoder to the pg adapter to type cast dates
Browse files Browse the repository at this point in the history
at the connection level

Fix rails#51448

Type cast columns of type `date` to ruby `Date` when running a raw
query through `ActiveRecord::Base.connection.select_all`.
  • Loading branch information
JoeDupuis committed Apr 30, 2024
1 parent cc7f0b0 commit 2c88c80
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 0 deletions.
10 changes: 10 additions & 0 deletions activerecord/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
* `PostgreSQLAdapter` now decodes columns of type date to `Date` instead of string.

Ex:
```ruby
ActiveRecord::Base.connection
.select_value("select '2024-01-01'::date").class #=> Date
```

*Joé Dupuis*

* Strict loading using `:n_plus_one_only` does not eagerly load child associations.

With this change, child associations are no longer eagerly loaded, to
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1159,6 +1159,7 @@ def add_pg_decoders
"bool" => PG::TextDecoder::Boolean,
"timestamp" => PG::TextDecoder::TimestampUtc,
"timestamptz" => PG::TextDecoder::TimestampWithTimeZone,
"date" => PG::TextDecoder::Date,
}

known_coder_types = coders_by_name.keys.map { |n| quote(n) }
Expand Down
6 changes: 6 additions & 0 deletions activerecord/test/cases/adapters/postgresql/date_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,10 @@ def test_bc_date_year_zero
topic = Topic.create!(last_read: date)
assert_equal date, Topic.find(topic.id).last_read
end

def test_date_decoder
date = ActiveRecord::Base.connection.select_value("select '2024-01-01'::date")
assert_equal Date.new(2024, 01, 01), date
assert_equal Date, date.class
end
end

0 comments on commit 2c88c80

Please sign in to comment.