Skip to content

Commit

Permalink
feat: PG::Numeric to Float64 field converter
Browse files Browse the repository at this point in the history
  • Loading branch information
vladfaust committed Oct 16, 2017
1 parent 4ab3cff commit 3024d49
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
6 changes: 6 additions & 0 deletions spec/migration.sql
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

DROP TABLE IF EXISTS posts;
DROP TABLE IF EXISTS users;
DROP TABLE IF EXISTS pg_numeric_model;

CREATE TABLE users(
id SERIAL PRIMARY KEY,
Expand All @@ -20,3 +21,8 @@ CREATE TABLE posts(
created_at TIMESTAMPTZ NOT NULL,
updated_at TIMESTAMPTZ
);

CREATE TABLE pg_numeric_model(
id SERIAL PRIMARY KEY,
a_number NUMERIC(16, 8)
)
24 changes: 24 additions & 0 deletions spec/model/converters/db/pg/numeric_spec.cr
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
34 changes: 34 additions & 0 deletions src/core/model/converters/db/pg/numeric.cr
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

0 comments on commit 3024d49

Please sign in to comment.