diff --git a/features_api_database/infrastructure/config.py b/features_api_database/infrastructure/config.py index 765eb6b..10a91a1 100644 --- a/features_api_database/infrastructure/config.py +++ b/features_api_database/infrastructure/config.py @@ -99,6 +99,10 @@ class FeaturesDBSettings(BaseSettings): False, description="Boolean if the RDS should be encrypted", ) + rds_deletion_protection: Optional[bool] = Field( + True, + description="Config to temporarily disable deletion protection for certain maintenance operations. Be sure to reenable after work is complete.", + ) max_allocated_storage: Optional[int] = Field( 500, description="Upper limit to which RDS can scale the storage in GiB(Gibibyte)", diff --git a/features_api_database/infrastructure/construct.py b/features_api_database/infrastructure/construct.py index 0b92c18..258b7b7 100644 --- a/features_api_database/infrastructure/construct.py +++ b/features_api_database/infrastructure/construct.py @@ -180,8 +180,8 @@ def __init__( "engine": engine, "instance_type": rds_instance_type, "vpc_subnets": self.vpc_subnets, - "deletion_protection": True, - "removal_policy": RemovalPolicy.RETAIN, + "deletion_protection": features_db_settings.rds_deletion_protection, + "removal_policy": RemovalPolicy.RETAIN_ON_UPDATE_OR_DELETE, "publicly_accessible": features_db_settings.publicly_accessible, "parameter_group": parameter_group, } diff --git a/features_api_database/runtime/handler.py b/features_api_database/runtime/handler.py index a3e6aa1..a36dcec 100644 --- a/features_api_database/runtime/handler.py +++ b/features_api_database/runtime/handler.py @@ -107,29 +107,24 @@ def create_user(cursor, username: str, password: str) -> None: try: # Check if user exists before - cursor.execute("SELECT rolname FROM pg_roles WHERE rolname = %s", (username,)) - exists_before = cursor.fetchone() is not None + cursor.execute("SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = %s)", (username,)) + exists_before = cursor.fetchone()[0] print(f"DEBUG: User '{username}' exists before: {exists_before}") # Create/update user - cursor.execute( - sql.SQL( - "DO $$ " - "BEGIN " - " IF NOT EXISTS ( " - " SELECT 1 FROM pg_roles " - " WHERE rolname = {user}) " - " THEN " - " CREATE USER {username} " - " WITH PASSWORD {password}; " - " ELSE " - " ALTER USER {username} " - " WITH PASSWORD {password}; " - " END IF; " - "END " - "$$; " - ).format(username=sql.Identifier(username), password=sql.Identifier(password), user=sql.Identifier(username)) - ) + if exists_before: + cursor.execute( + sql.SQL( + "ALTER USER {username} WITH PASSWORD {password};" + ).format(username=sql.Identifier(username), password=password) + ) + else: + cursor.execute( + sql.SQL( + "CREATE USER {username} WITH PASSWORD {password};" + ).format(username=sql.Identifier(username), password=password) + ) + print(f"DEBUG: SQL executed successfully") # Check if user exists after