From e41d9687102c19720a4cfdb78c090cd3d7f3803c Mon Sep 17 00:00:00 2001 From: Wojtek Mach Date: Fri, 7 Jun 2024 14:07:54 +0200 Subject: [PATCH] Send parameters with nil type as type `:string` Before this patch we were sending them as type `:binary`: ```elixir Mix.install([ {:tds, "2.3.5"} ]) defmodule Main do def main do {:ok, pid} = Tds.start_link( hostname: "localhost", username: "sa", password: "secret1@A", database: "mix_install_examples", port: 1433, pool_size: 1 ) Tds.query!(pid, "create table #date_test (x date)", []) Tds.query!(pid, "insert into #date_test values (@param1)", [ %Tds.Parameter{name: "@param1", value: nil} ]) # ** (Tds.Error) Implicit conversion from data type varbinary to date is not allowed. Use the CONVERT function to run this query. # above is same as this: Tds.query!(pid, "insert into #date_test values (@param1)", [ %Tds.Parameter{name: "@param1", type: :binary, value: nil} ]) # ** (Tds.Error) Implicit conversion from data type varbinary to date is not allowed. Use the CONVERT function to run this query. # setting the type as :string works: Tds.query!(pid, "insert into #date_test values (@param1)", [ %Tds.Parameter{name: "@param1", type: :string, value: nil} ]) end end Main.main() ``` And so `type: :string` seems like a better default. --- lib/tds/parameter.ex | 2 +- test/elixir_calendar_test.exs | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/lib/tds/parameter.ex b/lib/tds/parameter.ex index 217c303..6de82b1 100644 --- a/lib/tds/parameter.ex +++ b/lib/tds/parameter.ex @@ -84,7 +84,7 @@ defmodule Tds.Parameter do def fix_data_type(%__MODULE__{type: nil, value: nil} = param) do # should fix ecto has_one, on_change :nulify issue where type is not know when ecto # build query/statement for on_chage callback - %{param | type: :binary} + %{param | type: :string} end def fix_data_type(%__MODULE__{value: value} = param) diff --git a/test/elixir_calendar_test.exs b/test/elixir_calendar_test.exs index 05347ea..5760a7e 100644 --- a/test/elixir_calendar_test.exs +++ b/test/elixir_calendar_test.exs @@ -72,6 +72,24 @@ defmodule ElixirCalendarTest do assert [[date]] == query("select @1", [%P{name: "@1", value: date}]) end + test "Elixir.Date insert nil value", context do + :ok = query("CREATE TABLE #date_test (x date)", []) + + :ok = + query("insert into #date_test values (@param1), (@param2)", [ + %Tds.Parameter{ + name: "@param1", + value: ~D[2024-01-01] + }, + %Tds.Parameter{ + name: "@param2", + value: nil + } + ]) + + assert [[~D[2024-01-01]], [nil]] = query("select x from #date_test", []) + end + test "Elixir.NaiveDateTime type", context do # sql server datetime precision is not exacly 3 decimals precise, value is rader # round up to nearest .000, .003, .007. In case of near midnigh day is incremented