Skip to content
This repository was archived by the owner on Mar 19, 2021. It is now read-only.

fix decimal scale and precision parsing #67

Merged
merged 2 commits into from
Jun 8, 2018
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
2 changes: 1 addition & 1 deletion lib/sqlitex/row.ex
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ defmodule Sqlitex.Row do
end
defp translate_value({float, "decimal"}), do: Decimal.new(float)
defp translate_value({float, "decimal(" <> rest}) do
[precision, scale] = rest |> string_rstrip(?)) |> String.split(",") |> Enum.map(&String.to_integer/1)
[precision, scale] = rest |> string_rstrip(?)) |> String.split(",") |> Enum.map(&(&1 |> String.trim() |> String.to_integer))
Decimal.with_context %Decimal.Context{precision: precision, rounding: :down}, fn ->
float |> Float.round(scale) |> Float.to_string |> Decimal.new |> Decimal.plus
end
Expand Down
8 changes: 8 additions & 0 deletions test/sqlitex_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,14 @@ defmodule SqlitexTest do
|> Enum.each(fn {res, ans} -> assert Decimal.equal?(res, ans) end)
end

test "decimal types with spaces near scale and precision" do
{:ok, db} = Sqlitex.open(":memory:")
:ok = Sqlitex.exec(db, "CREATE TABLE t (f1 DECIMAL(3,2), f2 DECIMAL(3, 2), f3 DECIMAL( 3 ,2 ))")
{:ok, []} = Sqlitex.query(db, "INSERT INTO t VALUES (?,?,?)", bind: [Decimal.new("1.23"), Decimal.new("4.56"), Decimal.new("7.89")])
[row] = Sqlitex.query!(db, "SELECT f1, f2, f3 FROM t")
assert row == [f1: Decimal.new("1.23"), f2: Decimal.new("4.56"), f3: Decimal.new("7.89")]
end

test "it handles datetime, date, time with empty string" do
{:ok, db} = Sqlitex.open(":memory:")
:ok = Sqlitex.exec(db, "CREATE TABLE t (a datetime NOT NULL, b date NOT NULL, c time NOT NULL)")
Expand Down