-
Notifications
You must be signed in to change notification settings - Fork 64
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Adding new PG extension for auto converting Numeric to Float. Fixes #955
(#958)
- Loading branch information
Showing
4 changed files
with
43 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,10 @@ | ||
require "../spec_helper" | ||
|
||
describe "Custom SQL" do | ||
describe "PG::NumericFloatConverter extension" do | ||
it "converts PG::Numeric to Float64" do | ||
PriceFactory.create(&.in_cents(399).line_item_id(LineItemFactory.create.id)) | ||
CustomPriceQuery.total.should eq(3.99) | ||
end | ||
end | ||
end |
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,20 @@ | ||
class CustomPriceQuery | ||
class Result | ||
include DB::Serializable | ||
|
||
@[DB::Field(converter: PG::NumericFloatConverter)] | ||
property total : Float64 | ||
end | ||
|
||
def self.total : Float64 | ||
query = <<-SQL | ||
SELECT SUM(in_cents) / 100.0 AS total | ||
FROM prices | ||
SQL | ||
|
||
# Using `query_all` instead of scalar in order to map to | ||
# the `CustomPriceQuery::Result` object instead of straight to Float64 | ||
result = TestDatabase.query_all(query, as: CustomPriceQuery::Result).first | ||
result.total | ||
end | ||
end |
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
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,12 @@ | ||
# Extends the PG shard and adds a converter for | ||
# converting `PG::Numeric` columns to `Float64`. This | ||
# can be used with raw SQL queries. | ||
# ``` | ||
# @[DB::Field(converter: PG::NumericFloatConverter)] | ||
# property average_amount : Float64 | ||
# ``` | ||
module PG::NumericFloatConverter | ||
def self.from_rs(rs : DB::ResultSet) | ||
rs.read(PG::Numeric).to_f | ||
end | ||
end |