Skip to content

Commit

Permalink
Send parameters with nil type as type :string
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
wojtekmach committed Jun 7, 2024
1 parent b2ab0c7 commit e41d968
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/tds/parameter.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
18 changes: 18 additions & 0 deletions test/elixir_calendar_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit e41d968

Please sign in to comment.