Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a string representing date to postgres query in Ecto

Tags:

elixir

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?

like image 877
user2205259 Avatar asked Mar 15 '23 07:03

user2205259


1 Answers

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
like image 59
bratsche Avatar answered Apr 01 '23 22:04

bratsche