Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding new PG extension for auto converting Numeric to Float. #958

Merged
merged 1 commit into from
Aug 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions spec/avram/custom_sql_spec.cr
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
20 changes: 20 additions & 0 deletions spec/support/queries/custom_price_query.cr
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
1 change: 1 addition & 0 deletions src/avram.cr
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ require "uuid"
require "cadmium_transliterator"

require "./ext/db/*"
require "./ext/pg/*"
require "./avram/object_extensions"
require "./avram/criteria"
require "./avram/type"
Expand Down
12 changes: 12 additions & 0 deletions src/ext/pg/numeric_float_converter.cr
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