Passing a string representing date to postgres query in Ecto

user2205259

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?

bratsche

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Passing DateTimeOffset as WebAPI query string

Elixir: How to get the current date for an Ecto Query?

Ecto/Elixir, How can I query by date?

select query with date in postgres sql

Replace in a string representing a date only in certain positions

string representing date and transform it

Ecto query for date range

Passing percentage sign to string variable representing magic function

sql server convert string representing datetime to date

Postgres function passing table reference and string in RETURN QUERY

SQLite: Passing ' in query String

Passing Dates as Query String Parameters to SSRS reports, without being affected by Server Date Settings

Converting a string representing milliseconds to a Date

Passing query string data to form

Postgres date subtraction in a query

How to check if string representing timestamp is valid date in Java?

Ecto query where string field contains other string

JS - Passing a string to a MongoDB query

Passing date as string to textview

Passing Values to Query String

Ecto Query - Dates + Postgres Intervals + Query Interpolation

Ecto query Postgres JSON Array for a value

Convert string representing timestamp to date format inside python list

Ecto Query Fragment with Postgres substring

Passing Parameter to Progress via Open Query from SQL Server - error Invalid date string

What is they query format for date in Postgres?

Ecto - Return records with timestamps grouped by date in a single query

Passing string as query params not working

Passing array into query string