We are going to design a bot that manages schema changes in a database.
The bot should:
Perform impact analysis (what objects are affected, potential downtime, etc.)
Assign reviewers (maybe based on ownership or expertise)
Manage rollout windows (schedule the change during allowed times)
Steps:
We assume we have a way to get the current schema and the proposed change (SQL DDL).
Impact analysis: parse the DDL, compare with current schema, and determine:
Which tables/columns are being added, modified, or dropped.
Check for dependencies (views, stored procedures, etc. that might break).
Estimate the size of the change (e.g., adding a column might be fast, but modifying a column type might require a table rebuild and cause downtime).
We might also check against historical data (if available) to estimate the time for similar past changes.
Reviewers:
We might have a mapping of database objects to owners/teams.
Alternatively, we can assign reviewers based on who last modified the object or who is the current owner (if we have such metadata).
We might also have a list of mandatory reviewers (e.g., DBAs, SREs) for certain types of changes.
Rollout windows:
We might have a schedule of allowed deployment windows (e.g., only on weekends, or between 2am-4am).
The bot should check if the proposed change time (if provided) is within an allowed window.
If no time is provided, the bot can suggest the next available window.
Implementation:
We'll design a class SchemaChangeBot that will have the following methods:
__init__(self, db_connection, config):
db_connection: to connect to the database to get current schema and run analysis.
config: might include:
- impact_analysis_rules: how to analyze different types of changes.
- reviewer_assignment_rules: how to assign reviewers.
- rollout_windows: allowed time windows (could be a list of time ranges, or a function that returns if a given time is allowed).
- mandatory_reviewers: list of users or teams that must always be reviewers.
analyze_impact(self, ddl_statement):
Returns a report of the impact (affected objects, estimated downtime, etc.)
assign_reviewers(self, ddl_statement, current_user=None):
Returns a list of reviewers (usernames or emails) for this change.
Might use the impact analysis to see which objects are changed and then look up owners.
check_rollout_window(self, proposed_time=None):
If proposed_time is given, check if it's allowed. Otherwise, suggest the next allowed time.
approve_change(self, ddl_statement, approver, proposed_time=None):
This would be called when a change is approved. It might:
- Re-check impact and reviewers (in case something changed)
- Check the rollout window (if proposed_time is given, or if we are using the next available window)
- Then schedule the change (maybe by creating a ticket, or directly executing if allowed?).
However, note that the bot might not execute the change, but rather facilitate the approval process.
Alternatively, we might have a workflow:
User submits a DDL change via a command (e.g., in a chat bot or web form).
Bot runs impact analysis and posts the results.
Bot assigns reviewers and notifies them.
After reviewers approve, bot checks the rollout window and schedules the change (or allows the user to schedule).
We might also have a state machine for the change request.
Let's assume we are building a bot that integrates with a ticketing system (like Jira) or a chat system (like Slack).
But the core logic is in the analysis and assignment.
Given the complexity of the impact analysis and the fact that we don't have a real database to test, we'll implement a very basic version that:
Only handles ALTER TABLE ... ADD/DROP/ALTER COLUMN for a single column.
Extracts table and column name with regex.
For impact, we just return the table name and a fixed downtime estimate based on operation.
For reviewers, we have a config dict: {'table_owners': {'table1': 'team1', 'table2': 'team2'}} and we assign the owner team's email (or we have a mapping from team to reviewers).
For rollout windows, we have a simple config with allowed days and times.
Let's code accordingly.
However, note: the problem says "implement a schema change approval bot", so we need to provide a working example.
However, note that the problem says "Implement a schema change approval bot", so we are expected to provide a complete solution.
But given the complexity of the impact analysis, we might have to simplify.
Let's assume we are only dealing with PostgreSQL and we have the necessary permissions.
We'll improve the impact analysis by:
Getting the table OID and then querying pg_depend for direct dependencies on the table and columns.
But note: pg_depend is complex and we might not have time to get it right.
Alternatively, we can use the following query to get dependencies on a table:
SELECT
dep.refobjid AS referenced_table_oid,
dep.objid AS dependent_object_oid,
cls.relname AS dependent_object_name,
dep.deptype
FROM pg_depend dep
JOIN pg_class cls ON dep.objid = cls.oid
WHERE dep.refobjid = (SELECT oid FROM pg_class WHERE relname = %s)
AND dep.refobjsubid = 0 -- for table-level dependencies
AND dep.deptype = 'n' -- normal dependency?
But for column-level dependencies, we need refobjsubid = column_attnum.
We are not going to implement the full thing.
Given the time, we'll stick to the simple version and just note that the impact analysis is simplified.
We'll also note that the bot should be extended with better parsing and dependency analysis.
Let's write the code accordingly.
We'll also assume that the db_connection is a psycopg2 connection (for PostgreSQL).
Let's code accordingly.
However, note: the problem does not specify the database, so we'll make it database-agnostic in the interface, but the implementation is PostgreSQL-specific.
We assume the rollout windows are in the local timezone? We'll assume UTC for simplicity.
Let's code accordingly.
We'll use datetime for time calculations.
Now, note: the check_rollout_window method returns a tuple (is_allowed, suggestion) when proposed_time is given.
When proposed_time is None, it returns (None, next_window).
We'll adjust.
Let's write the code.
However, note: the _next_window function might be inefficient and not handle all cases (like windows that span midnight). We'll assume windows are within a single day.
We'll also assume that the windows are given in 24-hour format.
Let's code accordingly.
We'll now write the complete code.
But note: the impact analysis uses a simple regex and doesn't handle multiple changes in one DDL.
We'll improve the parser to handle multiple columns? Not in this version.
We'll just handle one column change per DDL.
Let's write the code accordingly.
We'll also note that the table size query might fail if the table doesn't exist? But the DDL is about to change it, so it might exist.
We'll catch exceptions and set table_size to None.
Let's code.
I'll design a comprehensive schema change approval bot system that handles impact analysis, reviewer assignment, and rollout window management. Here's a complete implementation:
python
def analyze_impact(self, ddl_statement):
# Connect to the database and get the current schema for the relevant objects?
# Or we might have a cached schema? Let's assume we have a method to get current schema.
# Parse the DDL to see what is being changed.
# We can use a SQL parser (like sqlparse for Python) or simple regex? But note: DDL can be complex.
# Since parsing SQL is complex, we might rely on the database's own parser?
# Alternatively, we can try to run the DDL in a transaction and then rollback, and capture the changes?
# But that might be dangerous.
# Better: use a SQL parser library. We'll use `sqlparse` for basic parsing, but note it doesn't validate.
# Steps for impact analysis:
# 1. Extract the type of statement (CREATE, ALTER, DROP) and the object type (TABLE, COLUMN, INDEX, etc.)
# 2. For ALTER TABLE, we need to know which table and what change.
# 3. Then we need to check the current schema for that table and its dependencies.
# We'll break down the DDL and then for each affected object, we check:
# - If we are adding a column: check if there are views that use this table? (We might not be able to easily check without parsing views)
# - If we are dropping a column: check if any other objects (views, procedures) reference it.
# - If we are changing a column type: check for implicit conversions in dependent objects.
# This is a very hard problem. We might need to use the database's system catalog to find dependencies.
# For PostgreSQL, we can use `pg_depend` and `pg_constraint` to find dependencies.
# Let's assume we are working with PostgreSQL.
# Approach for PostgreSQL:
# 1. Parse the DDL to get the table and column names involved.
# 2. Query the system catalogs to find:
# - Views that depend on the table/column.
# - Foreign key constraints that reference the table/column.
# - Stored procedures/functions that use the table/column (this is harder, we might need to parse the function bodies).
# We'll start with a simpler approach: only check for direct dependencies (like foreign keys and views) and ignore functions.
# Also, we can check if the table is large and the change might cause a long lock.
# We can estimate downtime by:
# - For adding a column: usually fast, but if we set a default, it might rewrite the table (if the default is not null and the table is large).
# - For dropping a column: usually fast (just metadata change) in PostgreSQL.
# - For changing a column type: might require a table rebuild.
# We can get the table size from `pg_total_relation_size` and the lock type required.
# But note: PostgreSQL 12+ has `ALTER TABLE ... ADD COLUMN ... DEFAULT` that doesn't rewrite the table if the default is not null? Actually, it does if you add a column with a non-null default to a non-empty table.
# So we need to parse the DDL and then check the table size and the type of change.
# Given the complexity, we might break the problem:
# Step 1: Parse the DDL to get:
# - operation (ALTER, CREATE, DROP)
# - object_type (TABLE, COLUMN, INDEX, etc.)
# - table_name (if applicable)
# - column_name (if applicable)
# - new_type (if changing type)
# Step 2: For each table affected, get:
# - size of the table (in pages or bytes)
# - existing locks (maybe from pg_locks? but that's current, not future)
# - dependencies:
# * views: from `pg_views` and `pg_depend`? We can use `pg_catalog.pg_depend` to find objects that depend on this table/column.
# * foreign keys: from `information_schema.table_constraints` and `key_column_usage`.
# Step 3: Estimate the time:
# - For adding a column with a default that is not null:
# If the table is empty, it's fast. If not, it will rewrite the table. The time is proportional to the table size and I/O.
# - For changing a column type:
# If the change is safe (e.g., varchar(100) to varchar(200)) then it's fast. But if it's a type change that requires conversion (like int to varchar) then it will rewrite.
# We can check the old type and new type. If they are binary compatible? We might have a mapping.
# This is a huge task. For the sake of this example, let's assume we have a simplified set of rules.
# We'll assume we have a function that can parse the DDL and return a structured object.
# Let's define:
# class TableChange:
# table_name: str
# changes: list of ColumnChange
# class ColumnChange:
# column_name: str
# operation: 'ADD' | 'DROP' | 'ALTER'
# old_type: Optional[str]
# new_type: Optional[str]
# default: Optional[str] # the default value if being set
# Then, for each TableChange, we get the table size and then compute:
# if operation is ADD and default is not None and default != 'NULL':
# if table_size > 0:
# downtime_estimate = f"Table rewrite expected. Size: {table_size}. This may take {estimate_time(table_size)}."
# else:
# downtime_estimate = "Fast (table is empty)."
# if operation is ALTER and old_type != new_type:
# if are_types_binary_compatible(old_type, new_type):
# downtime_estimate = "Fast (type change is binary compatible)."
# else:
# downtime_estimate = f"Table rewrite expected. Size: {table_size}. This may take {estimate_time(table_size)}."
# We can have a function `are_types_binary_compatible` that returns True for safe changes (like int to bigint, varchar(100) to varchar(200)).
# We also check for dependencies:
# For each column change, we check if there are any views or foreign keys that reference that column.
# We return an ImpactReport:
# class ImpactReport:
# affected_tables: list of TableImpact
# estimated_downtime: str
# risky_dependencies: list of str (e.g., "view my_view depends on table my_table")
# This is a very simplified version.
# Given the complexity, we might just simulate by running the DDL in a transaction and then rollback, and then use `EXPLAIN`? But that won't work for DDL.
# Alternatively, we can use the `pg_ddl` extension? Not standard.
# Given the time, we'll implement a very basic version that just extracts table and column names and then checks for foreign keys and views by querying the system catalogs.
# We'll do:
# For each table in the DDL:
# Get the table OID from pg_class.
# Then, from pg_depend, find objects that depend on this table (or its columns) and then get their names and types.
# But note: pg_depend might not capture all dependencies (like if a view uses a function that uses the table, it might not be direct).
# We'll stick to direct dependencies.
# Steps:
# 1. Parse the DDL to get the list of tables and columns being changed.
# 2. For each table, get its OID.
# 3. For each column, get its attribute number (attnum) in the table.
# 4. Query pg_depend for objects that depend on the table (objid = table_oid) or on the column (objid = column_attnum and deptype = 'n'? Actually, in pg_depend, for a column, the refobjid is the table and refobjsubid is the column attnum).
# This is getting too complex for a simple example.
# Given the constraints, let's assume we have a helper function that can parse the DDL and return the table and column names.
# We'll use sqlparse to split the DDL and then extract table and column names with regex.
# This is error-prone but for the example.
# Alternatively, we can use a library like `pg_query` (for PostgreSQL) but that's external.
# We'll do a very simple regex for ALTER TABLE:
# pattern: r'ALTER TABLE\s+(\w+)\s+(ADD|DROP|ALTER)\s+(COLUMN\s+)?(\w+)'
# But this won't capture multiple changes in one statement.
# Given the time, let's assume the DDL is one change at a time.
# We'll do:
# if the DDL starts with "ALTER TABLE":
# extract table name, operation, and column name.
# Then, we can check:
# dependencies = []
# # Check views
# query = """
# SELECT viewname FROM pg_views
# WHERE definition LIKE %s
# """
# # But this is inefficient and might have false positives.
# Given the time, we'll just return a fixed report for the example.
# We'll return:
# affected_tables: [table_name]
# estimated_downtime: "unknown"
# risky_dependencies: []
# And then we'll improve if we have time.
# But note: the requirement is to implement the bot, not necessarily a perfect analyzer.
# So we'll do a minimal version.
pass
def assign_reviewers(self, ddl_statement, current_user=None):
# We'll have a config that maps table names to owners (or teams).
# We can extract the table name from the DDL (using the same simple method as above).
# Then look up the owner for that table.
# Also, we might have mandatory reviewers (like DBAs) that are always added.
# We return a list of reviewers (usernames or emails).
pass
def check_rollout_window(self, proposed_time=None):
# If proposed_time is given, check if it's in the allowed windows.
# If not, return the next allowed time.
# The config might have:
# rollout_windows: [
# {"day_of_week": [0,6], "start_time": "02:00", "end_time": "04:00"}, # Sunday and Saturday, 2am-4am
# {"day_of_week": [1,2,3,4,5], "start_time": "22:00", "end_time": "23:59"} # Weekdays after 10pm
# ]
# We'll convert the proposed_time (a datetime) to day of week (0=Monday, 6=Sunday) and time.
# Then check if it falls within any of the windows.
# If no proposed_time, we can calculate the next window.
pass
def parse_ddl(self, ddl):
# Very simple parser for ALTER TABLE ... [ADD|DROP|ALTER] COLUMN ...
import re
pattern = r'ALTER\s+TABLE\s+(\w+)\s+(ADD|DROP|ALTER)\s+COLUMN\s+(\w+)'
match = re.search(pattern, ddl, re.IGNORECASE)
if match:
table_name = match.group(1)
operation = match.group(2).upper()
column_name = match.group(3)
return {
'table_name': table_name,
'operation': operation,
'column_name': column_name
}
else:
# Try to handle CREATE TABLE? We'll just return None.
return None
def analyze_impact(self, ddl_statement):
parsed = self.parse_ddl(ddl_statement)
if not parsed:
return {
'affected_tables': [],
'estimated_downtime': 'Could not parse DDL.',
'risky_dependencies': []
}
table_name = parsed['table_name']
operation = parsed['operation']
column_name = parsed['column_name']
# Get table size (if we have a db connection)
table_size = None
try:
with self.db_connection.cursor() as cursor:
cursor.execute("SELECT pg_total_relation_size(%s::regclass)", (table_name,))
table_size = cursor.fetchone()[0]
except Exception as e:
table_size = None
# Estimate downtime
downtime_estimate = "Unknown"
if operation == 'ADD':
# If we are adding a column with a default? We don't parse the default, so we assume it's NULL or no default.
# In PostgreSQL, adding a column without a default is fast (metadata only). With a default, it rewrites.
# We can't easily parse the DDL for the default, so we assume no default for now.
downtime_estimate = "Fast (metadata change only)."
elif operation == 'DROP':
downtime_estimate = "Fast (metadata change only)."
elif operation == 'ALTER':
# We don't know the type change, so we assume it might be a rewrite.
downtime_estimate = "May require table rebuild. Size: {} bytes. This could take time.".format(table_size) if table_size else "May require table rebuild."
# Check dependencies (we'll skip for now, but we can try to query pg_depend if we have the table OID and column attnum)
# We'll leave it empty.
return {
'affected_tables': [table_name],
'estimated_downtime': downtime_estimate,
'risky_dependencies': [] # TODO: implement
}
def assign_reviewers(self, ddl_statement, current_user=None):
parsed = self.parse_ddl(ddl_statement)
if not parsed:
return []
table_name = parsed['table_name']
# Look up owner for this table
table_owners = self.config.get('table_owners', {})
owner_team = table_owners.get(table_name, 'default_team')
# Map team to reviewers
team_reviewers = self.config.get('team_reviewers', {})
reviewers = team_reviewers.get(owner_team, [])
# Add mandatory reviewers
mandatory_reviewers = self.config.get('mandatory_reviewers', [])
reviewers = list(set(reviewers + mandatory_reviewers))
# If current_user is provided and not in reviewers, we might add them as the submitter? Not necessarily a reviewer.
# We return the list of reviewers.
return reviewers
def check_rollout_window(self, proposed_time=None):
# If proposed_time is given, check if it's allowed.
# Otherwise, calculate the next allowed time.
# We assume proposed_time is a datetime object (or None).
# The config has:
# 'rollout_windows': [
# {'days': [0,6], 'start': '02:00', 'end': '04:00'}, # 0=Monday, 6=Sunday
# {'days': [1,2,3,4,5], 'start': '22:00', 'end': '23:59'}
# ]
windows = self.config.get('rollout_windows', [])
if proposed_time:
# Check if proposed_time falls within any window.
day_of_week = proposed_time.weekday() # Monday is 0, Sunday is 6
time_str = proposed_time.strftime('%H:%M')
for window in windows:
if day_of_week in window['days']:
start = window['start']
end = window['end']
if start <= time_str <= end:
return True, None # allowed, no suggestion
return False, self._next_window(proposed_time)
else:
# Return the next window from now.
now = datetime.datetime.now()
return None, self._next_window(now)
def _next_window(self, from_time):
# Calculate the next allowed window from from_time.
# We assume windows are given in order? Not necessarily.
# We'll convert the from_time to a datetime and then check each window for the next occurrence.
# This is a simplified version: we'll just check today and then future days.
# We'll assume the windows are for recurring days.
# We'll create a list of upcoming datetimes for each window.
windows = self.config.get('rollout_windows', [])
candidates = []
for window in windows:
days = window['days']
start_time = window['start']
end_time = window['end']
# For each day in days, check if that day (from today) has a window that hasn't passed.
for day in days:
# day is 0=Monday, 6=Sunday.
# How many days from now to that day?
days_ahead = day - from_time.weekday()
if days_ahead < 0:
days_ahead += 7
candidate_date = from_time.date() + datetime.timedelta(days=days_ahead)
start_dt = datetime.datetime.combine(candidate_date, datetime.time.fromisoformat(start_time))
end_dt = datetime.datetime.combine(candidate_date, datetime.time.fromisoformat(end_time))
if start_dt > from_time:
candidates.append(start_dt)
if candidates:
return min(candidates)
else:
return None
"""
Schema Change Approval Bot
Handles impact analysis, reviewer assignment, and rollout window management for database schema changes.
"""
import re
import json
from datetime import datetime, timedelta, time
from typing import Dict, List, Optional, Tuple, Set
from dataclasses import dataclass, asdict
from enum import Enum
import logging
from abc import ABC, abstractmethod
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class ChangeType(Enum):
"""Types of schema changes"""
ADD_TABLE = "ADD_TABLE"
DROP_TABLE = "DROP_TABLE"
ALTER_TABLE = "ALTER_TABLE"
ADD_COLUMN = "ADD_COLUMN"
DROP_COLUMN = "DROP_COLUMN"
ALTER_COLUMN = "ALTER_COLUMN"
ADD_INDEX = "ADD_INDEX"
DROP_INDEX = "DROP_INDEX"
ADD_CONSTRAINT = "ADD_CONSTRAINT"
DROP_CONSTRAINT = "DROP_CONSTRAINT"
class ImpactLevel(Enum):
"""Impact severity levels"""
CRITICAL = "CRITICAL" # Full downtime, data loss risk
HIGH = "HIGH" # Brief downtime, significant risk
MEDIUM = "MEDIUM" # Minimal downtime, moderate risk
LOW = "LOW" # No downtime, low risk
NONE = "NONE" # metadata only, no impact
class ApprovalStatus(Enum):
"""Change approval statuses"""
DRAFT = "DRAFT"
SUBMITTED = "SUBMITTED"
UNDER_REVIEW = "UNDER_REVIEW"
APPROVED = "APPROVED"
REJECTED = "REJECTED"
SCHEDULED = "SCHEDULED"
ROLLED_BACK = "ROLLED_BACK"
COMPLETED = "COMPLETED"
@dataclass
class DatabaseObject:
"""Represents a database object"""
object_type: str # table, view, index, constraint, etc.
schema: str
name: str
dependencies: List[str] = None
def __post_init__(self):
if self.dependencies is None:
self.dependencies = []
@dataclass
class ChangeRequest:
"""Schema change request"""
id: str
title: str
description: str
ddl_statements: List[str]
change_type: ChangeType
affected_objects: List[DatabaseObject]
submitter: str
submission_time: datetime
status: ApprovalStatus = ApprovalStatus.DRAFT
impact_level: Optional[ImpactLevel] = None
impact_report: Optional[Dict] = None
estimated_duration: Optional[timedelta] = None
assigned_reviewers: List[str] = None
required_reviewers: List[str] = None
rollout_window: Optional[Dict] = None
approved_by: List[str] = None
rejection_reason: Optional[str] = None
scheduled_time: Optional[datetime] = None
completion_time: Optional[datetime] = None
def __post_init__(self):
if self.affected_objects is None:
self.affected_objects = []
if self.assigned_reviewers is None:
self.assigned_reviewers = []
if self.required_reviewers is None:
self.required_reviewers = []
if self.approved_by is None:
self.approved_by = []
class ImpactAnalyzer(ABC):
"""Abstract base class for impact analysis"""
@abstractmethod
def analyze(self, ddl: List[str], database_state: Dict) -> Dict:
"""Analyze impact of DDL changes"""
pass
@abstractmethod
def estimate_duration(self, change_type: ChangeType,
table_size: int, row_count: int) -> timedelta:
"""Estimate execution duration"""
pass
class PostgreSQLImpactAnalyzer(ImpactAnalyzer):
"""PostgreSQL-specific impact analyzer"""
def analyze(self, ddl: List[str], database_state: Dict) -> Dict:
"""Analyze PostgreSQL schema changes"""
impact = {
"affected_tables": set(),
"affected_columns": set(),
"dependent_objects": set(),
"requires_rebuild": False,
"locks_required": set(),
"estimated_rows_affected": 0,
"risks": []
}
for statement in ddl:
statement_upper = statement.upper()
# Extract table name (simplified - use proper parser in production)
table_match = re.search(r'TABLE\s+([^\s(]+)', statement_upper)
if table_match:
table_name = table_match.group(1).lower()
impact["affected_tables"].add(table_name)
# Check for operations that require table rebuild
if any(op in statement_upper for op in ['ALTER COLUMN', 'TYPE', 'SET DEFAULT']):
impact["requires_rebuild"] = True
impact["locks_required"].add("ACCESS EXCLUSIVE")
# Check for operations that block reads/writes
if 'DROP' in statement_upper:
impact["locks_required"].add("ACCESS EXCLUSIVE")
# Estimate row count affected (simplified)
if 'ADD COLUMN' in statement_upper:
impact["estimated_rows_affected"] = database_state.get("total_rows", 0)
# Find dependent objects from database state
for table in impact["affected_tables"]:
if table in database_state.get("dependencies", {}):
impact["dependent_objects"].update(
database_state["dependencies"][table]
)
# Determine impact level
impact["impact_level"] = self._determine_impact_level(impact, database_state)
# Add risk assessments
if impact["requires_rebuild"] and database_state.get("table_size", 0) > 1000000:
impact["risks"].append("Large table rebuild may cause significant downtime")
if impact["locks_required"]:
impact["risks"].append(f"Requires locks: {', '.join(impact['locks_required'])}")
return impact
def _determine_impact_level(self, impact: Dict, database_state: Dict) -> ImpactLevel:
"""Determine impact severity"""
if impact["requires_rebuild"]:
table_size = database_state.get("table_size", 0)
if table_size > 10000000: # 10M rows
return ImpactLevel.CRITICAL
elif table_size > 1000000: # 1M rows
return ImpactLevel.HIGH
else:
return ImpactLevel.MEDIUM
if "DROP" in [s.upper() for s in impact["affected_columns"]]:
return ImpactLevel.MEDIUM
if impact["dependent_objects"]:
return ImpactLevel.MEDIUM
return ImpactLevel.LOW
def estimate_duration(self, change_type: ChangeType,
table_size: int, row_count: int) -> timedelta:
"""Estimate execution time based on change type and table size"""
base_time = timedelta(seconds=10)
if change_type in [ChangeType.ADD_COLUMN, ChangeType.DROP_INDEX]:
# Metadata-only changes
return base_time
if change_type in [ChangeType.ALTER_COLUMN, ChangeType.ADD_CONSTRAINT]:
# May require table scan/rebuild
if table_size > 1000000:
# Estimate 1 second per 1000 rows for large tables
return timedelta(seconds=10 + (table_size // 1000))
return timedelta(seconds=30)
if change_type in [ChangeType.DROP_COLUMN, ChangeType.ADD_TABLE]:
return timedelta(seconds=15)
return base_time
class ReviewerManager:
"""Manages reviewer assignment and escalation"""
def __init__(self, config: Dict):
self.config = config