Skip to content

Commit

Permalink
Adding new PG extension for auto converting Numeric to Float. Fixes #955
Browse files Browse the repository at this point in the history
 (#958)
  • Loading branch information
jwoertink authored Aug 9, 2023
1 parent 17d8dad commit de8fd95
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 0 deletions.
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

0 comments on commit de8fd95

Please sign in to comment.