From ed93fa7b2920f6b7fe29025022d32d93ff373b01 Mon Sep 17 00:00:00 2001 From: Cayo Puigdefabregas Date: Wed, 4 Nov 2020 17:30:46 +0100 Subject: [PATCH] update the datas in the migration process --- .../68a5c025ab8e_adding_owner_id_in_device.py | 21 +++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/ereuse_devicehub/migrations/versions/68a5c025ab8e_adding_owner_id_in_device.py b/ereuse_devicehub/migrations/versions/68a5c025ab8e_adding_owner_id_in_device.py index 4570cbaa..c2cad2df 100644 --- a/ereuse_devicehub/migrations/versions/68a5c025ab8e_adding_owner_id_in_device.py +++ b/ereuse_devicehub/migrations/versions/68a5c025ab8e_adding_owner_id_in_device.py @@ -10,7 +10,6 @@ from alembic import context from alembic import op from sqlalchemy.dialects import postgresql - # revision identifiers, used by Alembic. revision = '68a5c025ab8e' down_revision = 'b9b0ee7d9dca' @@ -25,12 +24,30 @@ def get_inv(): return INV def upgrade(): - op.add_column('device', sa.Column('owner_id', postgresql.UUID(), nullable=True), schema=f'{get_inv()}') + # We need get the actual computers with owner_id + # because when add a column in device this reset the values of the owner_id + # in the computer tables + con = op.get_bind() + # computers = con.execute(f"select id, owner_id from {get_inv()}.computer") + + op.add_column('device', sa.Column('owner_id', postgresql.UUID(), + sa.ForeignKeyConstraint(['owner_id'], ['common.user.id'], ), + nullable=True), schema=f'{get_inv()}') op.create_foreign_key("fk_device_owner_id_user_id", "device", "user", ["owner_id"], ["id"], ondelete="SET NULL", source_schema=f'{get_inv()}', referent_schema='common') + sql = f"select {get_inv()}.component.id, {get_inv()}.computer.owner_id from \ + {get_inv()}.component \ + inner join {get_inv()}.computer on \ + {get_inv()}.component.parent_id={get_inv()}.computer.id" + + components = con.execute(sql) + for id_component, id_owner in components: + _sql = f"update {get_inv()}.component set owner_id={id_owner} where id={id_component}" + con.execute(_sql) + def downgrade():