Skip to content

Instantly share code, notes, and snippets.

@MartinElvar
Last active September 30, 2015 17:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MartinElvar/6e99a1aabc5ad051c6e3 to your computer and use it in GitHub Desktop.
Save MartinElvar/6e99a1aabc5ad051c6e3 to your computer and use it in GitHub Desktop.
Ecto builder Arithmetic support
# The idea is to add support for something like.
# query = from s in Subscription,
# order_by: s.price + s.registration_fee
#
# subscriptions = Repo.all(query)
# Arithmetic
def escape({operator, _, [left, right]} = expr, type, params, vars, env) when operator in ~w(+ - * /)a do
ltype = quoted_type(right, vars)
rtype = quoted_type(left, vars)
{left, params} = escape(left, ltype, params, vars, env)
{right, params} = escape(right, rtype, params, vars, env)
{{:{}, [], [operator, [], [left, right]]}, params}
end
# But this yields the following query, notice the ORDER BY, at the end.
# [debug] SELECT s0."id", s0."name", s0."price", s0."registration_fee", s0."call_time", s0."binding_period", s0."has_4g", s0."free_sms", s0."intro_discount", s0."endpoint", s0."data", s0."company_id", s0."inserted_at", s0."updated_at" FROM "subscriptions" AS s0 ORDER BY +(s0."call_time", s0."call_time") [] ERROR query=0.2ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment