Can Ecto query calls be generalized?

Standard query call:

query = from singer in "artists", where: singer.name == "J Balvin", select: [:id, :albums]
Repo.all(q)

Goal - Generalized query calls:

record_lookup("artists", :name, "J Balvin", [:id, :albums])

Attempt:

def record_lookup(table_name, key, identifier, lookup_fields_list) do
	Repo.transaction(fn ->
	  query = from record in table_name, where: record.key == ^identifier, select: ^lookup_fields_list

	  Repo.all(query)
	end)
end

This initial approach doesn’t work so my concern is whether it is even feasible to generalize Ecto queries in this manner. If so, how would one go about doing it?

1 Like

I think you need to use Ecto.Query.API — Ecto v3.7.0, so like this:

query = from record in table_name, where: field(record, ^key) == ^identifier, select: ^lookup_fields_list
5 Likes