如何在 Ecto 片段语句中使用 date_trunc with timezone
How to use date_trunc with timezone in Ecto fragment statement
我正在尝试使用商店的时区查询商店的订单和date_trunc
其inserted_at
。
以下有效。
shop |> Ecto.assoc(:orders) |> select([o], fragment("date_trunc('day', ? at time zone 'America/Los_Angeles')", o.inserted_at)) |> Repo.all
但是当我尝试动态传递时区时,我得到 "could not determine data type of parameter " 错误,即使我明确使用 type
将时区转换为字符串
shop |> Ecto.assoc(:orders) |> select([o], fragment("date_trunc('day', ? at time zone '?')", o.inserted_at, type(^timezone, :string))) |> Repo.all
** (Postgrex.Error) ERROR 42P18 (indeterminate_datatype): could not determine data type of parameter
[debug] QUERY ERROR source="orders" db=1.0ms
SELECT date_trunc('day', o0."inserted_at" at time zone '::varchar') FROM "orders" AS o0 WHERE (o0."shop_id" = ) ["America/Los_Angeles", "QXJnQWw2NWxhS289"]
(ecto) lib/ecto/adapters/sql.ex:436: Ecto.Adapters.SQL.execute_and_cache/7
(ecto) lib/ecto/repo/queryable.ex:130: Ecto.Repo.Queryable.execute/5
(ecto) lib/ecto/repo/queryable.ex:35: Ecto.Repo.Queryable.all/4
这里使用 elixir 1.4.1 和 ecto 2.1.4。
如何正确查询?
提前致谢!
使用 fragment
时,?
周围的 SQL 中不需要引号(并且在修复引号错误后也不需要显式类型转换) :
shop |> Ecto.assoc(:orders) |> select([o], fragment("date_trunc('day', ? at time zone ?)", o.inserted_at, ^timezone)) |> Repo.all
我正在尝试使用商店的时区查询商店的订单和date_trunc
其inserted_at
。
以下有效。
shop |> Ecto.assoc(:orders) |> select([o], fragment("date_trunc('day', ? at time zone 'America/Los_Angeles')", o.inserted_at)) |> Repo.all
但是当我尝试动态传递时区时,我得到 "could not determine data type of parameter " 错误,即使我明确使用 type
将时区转换为字符串
shop |> Ecto.assoc(:orders) |> select([o], fragment("date_trunc('day', ? at time zone '?')", o.inserted_at, type(^timezone, :string))) |> Repo.all
** (Postgrex.Error) ERROR 42P18 (indeterminate_datatype): could not determine data type of parameter
[debug] QUERY ERROR source="orders" db=1.0ms
SELECT date_trunc('day', o0."inserted_at" at time zone '::varchar') FROM "orders" AS o0 WHERE (o0."shop_id" = ) ["America/Los_Angeles", "QXJnQWw2NWxhS289"]
(ecto) lib/ecto/adapters/sql.ex:436: Ecto.Adapters.SQL.execute_and_cache/7
(ecto) lib/ecto/repo/queryable.ex:130: Ecto.Repo.Queryable.execute/5
(ecto) lib/ecto/repo/queryable.ex:35: Ecto.Repo.Queryable.all/4
这里使用 elixir 1.4.1 和 ecto 2.1.4。
如何正确查询?
提前致谢!
使用 fragment
时,?
周围的 SQL 中不需要引号(并且在修复引号错误后也不需要显式类型转换) :
shop |> Ecto.assoc(:orders) |> select([o], fragment("date_trunc('day', ? at time zone ?)", o.inserted_at, ^timezone)) |> Repo.all