-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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