Search code examples
elixirphoenix-frameworkecto

Ecto | How to get all schema modules in the application


I'm trying to create a mix task for automation some scaffolding and I want to get a list of all module names in the application which have schema and embed schema implementations. Eventually I'd like to have a list of all schemas with the fields definitions, not just module names. Can we get it and if yes then how, does ecto provide such api?


Solution

  • According to Ecto.Schema's documentation,

    Any schema module will generate the __schema__ function that can be used for runtime introspection of the schema.

    You can use this together with Erlang's and Elixir's own introspection facilities for filtering all relevant modules and neatly retrieving details of any defined schemata, e.g.:

    {:ok, modules} = :application.get_key(:your_app, :modules)
    
    modules 
    |> Enum.filter(&({:__schema__, 1} in &1.__info__(:functions))) 
    |> Enum.each(&(IO.inspect(&1.__schema__(:fields))))