Skip to content

Bulk asynchronous downloader for multiple file hosts

Implement Database Transfer Tool (#1766)

Jacob90a4eb42a8e0
diff --git a/cyberdrop_dl/__main__.py b/cyberdrop_dl/__main__.py
index 36382b0a3..952064b63 100644
--- a/cyberdrop_dl/__main__.py
+++ b/cyberdrop_dl/__main__.py
@@ -2,9 +2,10 @@
import logging
import sys
from collections.abc import Sequence
+from pathlib import Path
from typing import Annotated
-from cyclopts import App, CycloptsPanel, Parameter
+from cyclopts import App, CycloptsPanel, Parameter, validators
from cyberdrop_dl import __version__, aio, program_ui, tracebacks, webhook
@@ -12,6 +13,7 @@ tracebacks.install_exception_hook()
from cyberdrop_dl.cli import CLIargs
from cyberdrop_dl.config import Config
+from cyberdrop_dl.database.transfer import run as transfer_db
from cyberdrop_dl.logs import log_spacer, set_console_level, setup_console_logging, setup_file_logging
from cyberdrop_dl.manager import AppData, Manager
from cyberdrop_dl.models.types import HttpURL
@@ -95,6 +97,14 @@ app = App(
result_action="return_value",
)
+database_app = App(
+ name="cyberdrop-dl database",
+ help="Commands for managing the database",
+ version=__version__,
+)
+
+app.command(database_app, "database")
+
@app.default()
def download(
@@ -134,6 +144,26 @@ def show() -> None:
app.console.print(table)
+@database_app.command()
+def transfer(
+ db_path: Annotated[
+ Path,
+ Parameter(
+ help="Path to the SQLite database file to migrate",
+ validator=validators.Path(exists=True, file_okay=True, dir_okay=False, ext=".db"),
+ ),
+ ],
+ force: Annotated[
+ bool,
+ Parameter(
+ help="Skip the 'already latest' early-exit check and run all migration steps regardless of detected version"
+ ),
+ ] = False,
+) -> None:
+ """Migrate an old database to the latest schema version."""
+ transfer_db(db_path, force=force)
+
+
def main(args: Sequence[str] | None = None) -> None:
with setup_console_logging():
try:
diff --git a/cyberdrop_dl/database/__init__.py b/cyberdrop_dl/database/__init__.py
index 456f76bc3..d7f2d7b33 100644
--- a/cyberdrop_dl/database/__init__.py
+++ b/cyberdrop_dl/database/__init__.py
@@ -12,6 +12,12 @@ if TYPE_CHECKING:
from pathlib import Path
+async def connect(path: Path) -> aiosqlite.Connection:
+ db_conn = await aiosqlite.connect(path, timeout=20)
+ db_conn.row_factory = aiosqlite.Row
+ return db_conn
+
+
@dataclasses.dataclass(slots=True)
class Database:
_db_path: Path
@@ -28,8 +34,7 @@ class Database:
self.schema = SchemaVersionTable(self)
async def __aenter__(self) -> Self:
- self._db_conn = await aiosqlite.connect(self._db_path, timeout=20)
- self._db_conn.row_factory = aiosqlite.Row
+ self._db_conn = await connect(self._db_path)
await self._pre_allocate()
await self.history.create()
await self.hash.create()
diff --git a/cyberdrop_dl/database/tables/history.py b/cyberdrop_dl/database/tables/history.py
index 23b4e2b92..62d7bb2f1 100644
--- a/cyberdrop_dl/database/tables/history.py
+++ b/cyberdrop_dl/database/tables/history.py
@@ -31,46 +31,12 @@ class HistoryTable:
return self._database._db_conn
async def create(self) -> None:
- from cyberdrop_dl.crawlers import cyberdrop, jpg5, redgifs, turbovid
-
- def try_wrap(fn):
- def call(*args, **kwargs):
- try:
- return fn(*args, **kwargs)
- except BaseException:
- logger.exception(f"{fn.__name__} failed")
- raise
-
- return call
-
- for name, fn in [
- ("FIX_REDGIFS_REFERER", redgifs.fix_db_referer),
- ("FIX_JPG5_REFERER", jpg5.fix_db_referer),
- ("FIX_CYBERDROP_REFERER", cyberdrop.fix_db_referer),
- ("FIX_TURBOVID_REFERER", turbovid.fix_db_referer),
- ]:
- await self.db_conn.create_function(name, 1, try_wrap(fn), deterministic=True)
-
await self.db_conn.execute(create_history)
await self.db_conn.commit()
await self.fix_primary_keys()
await self.add_columns_media()
- await self.run_updates()
-
- async def run_updates(self) -> None:
- updates = (
- "UPDATE OR REPLACE media SET domain = 'bunkr' WHERE domain = 'bunkrr';"
- "UPDATE OR REPLACE media SET domain = 'jpg5.su' WHERE domain = 'sharex';"
- "UPDATE OR REPLACE media SET domain = 'turbovid' WHERE domain = 'saint';"
- "UPDATE OR REPLACE media SET domain = 'nudostar.tv' WHERE domain = 'nudostartv';"
- "UPDATE OR REPLACE media SET referer = FIX_REDGIFS_REFERER(referer) WHERE domain = 'redgifs';"
- "UPDATE OR REPLACE media SET referer = FIX_JPG5_REFERER(referer) WHERE domain = 'jpg5.su';"
- "UPDATE OR REPLACE media SET referer = FIX_CYBERDROP_REFERER(referer) WHERE domain = 'cyberdrop';"
- "UPDATE OR REPLACE media SET referer = FIX_TURBOVID_REFERER(referer) WHERE domain = 'turbovid';"
- )
-
- await self.db_conn.executescript(updates)
- await self.db_conn.commit()
+ await fix_domains(self.db_conn)
+ await fix_referers(self.db_conn)
await self.db_conn.executescript(create_media_index)
await self.db_conn.commit()
@@ -323,3 +289,52 @@ class HistoryTable:
if script:
await self.db_conn.executescript(script)
await self.db_conn.commit()
+
+
+async def fix_domains(db_conn: aiosqlite.Connection) -> None:
+ logger.info("Updating old domains")
+ updates = "\n".join(
+ f"UPDATE OR REPLACE media SET domain = '{current}' WHERE domain = '{old}';"
+ for current, old in [
+ ("bunkr", "bunkrr"),
+ ("jpg5.su", "sharex"),
+ ("turbovid", "saint"),
+ ("nudostar.tv", "nudostartv"),
+ ]
+ )
+ await db_conn.executescript(updates)
+ await db_conn.commit()
+
+
+async def fix_referers(db_conn: aiosqlite.Connection):
+ from cyberdrop_dl.crawlers import cyberdrop, jpg5, redgifs, turbovid
+
+ logger.info("Updating old referers")
+
+ def try_wrap(fn):
+ def call(*args, **kwargs):
+ try:
+ return fn(*args, **kwargs)
+ except BaseException:
+ logger.exception(f"{fn.__name__} failed")
+ raise
+
+ return call
+
+ for name, fn in [
+ ("FIX_REDGIFS_REFERER", redgifs.fix_db_referer),
+ ("FIX_JPG5_REFERER", jpg5.fix_db_referer),
+ ("FIX_CYBERDROP_REFERER", cyberdrop.fix_db_referer),
+ ("FIX_TURBOVID_REFERER", turbovid.fix_db_referer),
+ ]:
+ await db_conn.create_function(name, 1, try_wrap(fn), deterministic=True)
+
+ updates = (
+ "UPDATE OR REPLACE media SET referer = FIX_REDGIFS_REFERER(referer) WHERE domain = 'redgifs';"
+ "UPDATE OR REPLACE media SET referer = FIX_JPG5_REFERER(referer) WHERE domain = 'jpg5.su';"
+ "UPDATE OR REPLACE media SET referer = FIX_CYBERDROP_REFERER(referer) WHERE domain = 'cyberdrop';"
+ "UPDATE OR REPLACE media SET referer = FIX_TURBOVID_REFERER(referer) WHERE domain = 'turbovid';"
+ )
+
+ await db_conn.executescript(updates)
+ await db_conn.commit()
diff --git a/cyberdrop_dl/database/transfer.py b/cyberdrop_dl/database/transfer.py
new file mode 100644
index 000000000..565c8fcd1
--- /dev/null
+++ b/cyberdrop_dl/database/transfer.py
@@ -0,0 +1,228 @@
+from __future__ import annotations
+
+import asyncio
+import datetime
+import logging
+import sqlite3
+import sys
+from pathlib import Path
+
+from cyberdrop_dl.database import Database, connect
+from cyberdrop_dl.database.tables.history import fix_domains, fix_referers
+from cyberdrop_dl.database.tables.schema import CURRENT_APP_SCHEMA_VERSION, Version
+from cyberdrop_dl.logs import setup_console_logging
+from cyberdrop_dl.utils.filepath import sanitize_filename
+
+logger = logging.getLogger(__name__)
+
+
+def _get_table_names(conn: sqlite3.Connection, schema: str = "main") -> set[str]:
+ rows = conn.execute(f"SELECT name FROM {schema}.sqlite_master WHERE type='table'").fetchall()
+ return {r[0] for r in rows}
+
+
+def _get_column_names(conn: sqlite3.Connection, table: str, schema: str = "main") -> set[str]:
+ rows = conn.execute(f"PRAGMA {schema}.table_info({table})").fetchall()
+ return {r[1] for r in rows}
+
+
+def _get_column_info(conn: sqlite3.Connection, table: str, schema: str = "main") -> list[tuple[str, str | None]]:
+ """Return `[(col_name, default_value), ...]` for every column in *table*.
+
+ *default_value* is the literal SQL default from the schema, or `None` when no default is declared."""
+
+ # PRAGMA table_info columns: cid | name | type | notnull | dflt_value | pk
+ rows = conn.execute(f"PRAGMA {schema}.table_info({table})").fetchall()
+ return [(r[1], r[4]) for r in rows]
+
+
+def _get_applied_versions(conn: sqlite3.Connection) -> list[str]:
+ try:
+ rows = conn.execute("SELECT version FROM schema_version").fetchall()
+ return [r[0] for r in rows]
+ except sqlite3.OperationalError:
+ return []
+
+
+def detect_version(conn: sqlite3.Connection) -> Version | None:
+ tables = _get_table_names(conn)
+
+ if "schema_version" in tables:
+ versions = _get_applied_versions(conn)
+ if versions:
+ return Version.parse(sorted(versions)[-1])
+
+ if tables == {"media", "downloads_temp", "coomeno"}:
+ return Version(4, 2, 231)
+
+ if tables == {"media", "temp"}:
+ return Version(5, 3, 31)
+
+ if tables == {"media", "files", "hash"}:
+ media_cols = _get_column_names(conn, "media")
+ if "duration" in media_cols:
+ return Version(6, 10, 1) # v6.10.1 - v7.5.0
+ return Version(6, 5, 0)
+
+ return None
+
+
+def _transfer_table(new_conn: sqlite3.Connection, table: str) -> None:
+ """Transfer rows from `old.<table>` into the new `<table>`.
+
+ The SELECT list is built dynamically:
+ - columns that exist in the old table are selected by name;
+ - columns that are only in the current schema are filled with their declared schema default or `NULL`."""
+
+ old_tables = _get_table_names(new_conn, schema="old")
+ if table not in old_tables:
+ logger.debug("_transfer_table: %s absent in old DB, skipping", table)
+ return
+
+ old_cols = _get_column_names(new_conn, table, schema="old")
+ new_col_info = _get_column_info(new_conn, table, schema="main")
+
+ col_names: list[str] = []
+ select_exprs: list[str] = []
+
+ for name, default in new_col_info:
+ col_names.append(f'"{name}"')
+ if name in old_cols:
+ select_exprs.append(f'"{name}"')
+ else:
+ # Use the declared default value, or NULL when none is specified.
+ fallback = default if default is not None else "NULL"
+ select_exprs.append(f'{fallback} AS "{name}"')
+
+ cols_sql = ", ".join(col_names)
+ select_sql = ", ".join(select_exprs)
+
+ logger.info("_transfer_table: old.%s -> %s", table, table)
+ new_conn.execute(f'INSERT OR IGNORE INTO "{table}" ({cols_sql}) SELECT {select_sql} FROM old."{table}"')
+
+
+def _transfer_media_to_files(new_conn: sqlite3.Connection) -> None:
+ """Populate the new `files` table from `old.media`."""
+
+ old_tables = _get_table_names(new_conn, schema="old")
+ if "media" not in old_tables:
+ logger.debug("_transfer_media_to_files: no old media table, skipping")
+ return
+
+ old_media_cols = _get_column_names(new_conn, "media", schema="old")
+ file_size_expr = '"file_size"' if "file_size" in old_media_cols else "NULL"
+
+ logger.info("_transfer_media_to_files: old.media -> files")
+ # download_path is not absolute in older versions, but we can still use it to populate the folder column.
+ new_conn.execute(
+ f"""
+ INSERT OR IGNORE INTO "files"
+ ("folder", "download_filename", "original_filename", "file_size", "referer", "date")
+ SELECT
+ "download_path",
+ "download_filename",
+ "original_filename",
+ {file_size_expr},
+ "referer",
+ CAST(strftime('%s', "created_at") AS INTEGER)
+ FROM old."media"
+ WHERE "download_path" IS NOT NULL
+ """
+ )
+
+
+# TransferManager
+
+# Tables whose rows are transferred column-by-column, in dependency order.
+_DIRECT_TRANSFER_TABLES = ["media", "hash", "files"]
+
+_SKIP_TABLES = {"schema_version"}
+
+
+def run(db_path: Path, *, force: bool = False) -> None:
+ if not db_path.exists():
+ raise FileNotFoundError(f"Database not found: {db_path}")
+
+ with sqlite3.connect(db_path) as probe:
+ old_version = detect_version(probe)
+
+ logger.info("Detected schema version: %s", old_version)
+
+ if not force and old_version == CURRENT_APP_SCHEMA_VERSION:
+ logger.info(
+ "Database is already at the latest schema (%s). Use --force to re-run.",
+ CURRENT_APP_SCHEMA_VERSION,
+ )
+ return
+
+ now = sanitize_filename(str(datetime.datetime.now()))
+ new_path = db_path.with_name(f"{db_path.stem}_{CURRENT_APP_SCHEMA_VERSION}_{now}{db_path.suffix}")
+
+ logger.debug("Creating new database at: %s", new_path)
+ _create_new_database(new_path)
+ with sqlite3.connect(new_path) as new_conn:
+ new_conn.execute("PRAGMA foreign_keys=OFF")
+ new_conn.execute(f"ATTACH DATABASE '{db_path}' AS old")
+ try:
+ _transfer(new_conn)
+ except Exception:
+ new_conn.rollback()
+ new_conn.close()
+ logger.exception("Transfer failed - original database has NOT been changed")
+ new_path.unlink()
+ raise
+ else:
+ new_conn.commit()
+
+ _apply_fixes(new_path)
+ backup_path = db_path.with_name(f"{db_path.stem}_{old_version}_{now}.backup{db_path.suffix}")
+ db_path.rename(backup_path)
+ new_path.rename(db_path)
+ logger.info("Transfer complete", extra={"color": "green"})
+ logger.info("Backup at: '%s'", backup_path)
+ logger.info("New schema version: %s", CURRENT_APP_SCHEMA_VERSION)
+
+
+def _create_new_database(path: Path) -> None:
+ async def connect() -> None:
+ async with Database(_db_path=path, ignore_history=True):
+ pass
+
+ asyncio.run(connect())
+
+
+def _apply_fixes(db_path: Path) -> None:
+
+ async def fix() -> None:
+ conn = await connect(db_path)
+ try:
+ await fix_domains(conn)
+ await fix_referers(conn)
+ finally:
+ await conn.close()
+
+ asyncio.run(fix())
+
+
+def _transfer(new_conn: sqlite3.Connection) -> None:
+ old_tables = _get_table_names(new_conn, schema="old")
+ new_tables = _get_table_names(new_conn, schema="main")
+
+ for table in _DIRECT_TRANSFER_TABLES:
+ if table not in new_tables or table in _SKIP_TABLES:
+ continue
+
+ if table == "files" and "files" not in old_tables:
+ _transfer_media_to_files(new_conn)
+ else:
+ _transfer_table(new_conn, table)
+
+ # Transfer any remaining new tables not listed
+ covered = set(_DIRECT_TRANSFER_TABLES) | _SKIP_TABLES
+ for table in sorted(new_tables - covered):
+ _transfer_table(new_conn, table)
+
+
+if __name__ == "__main__":
+ with setup_console_logging():
+ run(Path(sys.argv[1]))