siddhant3030
How can I write a raw sql query?
Hi,
I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw queries in phoenix. So to understand
I have created a user schema that inserts an email in a database table.
So created the changeset the like this
def changeset(user, attrs) do
user
|> cast(attrs, [:email, :password])
end
Now I have a create function that I’m using in my model. So the model will basically talk to db.
def create_user(attrs \\ %{}) do
%User{}
|> User.changeset(attrs)
|> Repo.insert()
end
I have inserted an email in my database. using this
iex(1) > user = User.changeset(%User{}, %{email: “”, password: “”})
Now what I want is to find that user by his email address.
Also If I wanted to fetch through id. I would just do this
def get_user!(id), do: Repo.get!(User, id)
But what if I want to write a raw query? How do I do that?
Marked As Solved
sribe
Ah! Seeing your result, I maybe see your problem. You’re expected the $1 inside the quotes to get replaced with the argument? Maybe what you actually want is:
Ecto.Adapters.SQL.query(Wizex.Repo, "SELECT * FROM game WHERE name ILIKE $1", [name <> "%"])
Also Liked
kokolegorille
You might also have a look at…
https://hexdocs.pm/ecto_sql/Ecto.Adapters.SQL.html#query!/4
…for raw queries
al2o3cr
FWIW, you can do this with Repo.get_by(User, email: email_to_find).
benwilson512
The best place to start is always the docs. Hint: it’s a function inside this module Ecto.Repo — Ecto v3.11.1
benwilson512
Ah yeah, I’m realizing my post wasn’t super helpful because query! isn’t actually in the Repo docs
, it’s just added inside repos that actually use SQL adapters. That’s unfortunate.







