Proposal: Named parameters in Ecto `fragment`s

There were cases when I needed to use some arguments in fragment few times, and as fragment("foo(?, ?)", a, a) roughly translates to foo($1, $2) with [a, a] passed as parameters, this sometimes result with unwanted results, so instead I would like to be able to do something like fragment("foo(?{a}, ?{a})", a: a) which would allow to improve some complicated queries in lateral joins (as these need to be fragments currently).

1 Like

You can always define your own macro:

defmacrop foo(a) do
  quote do
    fragment("foo(?, ?)", unquote(a), unquote(a))
  end
end

Yes, you can (I have even created library for handling simple cases like that), but sometimes it is infeasible to create macro for each fragment in some queries. Also this will not work in case of some queries, ex.:

fragment("""
SELECT
  date_fragment(foo.inserted_at, ?) AS date,
  COUNT()
FROM foos foo
GROUP BY date_fragment(foo.inserted_at, ?)
""", date, date)

Will fail even with macro as date_fragment(foo.inserted_at, ?) in each case is different (even if it seems to be the same).

2 Likes