Using variable in ecto query prefix

When I use a variable instead of a string in the prefix option, the query fails:

The query:

query =
        from u in User,
          prefix: ^params["prefix"],
          order_by: [asc: u.full_name, asc: u.id],
          select: struct(u, [:id, :first_name, :last_name, :full_name])

Repo.all(query)

The result:

Ecto.Query.CompileError

prefix must be a compile time string, got: params["prefix"]

When I use a string in the prefix option like:

query =
        from u in User,
          prefix: "tenant",
          order_by: [asc: u.full_name, asc: u.id],
          select: struct(u, [:id, :first_name, :last_name, :full_name])

Repo.all(query)

everything works fine.

So, how can I convert a string variable into a compile time string? Is this possible or is the problem a bug in ecto?

Thanks for your advice.

You can’t use a variable, and since the error message explicitly tells you that you can’t, then it’s probably not a bug, but a design decision.

Thx NobbZ for your response. I thought I am doing something wrong because using a variable in the prefix option of e.g. Repo.all works.

As a workaround you could do something like:

query =
        from u in User,
          order_by: [asc: u.full_name, asc: u.id],
          select: struct(u, [:id, :first_name, :last_name, :full_name])
query = Map.put(query, :prefix, params["prefix"])
Repo.all(query)

This is from the actual example from the official docs, I don’t know why you can’t just do it inline though… ^.^;

3 Likes

Hi OvermindDL1. That’s it. Many many thanks!!!

1 Like