Synchronize ORM model to database
(engine, diff)
| 131 | |
| 132 | |
| 133 | def sync_database(engine, diff): |
| 134 | """Synchronize ORM model to database""" |
| 135 | metadata = Base.metadata |
| 136 | |
| 137 | # Alembic context configuration |
| 138 | from alembic.migration import MigrationContext |
| 139 | from alembic.operations import Operations |
| 140 | |
| 141 | conn = engine.connect() |
| 142 | ctx = MigrationContext.configure(conn) |
| 143 | op = Operations(ctx) |
| 144 | |
| 145 | # Handle deleted tables |
| 146 | for table_name in diff['deleted_tables']: |
| 147 | op.drop_table(table_name) |
| 148 | print(f"Deleted table: {table_name}") |
| 149 | |
| 150 | # Handle added tables |
| 151 | for table_name in diff['added_tables']: |
| 152 | table = metadata.tables.get(table_name) |
| 153 | if table is not None: |
| 154 | table.create(engine) |
| 155 | print(f"Created table: {table_name}") |
| 156 | |
| 157 | # Handle field changes |
| 158 | for table_name, changes in diff['changed_tables'].items(): |
| 159 | # Delete fields |
| 160 | for col_name in changes['deleted']: |
| 161 | op.drop_column(table_name, col_name) |
| 162 | print(f"Deleted field in table {table_name}: {col_name}") |
| 163 | # Add fields |
| 164 | for col_name in changes['added']: |
| 165 | table = metadata.tables.get(table_name) |
| 166 | column = table.columns.get(col_name) |
| 167 | if column is not None: |
| 168 | op.add_column(table_name, column) |
| 169 | print(f"Added field in table {table_name}: {col_name}") |
| 170 | |
| 171 | # Modify fields |
| 172 | for col_name, types in changes['modified'].items(): |
| 173 | table = metadata.tables.get(table_name) |
| 174 | if table is not None: |
| 175 | column = table.columns.get(col_name) |
| 176 | if column is not None: |
| 177 | op.alter_column(table_name, col_name, type_=column.type) |
| 178 | print(f"Modified field in table {table_name}: {col_name} (type changed to {column.type})") |
| 179 | |
| 180 | |
| 181 | def main(): |