Skip to content
Merged
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from os import path
from typing import AsyncGenerator
from contextlib import asynccontextmanager
from sqlalchemy import text, select
from sqlalchemy import text, select, MetaData
from sqlalchemy.orm import joinedload
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker

Expand Down Expand Up @@ -119,12 +119,22 @@ async def delete_database(self):
self.db_path = None
else:
async with self.engine.begin() as connection:
# Load the schema information into the MetaData object
await connection.run_sync(Base.metadata.reflect)
for table in Base.metadata.sorted_tables:
drop_table_query = text(f"DROP TABLE IF EXISTS {table.name} CASCADE")
await connection.execute(drop_table_query)

result = await connection.execute(
text("""
SELECT schema_name FROM information_schema.schemata
WHERE schema_name NOT IN ('pg_catalog', 'pg_toast', 'information_schema');
""")
)
# Create a MetaData instance to load table information
metadata = MetaData()
# Drop all tables from all schemas
for schema in result.fetchall():
# Load the schema information into the MetaData object
await connection.run_sync(metadata.reflect, schema=schema[0])
for table in metadata.sorted_tables:
drop_table_query = text(f"DROP TABLE IF EXISTS {schema[0]}.{table.name} CASCADE")
await connection.execute(drop_table_query)
metadata.clear()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider dropping entire schemas instead of individual tables

Currently, the delete_database method iterates over each table within each schema and drops them individually. This can be inefficient, especially if there are many tables or other objects within the schemas. Dropping the entire schema in a single operation is more efficient and ensures that all objects within the schema are removed.

Apply this diff to simplify the database deletion process:

+                    # Drop entire schemas instead of individual tables
                     for schema in result.fetchall():
-                        # Load the schema information into the MetaData object
-                        await connection.run_sync(metadata.reflect, schema=schema[0])
-                        for table in metadata.sorted_tables:
-                            drop_table_query = text(f"DROP TABLE IF EXISTS {schema[0]}.{table.name} CASCADE")
-                            await connection.execute(drop_table_query)
-                        metadata.clear()
+                        drop_schema_query = text(f'DROP SCHEMA IF EXISTS "{schema[0]}" CASCADE')
+                        await connection.execute(drop_schema_query)

This modification:

  • Drops each schema using the DROP SCHEMA command with the CASCADE option, which removes the schema and all dependent objects.
  • Simplifies the code by eliminating the need to reflect metadata and iterate over tables.
  • Enhances performance by reducing the number of database operations.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
result = await connection.execute(
text("""
SELECT schema_name FROM information_schema.schemata
WHERE schema_name NOT IN ('pg_catalog', 'pg_toast', 'information_schema');
""")
)
# Create a MetaData instance to load table information
metadata = MetaData()
# Drop all tables from all schemas
for schema in result.fetchall():
# Load the schema information into the MetaData object
await connection.run_sync(metadata.reflect, schema=schema[0])
for table in metadata.sorted_tables:
drop_table_query = text(f"DROP TABLE IF EXISTS {schema[0]}.{table.name} CASCADE")
await connection.execute(drop_table_query)
metadata.clear()
result = await connection.execute(
text("""
SELECT schema_name FROM information_schema.schemata
WHERE schema_name NOT IN ('pg_catalog', 'pg_toast', 'information_schema');
""")
)
# Create a MetaData instance to load table information
metadata = MetaData()
# Drop entire schemas instead of individual tables
for schema in result.fetchall():
drop_schema_query = text(f'DROP SCHEMA IF EXISTS "{schema[0]}" CASCADE')
await connection.execute(drop_schema_query)

except Exception as e:
print(f"Error deleting database: {e}")

Expand Down