Add missing nullable columns to existing tables if needed.
(self, engine)
| 105 | self.prepared = True |
| 106 | |
| 107 | def _migrate_missing_columns(self, engine): |
| 108 | """Add missing nullable columns to existing tables if needed.""" |
| 109 | try: |
| 110 | inspector = inspect(engine) |
| 111 | preparer = engine.dialect.identifier_preparer |
| 112 | for table in ResultModelBase.metadata.tables.values(): |
| 113 | actual_name = table.name |
| 114 | schema = table.schema |
| 115 | if not inspector.has_table(actual_name, schema=schema): |
| 116 | continue |
| 117 | existing_cols = { |
| 118 | col['name'] for col in inspector.get_columns(actual_name, schema=schema) |
| 119 | } |
| 120 | for col in table.columns: |
| 121 | if col.name not in existing_cols and col.nullable: |
| 122 | col_type = col.type.compile(engine.dialect) |
| 123 | table_name = preparer.format_table(table) |
| 124 | col_name = preparer.quote_identifier(col.name) |
| 125 | alter_stmt = f"ALTER TABLE {table_name} ADD COLUMN {col_name} {col_type}" |
| 126 | try: |
| 127 | with engine.begin() as conn: |
| 128 | conn.execute(text(alter_stmt)) |
| 129 | except Exception as exc: |
| 130 | logger.warning( |
| 131 | "Failed to add missing column %r to table %r. " |
| 132 | "To enable storing task children, execute: %s. Error: %s", |
| 133 | col.name, actual_name, alter_stmt, exc, |
| 134 | ) |
| 135 | except Exception as exc: |
| 136 | logger.warning("Failed to inspect or migrate database tables: %s", exc) |
| 137 | |
| 138 | def session_factory(self, dburi, **kwargs): |
| 139 | engine, session = self.create_session(dburi, **kwargs) |