-
Notifications
You must be signed in to change notification settings - Fork 9
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
improvement: create migration from string to json
Signed-off-by: Agustín Ramiro Díaz <[email protected]>
- Loading branch information
1 parent
60583e8
commit 2c4d5d0
Showing
1 changed file
with
66 additions
and
0 deletions.
There are no files selected for viewing
66 changes: 66 additions & 0 deletions
66
backend/database_handler/migration/versions/02aa0c34a463_validator_config_string_to_jsonb.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,66 @@ | ||
"""validator config string to jsonb | ||
Revision ID: 02aa0c34a463 | ||
Revises: 188ca1c3a340 | ||
Create Date: 2024-07-16 09:01:35.449848 | ||
""" | ||
|
||
import json | ||
from typing import Sequence, Union | ||
|
||
from alembic import op | ||
import sqlalchemy as sa | ||
|
||
|
||
# revision identifiers, used by Alembic. | ||
revision: str = "02aa0c34a463" | ||
down_revision: Union[str, None] = "188ca1c3a340" | ||
branch_labels: Union[str, Sequence[str], None] = None | ||
depends_on: Union[str, Sequence[str], None] = None | ||
|
||
|
||
def upgrade() -> None: | ||
|
||
# Define the Python function to apply | ||
def transform(value): | ||
if value is None: | ||
return {} | ||
if isinstance(value, dict): | ||
return value | ||
if isinstance(value, str): | ||
try: | ||
return json.loads(value) | ||
except: | ||
print(f"Failed to parse JSON: {value}. Removing configuration.") | ||
return {} | ||
print(f"Unexpected type: {type(value)}. Removing configuration.") | ||
return {} | ||
|
||
# Use SQLAlchemy to connect to the database | ||
connection = op.get_bind() | ||
|
||
column_name = "config" | ||
id_column = "id" | ||
table_name = "validators" | ||
|
||
result = connection.execute( | ||
sa.text(f"SELECT {id_column}, {column_name} FROM {table_name}") | ||
) | ||
|
||
for [id, value] in result: | ||
new_value = transform(value) | ||
print(f"Updating {table_name} {id} with `{new_value}`") | ||
# Update the row | ||
connection.execute( | ||
sa.text( | ||
f"UPDATE {table_name} SET {column_name} = :value WHERE {id_column} = :id" | ||
), | ||
{"value": json.dumps(new_value), id_column: id}, | ||
) | ||
|
||
|
||
def downgrade() -> None: | ||
# ### commands auto generated by Alembic - please adjust! ### | ||
pass | ||
# ### end Alembic commands ### |