Skip to content

Instantly share code, notes, and snippets.

@jaeyson
Forked from halfdan/schema_checker.ex
Created May 4, 2023 05:19
Show Gist options
  • Save jaeyson/1401c3af16024498f19c959b8f24fcae to your computer and use it in GitHub Desktop.
Save jaeyson/1401c3af16024498f19c959b8f24fcae 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