Ecto.Function v1.0.1 Ecto.Function
Helper macro for defining helper macros for calling DB functions.
A little Xzibity, but helps.
Link to this section Summary
Functions
Define new SQL function call
Link to this section Functions
Define new SQL function call.
Options
Currently there is only one option allowed:
for
- define DB function name to call
Examples
import Ecto.Function
defqueryfunc foo # Define function without params
defqueryfunc bar(a, b) # Explicit parameter names
defqueryfunc baz/1 # Define function using arity
defqueryfunc qux(a, b \\ 0) # Define function with default arguments
defqueryfunc quux/1, for: "db_quux" # Define with alternative DB call
Then calling such functions in query would be equivalent to:
from _ in "foos", select: %{foo: foo()}
# => SELECT foo() AS foo FROM foos
from q in "bars", select: %{bar: bar(q.a, q.b)}
# => SELECT bar(bars.a, bars.b) AS bar FROM bars
from q in "bazs", where: baz(q.a) == true
# => SELECT * FROM bazs WHERE baz(bazs.a) = TRUE
from q in "quxs", select: %{one: qux(q.a), two: qux(q.a, q.b)}
# => SELECT
# qux(quxs.a, 0) AS one,
# qux(quxs.a, quxs.b) AS two
# FROM "quxs"
from q in "quuxs", select: %{quux: quux(q.a)}
# => SELECT db_quux(quuxs.a) FROM quuxs
Gotchas
If your function uses “special syntax” like PostgreSQL extract
then this module won’t help you and you will be required to write your own
macro that will handle such case.
defmacro extract(from, field) do
query do: fragment("extract(? FROM ?)", field, from)
end
This case probably will never be supported in this library and you should handle it on your own.