8

I just want do execute an Ecto query with an simple concatination of two or more columns.

I think the following elixir pseudo code already shows what I try to do:

customers = Customer.undeleted(
  from c in Customer,
  select: %{id: c.id, name: c.name <> " – " <> c.street},
  order_by: c.name
) |> Repo.all

It drives me crazy cuz in SQL it is easy like this: ...SELECT c.id, concat(c.name, ' - ', c,street) AS name

Any ideas how to solve this with ecto querys ?

1
  • Dogbert's answer is the way to go but I believe for things of such small complexity, it may make sense to just do it on the application level Commented Apr 24, 2017 at 16:31

2 Answers 2

12

You cannot use <> in a select expression in Ecto. If you want to call concat like that, you can use fragment:

select: %{id: c.id, name: fragment("concat(?, ' - ', ?)", c.name, c.street)},
Sign up to request clarification or add additional context in comments.

Comments

1

To add to @Dogbert answer, you can clean up the code a bit by putting the SQL function fragment in a custom macro as described in the docs:

defmodule CustomSQLFunctions do
  defmacro concat(left, mid, right) do
    quote do
      fragment("concat(?, ?, ?)", unquote(left), unquote(mid), unquote(right))
    end
  end
end

Then import for use in query

import CustomSQLFunctions

customers = Customer.undeleted(
  from c in Customer,
  select: %{id: c.id, name: concat(c.name, ' - ', c.street)},
  order_by: c.name
) |> Repo.all

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.