Skip to content

Commit 22a0bd8

Browse files
author
Simon Thörnqvist
committed
encode tvp data
1 parent a18f47f commit 22a0bd8

File tree

1 file changed

+31
-4
lines changed

1 file changed

+31
-4
lines changed

lib/tds/types.ex

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -580,7 +580,7 @@ defmodule Tds.Types do
580580
encode_data_type(%{param | type: :datetimeoffset})
581581
end
582582

583-
def encode_tvp_type(%Parameter{value: value} = param) do
583+
def encode_tvp_type(%Parameter{}) do
584584
type = @tds_data_type_tvp
585585
data = <<type>> <> <<0, 0>> <> <<0, 0>> <> <<0, 0>>
586586
{type, data, []}
@@ -974,15 +974,42 @@ defmodule Tds.Types do
974974
def encode_data(@tds_data_type_bigvarbinary = data_type, value, attr)
975975
when is_integer(value),
976976
do: encode_data(data_type, <<value>>, attr)
977-
def encode_data(@tds_data_type_bigvarbinary, nil, _),
977+
def encode_data(@tds_data_type_bigvarbinary, nil, _),
978978
do: <<@tds_plp_null::little-unsigned-64>>
979-
def encode_data(@tds_data_type_bigvarbinary, value, _),
979+
def encode_data(@tds_data_type_bigvarbinary, value, _),
980980
do: <<byte_size(value)::little-unsigned-16>> <> value
981981

982+
@doc """
983+
Data Encoding TVP type
984+
"""
985+
def encode_data(@tds_data_type_tvp, value, _attrs) when is_nil(value),
986+
do: <<0xFF :: little-unsigned-16, 0x00, 0x00 >>
987+
988+
def encode_data(@tds_data_type_tvp, %{columns: columns, rows: rows}, _attrs) do
989+
column_length = <<length(columns) :: little-unsigned-16>>
990+
{column_attrs, column_meta} = Enum.reduce(columns, {[], <<>>}, fn (%Parameter{} = param, {attrs, acc_bin}) ->
991+
{bin_type, data, attr} = encode_data_type(param)
992+
bin = acc_bin <> <<0x00 :: little-unsigned-32, 0x00 :: little-unsigned-16 >> <> data <> <<0, 0>>
993+
994+
{[{bin_type, attr} | attrs], bin}
995+
end)
996+
997+
row_data = Enum.reduce(rows, <<>>, fn params ->
998+
column_attrs
999+
|> Enum.zip(params)
1000+
|> Enum.reduce(<<>>, fn ({{type, attr}, param}, acc) ->
1001+
acc <> encode_data(type, param, attr)
1002+
end)
1003+
<< 0x01 >> <> column_attrs
1004+
end)
1005+
1006+
column_length <> column_meta <> <<0x00>> <> row_data <> <<0x00>>
1007+
end
1008+
9821009
@doc """
9831010
Data Encoding String Types
9841011
"""
985-
def encode_data(@tds_data_type_nvarchar, nil, _),
1012+
def encode_data(@tds_data_type_nvarchar, nil, _),
9861013
do: <<@tds_plp_null::little-unsigned-64>>
9871014
def encode_data(@tds_data_type_nvarchar, value, _) do
9881015
value = to_little_ucs2(value)

0 commit comments

Comments
 (0)