Add migration to assign 'Mitglied' role to existing users

This commit is contained in:
Moritz 2026-01-24 19:13:03 +01:00 committed by Simon
parent f426e853de
commit a7e6136648
Signed by: simon
GPG key ID: 40E7A58C4AA1EDB2

View file

@ -0,0 +1,41 @@
defmodule Mv.Repo.Migrations.AssignMitgliedRoleToExistingUsers do
@moduledoc """
Assigns the "Mitglied" role to all existing users without a role.
This migration runs once during deployment to ensure all users have a role assigned.
New users will automatically get the "Mitglied" role via the AssignDefaultRole change.
"""
use Ecto.Migration
import Ecto.Query
def up do
# Find the Mitglied role ID
mitglied_role_id =
repo().one(
from(r in "roles",
where: r.name == "Mitglied",
select: r.id
)
)
if mitglied_role_id do
# Assign Mitglied role to all users without a role
updated_count =
repo().update_all(
from(u in "users", where: is_nil(u.role_id)),
set: [role_id: mitglied_role_id]
)
IO.puts("✅ Assigned 'Mitglied' role to #{updated_count} existing user(s)")
else
IO.puts("⚠️ Warning: 'Mitglied' role not found - skipping role assignment")
IO.puts(" This is expected if roles haven't been seeded yet.")
IO.puts(" New users will get the role automatically via AssignDefaultRole change.")
end
end
def down do
# Not reversible - we can't know which users had no role before
:ok
end
end