|
| 1 | +import logging |
| 2 | + |
| 3 | +from sqlalchemy import MetaData, String, and_, func, select |
| 4 | + |
| 5 | +logger = logging.getLogger(__name__) |
| 6 | + |
| 7 | + |
| 8 | +class InconsistentDatabaseError(Exception): |
| 9 | + pass |
| 10 | + |
| 11 | + |
| 12 | +def store_database_values(engine, conn): |
| 13 | + """Introspect the session, get all the tables and store their primary key values. |
| 14 | +
|
| 15 | + The result is a dict[table_name, list[pk_tuple]] |
| 16 | + """ |
| 17 | + |
| 18 | + metadata = MetaData() |
| 19 | + metadata.reflect(engine) |
| 20 | + |
| 21 | + dump = {} |
| 22 | + for table_name, table in metadata.tables.items(): |
| 23 | + # Get primary key columns and foreign key columns |
| 24 | + pk_columns = [ |
| 25 | + column |
| 26 | + for column in table.columns |
| 27 | + if column.primary_key or len(column.foreign_keys) > 0 |
| 28 | + ] |
| 29 | + |
| 30 | + if not pk_columns: |
| 31 | + # Skip tables without primary keys |
| 32 | + continue |
| 33 | + |
| 34 | + # Select only primary key columns, cast to string at database level |
| 35 | + pk_columns_as_string = [func.cast(col, String) for col in pk_columns] |
| 36 | + result = conn.execute(select(*pk_columns_as_string)) |
| 37 | + try: |
| 38 | + dump[table_name] = [tuple(row) for row in result.fetchall()] |
| 39 | + except Exception as ex: |
| 40 | + raise RuntimeError(f"Could not fetch rows from table {table_name}") from ex |
| 41 | + |
| 42 | + return dump |
| 43 | + |
| 44 | + |
| 45 | +def purge_database_values(engine, conn, stored_values): |
| 46 | + """Delete rows that are not in the stored values.""" |
| 47 | + |
| 48 | + metadata = MetaData() |
| 49 | + metadata.reflect(engine) |
| 50 | + |
| 51 | + # Build a list of (table_name, delete_condition) tuples |
| 52 | + to_be_deleted = [] |
| 53 | + |
| 54 | + for table_name, table in metadata.tables.items(): |
| 55 | + stored_rows = stored_values.get(table_name, []) |
| 56 | + |
| 57 | + # Get primary key columns and foreign key columns |
| 58 | + pk_columns = [ |
| 59 | + column |
| 60 | + for column in table.columns |
| 61 | + if column.primary_key or len(column.foreign_keys) > 0 |
| 62 | + ] |
| 63 | + |
| 64 | + if not pk_columns: |
| 65 | + logger.warning(f"Table {table_name} has no primary key. Skipping.") |
| 66 | + continue |
| 67 | + |
| 68 | + # Convert stored rows to a set of primary key tuples for fast lookup |
| 69 | + stored_pk_set = set(stored_rows) |
| 70 | + |
| 71 | + # create a select statement that would include only rows that are not present |
| 72 | + # in the stored values. It will be not (pk1 == val1 and pk2 == val2 and ...) and not (...) |
| 73 | + row_matcher_conditions = [] |
| 74 | + for stored_pk in stored_pk_set: |
| 75 | + # Cast columns to string at database level for comparison |
| 76 | + condition = and_( |
| 77 | + *( |
| 78 | + func.cast(pk_col, String) == pk_val |
| 79 | + for pk_col, pk_val in zip(pk_columns, stored_pk) |
| 80 | + ) |
| 81 | + ) |
| 82 | + # negate the condition to match rows that are not equal |
| 83 | + row_matcher_conditions.append(~condition) |
| 84 | + |
| 85 | + if row_matcher_conditions: |
| 86 | + non_matching_condition = and_(*row_matcher_conditions) |
| 87 | + to_be_deleted.append( |
| 88 | + (table_name, table, non_matching_condition, len(stored_pk_set)) |
| 89 | + ) |
| 90 | + else: |
| 91 | + # delete everything |
| 92 | + to_be_deleted.append((table_name, table, None, len(stored_pk_set))) |
| 93 | + |
| 94 | + # Try to delete rows with retry mechanism for foreign key constraints |
| 95 | + while to_be_deleted: |
| 96 | + failed_deletions = [] |
| 97 | + |
| 98 | + for table_name, table, where_condition, expected_count in to_be_deleted: |
| 99 | + # Execute deletion in a transaction so that we can rollback on failure |
| 100 | + with conn.begin(): |
| 101 | + try: |
| 102 | + delete_stmt = table.delete() |
| 103 | + if where_condition is not None: |
| 104 | + delete_stmt = delete_stmt.where(where_condition) |
| 105 | + |
| 106 | + conn.execute(delete_stmt) |
| 107 | + |
| 108 | + existing_count = conn.execute( |
| 109 | + select(func.count()).select_from(table) |
| 110 | + ).scalar() |
| 111 | + conn.commit() |
| 112 | + if expected_count > existing_count: |
| 113 | + |
| 114 | + where_str = where_condition.compile( |
| 115 | + dialect=conn.dialect, |
| 116 | + compile_kwargs={"literal_binds": True}, |
| 117 | + ) |
| 118 | + |
| 119 | + raise InconsistentDatabaseError( |
| 120 | + f"Expected to have {expected_count} rows in table {table_name} " |
| 121 | + f"in test cleanup but only {existing_count} remain after the test. " |
| 122 | + f"The test must have removed rows from module-level fixtures, " |
| 123 | + f"thus making the database inconsistent for subsequent tests." |
| 124 | + f"The conditions for rows: {where_str}" |
| 125 | + ) |
| 126 | + logger.debug( |
| 127 | + "Deleted rows from table: %s, expected: %s, remaining: %s", |
| 128 | + table_name, |
| 129 | + expected_count, |
| 130 | + existing_count, |
| 131 | + ) |
| 132 | + if existing_count != expected_count: |
| 133 | + logger.warning( |
| 134 | + "Not all rows deleted as expected, will try again." |
| 135 | + ) |
| 136 | + failed_deletions.append( |
| 137 | + (table_name, table, where_condition, expected_count) |
| 138 | + ) |
| 139 | + except InconsistentDatabaseError: |
| 140 | + # Reraise as the database is in an inconsistent state which can not be fixed |
| 141 | + raise |
| 142 | + except Exception: |
| 143 | + # Rollback on failure and retry in next iteration |
| 144 | + conn.rollback() |
| 145 | + failed_deletions.append( |
| 146 | + (table_name, table, where_condition, expected_count) |
| 147 | + ) |
| 148 | + |
| 149 | + if len(failed_deletions) == len(to_be_deleted): |
| 150 | + table_names = [table_name for table_name, _, _, _ in failed_deletions] |
| 151 | + raise RuntimeError( |
| 152 | + f"Could not delete the remaining rows due to foreign key cycles in tables: {table_names}" |
| 153 | + ) |
| 154 | + else: |
| 155 | + # Update the list with failed deletions for next iteration |
| 156 | + to_be_deleted = failed_deletions |
0 commit comments