Skip to content
Open
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
32 changes: 26 additions & 6 deletions lib/ch/query.ex
Original file line number Diff line number Diff line change
Expand Up @@ -347,14 +347,34 @@ defimpl DBConnection.Query, for: Ch.Query do
seconds = div(unix, size)
fractional = rem(unix, size)

IO.iodata_to_binary([
Integer.to_string(seconds),
?.,
String.pad_leading(Integer.to_string(fractional), precision, "0")
])
# Manually add minus sign if fractional is < 0 and seconds isn't already negative.
sign = if fractional < 0 and seconds >= 0, do: [?-], else: []

fractional = abs(fractional)

IO.iodata_to_binary(
sign ++
[
Integer.to_string(seconds),
?.,
String.pad_leading(Integer.to_string(fractional), precision, "0")
]
)

_ ->
dt |> DateTime.to_unix(:second) |> Integer.to_string()
# Padding needed for small values: https://github.com/ClickHouse/ClickHouse/issues/64708
dt = dt |> DateTime.to_unix(:second)

sign = if dt < 0, do: [?-], else: []

IO.iodata_to_binary(
sign ++
[
abs(dt)
|> Integer.to_string()
|> String.pad_leading(5, "0")
]
)
end
end

Expand Down
43 changes: 43 additions & 0 deletions test/ch/query_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,49 @@ defmodule Ch.QueryTest do
# assert [[[1, nil, 3]]] = Ch.query!(conn, "SELECT {$0:Array(integer)}", [[1, nil, 3]], query_options).rows
end

test "encode datetimes close to unix epoch", %{conn: conn, query_options: query_options} do
assert [[~U[1970-01-01 00:00:00Z]]] ==
Ch.query!(
conn,
"SELECT {$0:DateTime('UTC')}",
[~U[1970-01-01 00:00:00Z]],
query_options
).rows

assert [[~U[1970-01-01 00:00:00.001Z]]] ==
Ch.query!(
conn,
"SELECT {$0:DateTime64(3, 'UTC')}",
[~U[1970-01-01 00:00:00.001Z]],
query_options
).rows

assert [[~U[1969-12-31 23:59:59Z]]] ==
Ch.query!(
conn,
"SELECT {$0:DateTime64(0, 'UTC')}",
[~U[1969-12-31 23:59:59Z]],
query_options
).rows

# This is currently blocked on https://github.com/ClickHouse/ClickHouse/issues/96745
# assert [[~U[1969-12-31 23:59:59.500Z]]] ==
# Ch.query!(
# conn,
# "SELECT {$0:DateTime64(3, 'UTC')}",
# [~U[1969-12-31 23:59:59.500Z]],
# query_options
# ).rows

assert [[~U[1969-12-31 23:59:58.500Z]]] ==
Ch.query!(
conn,
"SELECT {$0:DateTime64(3, 'UTC')}",
[~U[1969-12-31 23:59:58.500Z]],
query_options
).rows
end

test "encode network types", %{conn: conn, query_options: query_options} do
# TODO, or wrap in custom struct like in postgrex
# assert [["127.0.0.1/32"]] =
Expand Down