Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle missing schemas in ensure_up! #53

Merged
merged 1 commit into from
Dec 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
### Fixed

* Allow any type of `id` param in `Repo.fetch/2`. Remove the (incorrect) guard restricting the `id` param to binaries, against the spec saying it would allow `any`.
* Handle missing schemas gracefully in `Migrator.ensure_up!/0`.

## [0.16.0] - 2023-03-21

Expand Down
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