-
Notifications
You must be signed in to change notification settings - Fork 36
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: joshuaunity <[email protected]>
- Loading branch information
1 parent
2cc92fb
commit c914e55
Showing
1 changed file
with
58 additions
and
0 deletions.
There are no files selected for viewing
58 changes: 58 additions & 0 deletions
58
...easures/data/migrations/versions/950e23e3aa54_add_sensors_to_show_field_in_asset_model.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
"""add sensors_to_show field in asset model | ||
Revision ID: 950e23e3aa54 | ||
Revises: 0af134879301 | ||
Create Date: 2024-09-27 10:21:37.910186 | ||
""" | ||
|
||
from alembic import op | ||
import sqlalchemy as sa | ||
from sqlalchemy.sql import select | ||
|
||
# revision identifiers, used by Alembic. | ||
revision = "950e23e3aa54" | ||
down_revision = "0af134879301" | ||
branch_labels = None | ||
depends_on = None | ||
|
||
|
||
def upgrade(): | ||
# Add the 'sensors_to_show' column with nullable=True since we will populate it | ||
with op.batch_alter_table("generic_asset", schema=None) as batch_op: | ||
batch_op.add_column(sa.Column("sensors_to_show", sa.JSON(), nullable=True)) | ||
|
||
generic_asset_table = sa.Table( | ||
"generic_asset", | ||
sa.MetaData(), | ||
sa.Column("id", sa.Integer, primary_key=True), | ||
sa.Column("attributes", sa.JSON), | ||
sa.Column("sensors_to_show", sa.JSON), | ||
) | ||
|
||
# Initiate connection to execute the queries | ||
conn = op.get_bind() | ||
|
||
select_stmt = select(generic_asset_table.c.id, generic_asset_table.c.attributes) | ||
results = conn.execute(select_stmt) | ||
|
||
for row in results: | ||
asset_id, attributes_data = row | ||
|
||
sensors_to_show = attributes_data.get("sensors_to_show", {}) | ||
|
||
update_stmt = ( | ||
generic_asset_table.update() | ||
.where(generic_asset_table.c.id == asset_id) | ||
.values(sensors_to_show=sensors_to_show) | ||
) | ||
conn.execute(update_stmt) | ||
|
||
# After populating column, set back to be NOT NULL | ||
with op.batch_alter_table("generic_asset", schema=None) as batch_op: | ||
batch_op.alter_column("sensors_to_show", nullable=False) | ||
|
||
|
||
def downgrade(): | ||
with op.batch_alter_table("generic_asset", schema=None) as batch_op: | ||
batch_op.drop_column("sensors_to_show") |