-
Notifications
You must be signed in to change notification settings - Fork 7
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: PG::Numeric to Float64 field converter
- Loading branch information
Showing
3 changed files
with
64 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
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,24 @@ | ||
require "../../../../spec_helper" | ||
require "../../../../../src/core/model/converters/db/pg/numeric" | ||
|
||
require "pg" | ||
|
||
db = DB.open(ENV["DATABASE_URL"] || raise "No DATABASE_URL is set!") | ||
query_logger = Core::QueryLogger.new(nil) | ||
repo = Repo.new(db, query_logger) | ||
|
||
class PGNumericModel < Core::Model | ||
schema do | ||
table_name "pg_numeric_model" | ||
primary_key :id | ||
field :a_number, Float64, db_converter: Converters::DB::PG::Numeric | ||
end | ||
end | ||
|
||
describe Core::Model::Converters::DB::PG::Numeric do | ||
repo.insert(PGNumericModel.new(a_number: 42.0)) | ||
|
||
it do | ||
repo.query(Query(PGNumericModel).all).first.a_number.should be_a(Float64) | ||
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,34 @@ | ||
require "../converter" | ||
require "pg/numeric" | ||
|
||
module Core | ||
abstract class Model | ||
module Converters::DB | ||
# Allows to represent `PG::Numeric` values as `Float64`s in `Model`s. | ||
# | ||
# ``` | ||
# # SQL: | ||
# # table users | ||
# # column balance NUMERIC(16, 8) | ||
# | ||
# require "core/model/converters/db/pg/numeric" | ||
# | ||
# class User < Core::Model | ||
# schema do | ||
# field :balance, Float64, db_converter: Converters::DB::PG::Numeric | ||
# end | ||
# end | ||
# | ||
# user = repository.query(Query(User).last).first | ||
# user.balance # => 42.0 | ||
# ``` | ||
module PG | ||
class Numeric < Converter(::PG::Numeric) | ||
def self.from_rs(rs) | ||
rs.read(::PG::Numeric | Nil).try &.to_f64 | ||
end | ||
end | ||
end | ||
end | ||
end | ||
end |