如何在Ecto片段语句中使用date_trunc和timezone

时间:2017-04-08 00:33:11

标签: postgresql elixir ecto

我尝试使用商店的时区查询商店的订单和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

但是当我尝试动态传入时区时,我得到了#34;无法确定参数$ 1"的数据类型。即使我明确使用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 $1
[debug] QUERY ERROR source="orders" db=1.0ms
SELECT date_trunc('day', o0."inserted_at" at time zone '$1::varchar') FROM "orders" AS o0 WHERE (o0."shop_id" = $2) ["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。

如何正确查询?

提前致谢!

1 个答案:

答案 0 :(得分:2)

使用?时,您在fragment周围的SQL中不需要引号(在修复引用错误后,您也不需要显式类型转换):< / p>

shop |> Ecto.assoc(:orders) |> select([o], fragment("date_trunc('day', ? at time zone ?)", o.inserted_at, ^timezone)) |> Repo.all
相关问题