Search code examples
elixirecto

Passing a string representing date to postgres query in Ecto


Trying to execute this postgres query:

select date('2015-10-05') from posts;

I'm passing the date as a string:

Ecto.Adapters.SQL.query!(
  Repo, "select date('$1') from posts", ["2015-10-05"])  

But getting an error that the datetime format is invalid.

** (Postgrex.Error) ERROR (invalid_datetime_format): 
  invalid input syntax for type date: "$1"

[debug] select date('$1') from posts ["2015-10-05"]
  ERROR query=0.6ms
    (ecto) lib/ecto/adapters/sql.ex:172: Ecto.Adapters.SQL.query!/5

However, I'm not passing it as a date, but as a string. Postgres' date() function accepts string too, AFAIK and the error is still the same when I add ::varchar to make sure it's a string. Any advice how can this be avoided?


Solution

  • So you want to pass it into Ecto in the form {2015, 10, 5} instead of as a string.

    Ecto.Adapters.SQL.query(Repo, "SELECT $1::date", [{2015, 10, 5}])
    

    You can make a little helper function to turn a string into that format:

    def string_to_date(str) do
      {_, date} = Ecto.Date.cast(str)
      Ecto.Date.to_erl(date)
    end