From ee5bb299ac9fdeb5566c33d41feae32e0998a7da Mon Sep 17 00:00:00 2001 From: John Davis Date: Tue, 11 Jun 2024 19:03:28 -0400 Subject: [PATCH] Add migration for username column db schema + data --- ..._update_username_column_schema_and_data.py | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 lib/galaxy/model/migrations/alembic/versions_gxy/c63848676caf_update_username_column_schema_and_data.py diff --git a/lib/galaxy/model/migrations/alembic/versions_gxy/c63848676caf_update_username_column_schema_and_data.py b/lib/galaxy/model/migrations/alembic/versions_gxy/c63848676caf_update_username_column_schema_and_data.py new file mode 100644 index 000000000000..30c2c4a48520 --- /dev/null +++ b/lib/galaxy/model/migrations/alembic/versions_gxy/c63848676caf_update_username_column_schema_and_data.py @@ -0,0 +1,53 @@ +"""Update username column schema and data + +Revision ID: c63848676caf +Revises: c14a3c93d66b +Create Date: 2024-06-11 13:41:36.411803 + +""" + +from alembic import op +from sqlalchemy import ( + or_, + select, + update, +) + +from galaxy.managers.users import username_from_email_with_connection +from galaxy.model import User +from galaxy.model.migrations.util import ( + alter_column, + transaction, +) + +# revision identifiers, used by Alembic. +revision = "c63848676caf" +down_revision = "c14a3c93d66b" +branch_labels = None +depends_on = None + +table_name = "galaxy_user" +column_name = "username" + + +def upgrade(): + with transaction(): + _generate_missing_usernames() + alter_column(table_name, column_name, nullable=False) + + +def downgrade(): + with transaction(): + # The data migration is one-way: we can change back the database schema, + # but we can't remove the generated username values. + alter_column(table_name, column_name, nullable=True) + + +def _generate_missing_usernames(): + stmt = select(User.id, User.email).where(or_(User.username.is_(None), User.username == "")) + connection = op.get_bind() + users = connection.execute(stmt).all() + for id, email in users: + new_username = username_from_email_with_connection(connection, email) + stmt = update(User).where(User.id == id).values(username=new_username) + connection.execute(stmt)