Why are pin operators necessary in Ecto queries?

只愿长相守 提交于 2019-11-30 04:49:54

Ecto's queries rely on macros to provide the powerful DSL that we use. That means that, whatever comes after from, is not "regular" Elixir code, but a DSL which will eventually get transformed to SQL query. So, a caret there is not pin operator per se, and has nothing to do with pattern matching (although obviously it still can be called "pin operator" because people always forget words such as caret and ampersand and asterisk). It's just a convenient operator that Ecto's authors choose to be an "interpolation operator". Without it, the username from your example would be taken literally, and inserted directly to the generated SQL (though Ecto is smart enough to see that that's not what you want so it spills an error).

Great question BTW, inspired me to read more about macros (newbie in FP here).

According to Ecto documentation, the pin operator in ecto is used for query interpolation:

External values and Elixir expressions can be injected into a query expression with ^

def with_minimum(age, height_ft) do
  from u in "users",
    where: u.age > ^age and u.height > ^(height_ft * 3.28),
    select: u.name
end

Trying to skip the pin will give you an error as Ecto cann't figure out a database function or query expression named age:

(Ecto.Query.CompileError) variable age is not a valid query expression. Variables need to be explicitly interpolated in queries with ^

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!