why
Dynamic schema name
Hello,
I’m trying to dynamically pass a schema name into a function for use in a query. Can’t quite figure out in which format to pass in the schema name.
Pseudo code (not working):
def test(schema_name) do
Test.Repo.all(from a in schema_name, where: a.name == "ACME")
end
Have tried various ways of passing the schema_name in, including in the form of a {“source”, Schema} tuple, as discussed here: https://stackoverflow.com/questions/40687186/how-can-you-dynamically-set-a-schema-table-name-for-a-ecto-model
But no luck so far… Any ideas how one could do this?
Thank you!
Most Liked
1player
Sorry for the double post, but using the schema module actually works!
Your problem is using the Account atom, which isn’t probably aliased to its fully qualified name.
You’ll see that if you alias it, or use the fully qualified module name, such as YourApp.Data.Account, it will work.
alias YourApp.Data.Account
# Without the alias above, Ecto does not know what Account is.
# You might have multiple Account modules in different namespaces.
test(Account)
# This will always work, alias or not
test(YourApp.Data.Account)
1player
Ah, gotcha.
The use Ecto.Schema macro creates a __schema__ function that exposes some introspection details about your schema, and you can use that to find the actual table name as string (https://hexdocs.pm/ecto/Ecto.Schema.html#module-reflection)
def test(schema_name) when is_atom(schema_name) do
# Get the table name as string
table_name = schema_name.__schema__(:source)
Test.Repo.all(from a in table_name, where: a.name == "ACME", select: a.id)
end
Hope this helps!
why
Awesome, thanks a lot, that fixed it, it was the aliasing 
Great help, really appreciate it!







