Skip to content

Commit

Permalink
Handle missing schemas in ensure_up!
Browse files Browse the repository at this point in the history
We noticed that `c:Migrator.ensure_up!/0` does not check for existence
of schemas before calling `Ecto.Migrator.migrations/3`, which
unfortunately terminates with a rather cryptic error.

This PR fixes that by explicitly checking schema existence before
calling `migrations/3`. Opted for only checking (instead of creating it)
to keep `ensure_up!/0`'s behaviour "read-only".
  • Loading branch information
maltoe committed Dec 6, 2023
1 parent 55e8f8a commit 9a66c18
Showing 1 changed file with 16 additions and 3 deletions.
19 changes: 16 additions & 3 deletions lib/bitcrowd_ecto/migrator.ex
Original file line number Diff line number Diff line change
Expand Up @@ -215,10 +215,19 @@ defmodule BitcrowdEcto.Migrator do
end

defp down_tenant_migrations(repo) do
for tenant <- repo.known_prefixes() do
if schema_exists?(repo, tenant) do
down_tenant_migrations(repo, tenant)
else
["SCHEMA DOES NOT EXIST: #{tenant}"]
end
end
end

defp down_tenant_migrations(repo, tenant) do
path = tenant_migrations_path(repo)

for tenant <- repo.known_prefixes(),
{:down, prefix, name} <- Migrator.migrations(repo, [path], prefix: tenant) do
for {:down, prefix, name} <- Migrator.migrations(repo, [path], prefix: tenant) do
"#{prefix}_#{name} (tenant: #{tenant})"
end
end
Expand Down Expand Up @@ -286,8 +295,12 @@ defmodule BitcrowdEcto.Migrator do
SELECT 1 FROM information_schema.schemata WHERE schema_name = $1;
"""

defp schema_exists?(repo, tenant) do
match?(%{rows: [[1]]}, SQL.query!(repo, @exists_query, [tenant]))
end

defp ensure_schema!(repo, tenant) do
unless match?(%{rows: [[1]]}, SQL.query!(repo, @exists_query, [tenant])) do
unless schema_exists?(repo, tenant) do
SQL.query!(repo, ~s(CREATE SCHEMA "#{tenant}"), [])
end
end
Expand Down

0 comments on commit 9a66c18

Please sign in to comment.