Skip to content

Instantly share code, notes, and snippets.

@halfdan
Last active August 14, 2023 21:17
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save halfdan/6853a8cc8994eca4c9311ecad04a0eb0 to your computer and use it in GitHub Desktop.
Save halfdan/6853a8cc8994eca4c9311ecad04a0eb0 to your computer and use it in GitHub Desktop.
Detecting unused database columns using Ecto schemas - https://geekmonkey.org/detecting-unused-database-columns-using-ecto-schemas/
defmodule SchemaChecker do
def find_field_discrepancies do
schema_modules()
|> Enum.map(fn mod ->
{mod.__schema__(:source), check_module(mod)}
end)
end
defp schema_modules do
{:ok, modules} = :application.get_key(:core, :modules)
modules
|> Enum.filter(&({:__schema__, 1} in &1.__info__(:functions)))
|> Enum.filter(&(:__meta__ in Map.keys(&1.__schema__(:loaded))))
end
defp check_module(module) do
fields =
module.__schema__(:fields)
|> Enum.map(&module.__schema__(:field_source, &1))
|> Enum.map(&Atom.to_string/1)
table_name = module.__schema__(:source)
{:ok, %{columns: columns}} = DB.Repo.query("SELECT * FROM #{table_name} LIMIT 0")
columns -- fields
end
end
SchemaChecker.find_field_discrepancies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment