Skip to content

Commit

Permalink
improvement: create migration from string to json
Browse files Browse the repository at this point in the history
Signed-off-by: Agustín Ramiro Díaz <[email protected]>
  • Loading branch information
AgustinRamiroDiaz committed Jul 16, 2024
1 parent 60583e8 commit 2c4d5d0
Showing 1 changed file with 66 additions and 0 deletions.
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 ###

0 comments on commit 2c4d5d0

Please sign in to comment.