Hi all
When I want to query something from db, for exmaple
query = from p in EctoBlog.Post, where: p.id == ^post_id
Why do I need here the pin operator?
Thanks
Hi all
When I want to query something from db, for exmaple
query = from p in EctoBlog.Post, where: p.id == ^post_id
Why do I need here the pin operator?
Thanks
This is simply a choice of how Ecto wanted to make its api. It helps make it clear when a term refers to a table, and when it refers to an injected value. For example consider the following example:
u = %User{id: 1}
from u in User, where: u.id == ^u.id
The pin operator makes it clear that the right hand side of the ==
is referring to the external u
.
Think of it as a safe interpolation operator: the Ecto query doesn’t see your variables outside the from macro call unless you tell it to look outside itself. You using the ^ is marking that the variable is outside the DSL language of the macro to separate the variables like p that represent a table. This always the macro to detect errors and typos at compile time as it can be sure if a variable is in the DSL or from the scope.