Skip to content

Commit

Permalink
try db clone through shutil copy
Browse files Browse the repository at this point in the history
  • Loading branch information
CuriousLearner committed Nov 26, 2024
1 parent 76ef904 commit 4800bf8
Showing 1 changed file with 11 additions and 12 deletions.
23 changes: 11 additions & 12 deletions src/django_libsql/creation.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,28 +227,27 @@ def _clone_test_db(self, suffix, verbosity, keepdb=False):
"""
Internal implementation - duplicate the test db tables.
"""
import os
import shutil

try:
# Get the source database name from settings
source_database = self.connection.settings_dict["NAME"]
clone_database = f"{source_database}_{suffix}"

# Use the existing database connection to clone
conn = self.connection.get_new_connection(self.connection.connection_params())

# Attach the clone database
conn.execute(f"ATTACH DATABASE '{clone_database}' AS clone_db")
# If `keepdb` is False, ensure the cloned database doesn't already exist
if not keepdb and os.path.exists(clone_database):
os.remove(clone_database)

# Copy all tables to the clone database
tables = conn.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()
for table in tables:
table_name = table[0]
conn.execute(f"CREATE TABLE clone_db.{table_name} AS SELECT * FROM main.{table_name}")
# Copy the source database file to create the clone
shutil.copy2(source_database, clone_database)

# Detach the clone database
conn.execute("DETACH DATABASE clone_db")
# Update the connection to point to the cloned database
self.connection.settings_dict["NAME"] = clone_database

if verbosity >= 1:
print(f"Cloned test database '{source_database}' to '{clone_database}'")

except Exception as e:
raise NotImplementedError(
"Cloning databases is not supported for this backend."
Expand Down

0 comments on commit 4800bf8

Please sign in to comment.