@@ -104,14 +104,23 @@ def upgrade() -> None:
104104 with op .batch_alter_table ('admins' , schema = None ) as batch_op :
105105 batch_op .add_column (sa .Column ('role_id' , app .db .compiles_types .SqliteCompatibleBigInteger (), nullable = True ))
106106 batch_op .add_column (sa .Column ('permission_overrides' , sa .JSON ().with_variant (postgresql .JSONB (none_as_null = True , astext_type = Text ()), 'postgresql' ), nullable = True ))
107- # Backfill: is_sudo=true -> administrator (id=2), is_sudo=false -> operator (id=3)
107+ # Backfill: if there is exactly one sudo admin, make it owner. Otherwise keep legacy behavior:
108+ # is_sudo=true -> administrator (id=2), is_sudo=false -> operator (id=3).
108109 conn = op .get_bind ()
109110 dialect = conn .dialect .name
110111 if dialect == "postgresql" :
111- conn .execute (sa .text ("UPDATE admins SET role_id = 2 WHERE is_sudo = true" ))
112+ sudo_count = conn .execute (sa .text ("SELECT COUNT(*) FROM admins WHERE is_sudo = true" )).scalar ()
113+ if sudo_count == 1 :
114+ conn .execute (sa .text ("UPDATE admins SET role_id = 1 WHERE is_sudo = true" ))
115+ else :
116+ conn .execute (sa .text ("UPDATE admins SET role_id = 2 WHERE is_sudo = true" ))
112117 conn .execute (sa .text ("UPDATE admins SET role_id = 3 WHERE is_sudo = false OR role_id IS NULL" ))
113118 else :
114- conn .execute (sa .text ("UPDATE admins SET role_id = 2 WHERE is_sudo = 1" ))
119+ sudo_count = conn .execute (sa .text ("SELECT COUNT(*) FROM admins WHERE is_sudo = 1" )).scalar ()
120+ if sudo_count == 1 :
121+ conn .execute (sa .text ("UPDATE admins SET role_id = 1 WHERE is_sudo = 1" ))
122+ else :
123+ conn .execute (sa .text ("UPDATE admins SET role_id = 2 WHERE is_sudo = 1" ))
115124 conn .execute (sa .text ("UPDATE admins SET role_id = 3 WHERE is_sudo = 0 OR role_id IS NULL" ))
116125
117126 with op .batch_alter_table ('admins' , schema = None ) as batch_op :
0 commit comments