Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor: drop v7 database compat code (#1961)

NTFSvolumec4318d81113d
diff --git a/cyberdrop_dl/__main__.py b/cyberdrop_dl/__main__.py
index 440a92f51..2fa62339c 100644
--- a/cyberdrop_dl/__main__.py
+++ b/cyberdrop_dl/__main__.py
@@ -5,7 +5,7 @@ from typing import TYPE_CHECKING
from cyberdrop_dl import tracebacks
from cyberdrop_dl.cli import app
-from cyberdrop_dl.exceptions import CDLConfigRuntimeErrorsGroup
+from cyberdrop_dl.exceptions import CDLConfigRuntimeErrorsGroup, DatabaseError
if TYPE_CHECKING:
from collections.abc import Sequence
@@ -32,12 +32,16 @@ def _error_panel(message: RenderableType, title: str = "Error") -> Panel:
def run_cdl(args: Sequence[str] | None = None) -> int:
+ from pydantic import ValidationError
+
from cyberdrop_dl.logs import setup_console_logging
with setup_console_logging():
try:
app(args)
-
+ except (ValidationError, DatabaseError) as exc:
+ tb = tracebacks.from_exception(exc.with_traceback(None), chain_traceback=False)
+ app.console.print(_error_panel(tb))
except CDLConfigRuntimeErrorsGroup as exc_group:
tb = tracebacks.from_exception(exc_group, chain_traceback=False)
app.console.print(_error_panel(tb, title="Invalid Config"))
diff --git a/cyberdrop_dl/database/__init__.py b/cyberdrop_dl/database/__init__.py
index 7edb1e89c..f12651af2 100644
--- a/cyberdrop_dl/database/__init__.py
+++ b/cyberdrop_dl/database/__init__.py
@@ -1,76 +1,121 @@
from __future__ import annotations
+import contextlib
import dataclasses
from typing import TYPE_CHECKING, Any, Self
import aiosqlite
+from cyberdrop_dl import aio
+
from .tables import HashTable, HistoryTable, SchemaVersionTable
if TYPE_CHECKING:
- from collections.abc import Iterable
+ from collections.abc import AsyncGenerator, Iterable
from pathlib import Path
-async def connect(path: Path) -> aiosqlite.Connection:
+async def _connect(path: Path) -> aiosqlite.Connection:
db_conn = await aiosqlite.connect(path, timeout=20)
db_conn.row_factory = aiosqlite.Row
return db_conn
+async def connect(path: Path) -> AsyncGenerator[aiosqlite.Connection]:
+ db_conn = await _connect(path)
+ try:
+ yield db_conn
+ finally:
+ await db_conn.close()
+
+
@dataclasses.dataclass(slots=True)
class Database:
_db_path: Path
- ignore_history: bool
+ ignore_history: bool = False
history: HistoryTable = dataclasses.field(init=False)
hash: HashTable = dataclasses.field(init=False)
schema: SchemaVersionTable = dataclasses.field(init=False)
- _db_conn: aiosqlite.Connection = dataclasses.field(init=False)
+ _conn: aiosqlite.Connection = dataclasses.field(init=False)
+ _is_new: bool = dataclasses.field(init=False)
def __post_init__(self) -> None:
self.history = HistoryTable(self)
self.hash = HashTable(self)
self.schema = SchemaVersionTable(self)
- async def __aenter__(self) -> Self:
- self._db_conn = await connect(self._db_path)
- await self._pre_allocate()
+ @property
+ def conn(self) -> aiosqlite.Connection:
+ return self._conn
+
+ async def _connect(self) -> None:
+ self._is_new = not await aio.get_size(self._db_path)
+ self._conn = await _connect(self._db_path)
+
+ async def exists(self, table: str) -> bool:
+ query = f"SELECT name FROM sqlite_master WHERE type='table' AND name='{table}';" # noqa: S608
+ row = await self.fetchone(query)
+ return row is not None
+
+ async def _create_tables(self) -> None:
await self.schema.create()
+ if not self._is_new:
+ self.schema.check_version()
+ await _pre_allocate(self.conn)
await self.history.create()
await self.hash.create()
- if not self.schema.up_to_date:
- await self.history.apply_updates()
+ if self._is_new:
await self.schema.update()
+ async def __aenter__(self) -> Self:
+ await self._connect()
+ try:
+ await self._create_tables()
+ except Exception:
+ if self._is_new:
+ await self.conn.close()
+ try:
+ await aio.unlink(self._db_path, missing_ok=True)
+ except OSError:
+ pass
+ raise
+ else:
+ if not (self._is_new or self.schema.up_to_date):
+ await self.history.apply_updates()
+ await self.schema.update()
+
return self
async def fetchone(self, query: str, parameters: Iterable[Any] | None = None) -> aiosqlite.Row | None:
- cursor = await self._db_conn.execute(query, parameters)
+ cursor = await self.conn.execute(query, parameters)
return await cursor.fetchone()
async def fetchall(self, query: str, parameters: Iterable[Any] | None = None) -> list[aiosqlite.Row]:
- return await self._db_conn.execute_fetchall(query, parameters) # pyright: ignore[reportReturnType]
+ return await self.conn.execute_fetchall(query, parameters) # pyright: ignore[reportReturnType]
async def __aexit__(self, *_: object) -> None:
- await self._db_conn.close()
+ await self.conn.close()
+
- async def _pre_allocate(self) -> None:
- """We pre-allocate 100MB of space to the SQL file just in case the user runs out of disk space."""
+async def _pre_allocate(db_conn: aiosqlite.Connection) -> None:
+ """Pre-allocate 100MB of space to the SQL file just in case the user runs out of disk space."""
- free_space = await self.fetchone("PRAGMA freelist_count;")
- assert free_space is not None
+ cursor = await db_conn.execute("PRAGMA freelist_count;")
+ free_space = await cursor.fetchone()
+ assert free_space is not None
- if free_space[0] > 1024:
- return
+ if free_space[0] > 1024:
+ return
- pre_allocate_script = (
- "CREATE TABLE IF NOT EXISTS t(x);"
- "INSERT INTO t VALUES(zeroblob(100*1024*1024));" # 100 MB
- "DROP TABLE t;"
- )
- _ = await self._db_conn.executescript(pre_allocate_script)
- await self._db_conn.commit()
+ pre_allocate_script = (
+ "CREATE TABLE IF NOT EXISTS t(x);"
+ "INSERT INTO t VALUES(zeroblob(100*1024*1024));" # 100 MB
+ "DROP TABLE t;"
+ )
+ _ = await db_conn.executescript(pre_allocate_script)
+ await db_conn.commit()
__all__ = ["Database"]
diff --git a/cyberdrop_dl/database/tables/definitions.py b/cyberdrop_dl/database/tables/definitions.py
index 4cf4588ad..bbab09d33 100644
--- a/cyberdrop_dl/database/tables/definitions.py
+++ b/cyberdrop_dl/database/tables/definitions.py
@@ -2,27 +2,15 @@ create_history = """CREATE TABLE IF NOT EXISTS media (
domain TEXT,
url_path TEXT,
referer TEXT,
- album_id TEXT,
- download_path TEXT,
- download_filename TEXT,
- original_filename TEXT,
- completed INTEGER NOT NULL,
- created_at TIMESTAMP,
- completed_at TIMESTAMP,
- PRIMARY KEY (domain, url_path, original_filename)
-);"""
-
-create_fixed_history = """CREATE TABLE IF NOT EXISTS media_copy (
- domain TEXT,
- url_path TEXT,
- referer TEXT,
- album_id TEXT,
download_path TEXT,
download_filename TEXT,
original_filename TEXT,
file_size INT,
duration FLOAT,
+ album_id TEXT,
completed INTEGER NOT NULL,
+ created_at TIMESTAMP,
+ completed_at TIMESTAMP,
PRIMARY KEY (domain, url_path, original_filename)
);"""
@@ -58,16 +46,6 @@ CREATE TABLE IF NOT EXISTS hash (
"""
-create_temp_hash = """
-CREATE TABLE IF NOT EXISTS temp_hash (
- folder TEXT,
- download_filename TEXT,
- hash_type TEXT,
- hash TEXT,
- PRIMARY KEY (folder, download_filename, hash_type),
- FOREIGN KEY (folder, download_filename) REFERENCES files(folder, download_filename)
-);
-"""
create_hash_index = """
CREATE INDEX IF NOT EXISTS idx_hash_type_hash ON hash (hash_type, hash);
diff --git a/cyberdrop_dl/database/tables/hash.py b/cyberdrop_dl/database/tables/hash.py
index 385a2e7df..e6b1a62f3 100644
--- a/cyberdrop_dl/database/tables/hash.py
+++ b/cyberdrop_dl/database/tables/hash.py
@@ -24,7 +24,7 @@ class HashTable:
@property
def db_conn(self) -> aiosqlite.Connection:
- return self._database._db_conn
+ return self._database.conn
async def create(self) -> None:
for query in (
diff --git a/cyberdrop_dl/database/tables/history.py b/cyberdrop_dl/database/tables/history.py
index 677fc73a9..731dcd3e4 100644
--- a/cyberdrop_dl/database/tables/history.py
+++ b/cyberdrop_dl/database/tables/history.py
@@ -7,7 +7,7 @@ import time
from sqlite3 import IntegrityError, Row
from typing import TYPE_CHECKING, Any, cast
-from .definitions import create_fixed_history, create_history, create_media_index
+from .definitions import create_history, create_media_index
if TYPE_CHECKING:
import datetime
@@ -31,16 +31,15 @@ class HistoryTable:
@property
def db_conn(self) -> aiosqlite.Connection:
- return self._database._db_conn
+ return self._database.conn
async def create(self) -> None:
await self.db_conn.execute(create_history)
+ await self.db_conn.executescript(create_media_index)
await self.db_conn.commit()
async def apply_updates(self) -> None:
logger.info("Applying database updates. This could take a while...")
- await self.fix_primary_keys()
- await self.add_columns_media()
await apply_fixes(self.db_conn)
async def delete_invalid_rows(self) -> None:
@@ -250,55 +249,10 @@ class HistoryTable:
except Exception:
logger.exception("Error getting bunkr failed via hash")
- async def fix_primary_keys(self) -> None:
- domain_column, *_ = await self._get_media_table_columns()
- domain_is_primary_key: bool = domain_column["pk"] != 0
- if domain_is_primary_key:
- return
-
- await self.db_conn.execute(create_fixed_history)
- await self.db_conn.commit()
- script = """
- INSERT INTO media_copy (domain, url_path, referer, download_path,
- download_filename, original_filename, completed)
- SELECT * FROM media GROUP BY domain, url_path, original_filename;
- DROP TABLE media;
- ALTER TABLE media_copy RENAME TO media;
- """
- await self.db_conn.executescript(script)
- await self.db_conn.commit()
-
- async def _get_media_table_columns(self) -> list[Row]:
- query = "pragma table_info(media)"
- cursor = await self.db_conn.execute(query)
- return cast("list[Row]", await cursor.fetchall())
-
- async def add_columns_media(self) -> None:
- columns = await self._get_media_table_columns()
- current_column_names: tuple[str, ...] = tuple(col["name"] for col in columns)
- new_columns = (
- ("album_id", "TEXT"),
- ("created_at", "TIMESTAMP"),
- ("completed_at", "TIMESTAMP"),
- ("file_size", "INT"),
- ("duration", "FLOAT"),
- )
-
- script = ""
- for name, type_ in new_columns:
- if name not in current_column_names:
- script += f"ALTER TABLE media ADD COLUMN {name} {type_};"
-
- if script:
- await self.db_conn.executescript(script)
- await self.db_conn.commit()
-
async def apply_fixes(db_conn: aiosqlite.Connection) -> None:
await _fix_domains(db_conn)
await _fix_referers(db_conn)
- await db_conn.executescript(create_media_index)
- await db_conn.commit()
async def _fix_domains(db_conn: aiosqlite.Connection) -> None:
diff --git a/cyberdrop_dl/database/tables/schema.py b/cyberdrop_dl/database/tables/schema.py
index a857ee2c1..56b9055fa 100644
--- a/cyberdrop_dl/database/tables/schema.py
+++ b/cyberdrop_dl/database/tables/schema.py
@@ -6,6 +6,8 @@ from typing import TYPE_CHECKING, NamedTuple
import aiosqlite
+from cyberdrop_dl.exceptions import DatabaseError
+
from .definitions import create_schema_version
if TYPE_CHECKING:
@@ -27,7 +29,8 @@ class Version(NamedTuple):
return ".".join(map(str, self))
-CURRENT_APP_SCHEMA_VERSION = Version(9, 15, 0)
+CURRENT_APP_SCHEMA_VERSION = Version(10, 0, 0)
+REQUIRED_APP_SCHEMA_VERSION = Version(9, 15, 0)
logger = logging.getLogger(__name__)
@@ -36,6 +39,7 @@ logger = logging.getLogger(__name__)
class SchemaVersionTable:
_database: Database
_up_to_date: bool = False
+ _version: Version | None = None
@property
def up_to_date(self) -> bool:
@@ -43,42 +47,102 @@ class SchemaVersionTable:
@property
def db_conn(self) -> aiosqlite.Connection:
- return self._database._db_conn
+ return self._database.conn
- async def get_version(self) -> Version | None:
- if not await self.__exists():
+ async def _get_version(self) -> Version | None:
+ if not await self._database.exists("schema_version"):
return None
query = "SELECT version FROM schema_version ORDER BY ROWID DESC LIMIT 1;"
cursor = await self.db_conn.execute(query)
- result = await cursor.fetchone()
- if result:
- return Version.parse(result["version"])
-
- async def __exists(self) -> bool:
- query = "SELECT name FROM sqlite_master WHERE type='table' AND name='schema_version';"
- cursor = await self.db_conn.execute(query)
- result = await cursor.fetchone()
- return result is not None
+ if row := await cursor.fetchone():
+ return Version.parse(row["version"])
- async def __create_if_not_exists(self) -> None:
+ async def create(self) -> None:
+ logger.info(f"Expected database schema: {CURRENT_APP_SCHEMA_VERSION!s}")
+ self._version = await self._get_version()
+ logger.info(f"Current database schema: {self._version!s}")
await self.db_conn.execute(create_schema_version)
await self.db_conn.commit()
- async def __update_schema_version(self) -> None:
- await self.__create_if_not_exists()
- query = "INSERT INTO schema_version (version) VALUES (?)"
- _ = await self.db_conn.execute(query, (str(CURRENT_APP_SCHEMA_VERSION),))
- await self.db_conn.commit()
-
- async def create(self) -> None:
- logger.info(f"Expected database schema: {CURRENT_APP_SCHEMA_VERSION!s}")
- version = await self.get_version()
- logger.info(f"Current database schema: {version!s}")
- # TODO: on v10, raise SystemExit if db version is None or older than 8.0.0
- if version is not None and version >= CURRENT_APP_SCHEMA_VERSION:
+ def check_version(self) -> None:
+ if self._version is None:
+ raise DatabaseError(
+ f"Database has no schema information. Minimum required version: {REQUIRED_APP_SCHEMA_VERSION}"
+ )
+ if self._version < REQUIRED_APP_SCHEMA_VERSION:
+ raise DatabaseError(
+ f"Incompatible database version detected. Current: {self._version!s} , Minimum required: {REQUIRED_APP_SCHEMA_VERSION!s}"
+ )
+ if self._version >= CURRENT_APP_SCHEMA_VERSION:
self._up_to_date = True
- async def update(self) -> None:
- await self.__update_schema_version()
- logger.info(f"Updated database schema to {CURRENT_APP_SCHEMA_VERSION!s}")
- self._up_to_date = True
+ async def update(self, version: Version = CURRENT_APP_SCHEMA_VERSION) -> None:
+ query = "INSERT INTO schema_version (version) VALUES (?)"
+ _ = await self.db_conn.execute(query, (str(version),))
+ await self.db_conn.commit()
+ self._version = version
+ self._up_to_date = version >= CURRENT_APP_SCHEMA_VERSION
+ logger.info(f"Updated database schema to {version!s}")
+
+
+async def dump(db_conn: aiosqlite.Connection) -> str:
+ query = "SELECT sql FROM sqlite_master WHERE sql IS NOT NULL ORDER BY name"
+ cursor = await db_conn.execute(query)
+ rows = await cursor.fetchall()
+ index_queries: list[str] = []
+ table_queries: list[str] = []
+
+ for query in (row["sql"] for row in rows):
+ group = table_queries if "CREATE TABLE" in query else index_queries
+ group.append(query)
+
+ return ";\n".join([*sorted(table_queries), *sorted(index_queries)]) + ";"
+
+
+V9_15_0 = """
+CREATE TABLE files (
+ folder TEXT,
+ download_filename TEXT,
+ original_filename TEXT,
+ file_size INT,
+ referer TEXT,
+ date INT,
+ PRIMARY KEY (folder, download_filename)
+);
+CREATE TABLE hash (
+ folder TEXT,
+ download_filename TEXT,
+ hash_type TEXT,
+ hash TEXT,
+ PRIMARY KEY (folder, download_filename, hash_type),
+ FOREIGN KEY (folder, download_filename) REFERENCES files(folder, download_filename)
+);
+CREATE TABLE media (
+ domain TEXT,
+ url_path TEXT,
+ referer TEXT,
+ download_path TEXT,
+ download_filename TEXT,
+ original_filename TEXT,
+ file_size INT,
+ duration FLOAT,
+ album_id TEXT,
+ completed INTEGER NOT NULL,
+ created_at TIMESTAMP,
+ completed_at TIMESTAMP,
+ PRIMARY KEY (domain, url_path, original_filename)
+);
+CREATE TABLE schema_version (
+ version VARCHAR(50) NOT NULL PRIMARY KEY,
+ applied_on TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
+);
+CREATE INDEX idx_hash_type_hash ON hash (hash_type, hash);
+CREATE INDEX idx_media_domain_album
+ ON media (domain, album_id);
+CREATE INDEX idx_media_domain_referer_completed
+ ON media (domain, referer, completed);
+CREATE INDEX idx_media_domain_url_path_referer
+ ON media (domain, url_path, referer);
+CREATE INDEX idx_media_referer_completed
+ ON media (referer, completed);
+""".strip()
diff --git a/cyberdrop_dl/database/transfer.py b/cyberdrop_dl/database/transfer.py
index 51b4e25b2..461b5f7e7 100644
--- a/cyberdrop_dl/database/transfer.py
+++ b/cyberdrop_dl/database/transfer.py
@@ -7,7 +7,7 @@ import sys
from pathlib import Path
from typing import LiteralString
-from cyberdrop_dl.database import Database, connect
+from cyberdrop_dl import database
from cyberdrop_dl.database.tables.history import apply_fixes
from cyberdrop_dl.database.tables.schema import CURRENT_APP_SCHEMA_VERSION, Version
from cyberdrop_dl.logs import setup_console_logging
@@ -186,7 +186,7 @@ def run(db_path: Path, *, force: bool = False) -> None:
def _create_new_database(path: Path) -> None:
async def connect() -> None:
- async with Database(_db_path=path, ignore_history=True):
+ async with database.Database(_db_path=path, ignore_history=True):
pass
asyncio.run(connect())
@@ -195,11 +195,8 @@ def _create_new_database(path: Path) -> None:
def _apply_fixes(db_path: Path) -> None:
async def fix() -> None:
- conn = await connect(db_path)
- try:
+ async with database.connect(db_path) as conn:
await apply_fixes(conn)
- finally:
- await conn.close()
asyncio.run(fix())
diff --git a/cyberdrop_dl/exceptions.py b/cyberdrop_dl/exceptions.py
index 2fd464425..8a126116d 100644
--- a/cyberdrop_dl/exceptions.py
+++ b/cyberdrop_dl/exceptions.py
@@ -53,6 +53,9 @@ def _notes(e: BaseException) -> list[str] | tuple[()]:
return getattr(e, "__notes__", ())
+class DatabaseError(RuntimeError): ...
+
+
class CDLBaseError(Exception):
"""Base exception for cyberdrop-dl errors."""
diff --git a/docs/SUMMARY.md b/docs/SUMMARY.md
index 443f21169..a62b3f131 100644
--- a/docs/SUMMARY.md
+++ b/docs/SUMMARY.md
@@ -4,9 +4,7 @@
- [Getting Started](getting-started/README.md)
- [Cyberdrop-DL Install](getting-started/cyberdrop-dl-install.md)
- [Running CDL on Android](getting-started/cyberdrop-dl-on-android.md)
-- [Transition to V8](upgrade.md)
- [Frequently Asked Questions](frequently-asked-questions.md)
-- [Migration to Cyberdrop-DL-Patched](migration-to-cyberdrop-dl-patched.md)
- [SimpCity Support Dropped](simpcity-support-dropped.md)
## Reference
diff --git a/docs/migration-to-cyberdrop-dl-patched.md b/docs/migration-to-cyberdrop-dl-patched.md
deleted file mode 100644
index ac81a30d7..000000000
--- a/docs/migration-to-cyberdrop-dl-patched.md
+++ /dev/null
@@ -1,44 +0,0 @@
----
-description: How to migrate to the patched version of Cyberdrop-DL.
-icon: arrow-trend-up
-layout:
- title:
- visible: true
- description:
- visible: true
- tableOfContents:
- visible: true
- outline:
- visible: false
- pagination:
- visible: true
----
-
-# Move to Cyberdrop-DL-Patched
-
-If you used the original version of the package (`cyberdrop-dl` instead of `cyberdrop-dl-patched`), you can follow the steps below to migrate.
-
-{% hint style="warning" %}
-You may need to adjust your config to make sure it's compatible with the newer versions.
-
-See: [Transition to V8](https://script-ware.gitbook.io/cyberdrop-dl/upgrade)
-{% endhint %}
-
-## If you installed on your own using pip
-
-You can simply uninstall the old version and install the new one using the following commands:
-
-```shell
-pip uninstall -y cyberdrop-dl
-pip install cyberdrop-dl-patched
-```
-
-The command to use the new version will be `cyberdrop-dl-patched`.
-
-## If you installed using the start files
-
-You can find the new ones here: [new start scripts](https://github.com/Cyberdrop-DL/cyberdrop-dl/releases/latest)
-
-Put the new start scripts on the same folder as the old ones, them delete the old ones.
-
-You also have to delete any `venv` or `.venv` folder (if you have any)
diff --git a/docs/upgrade.md b/docs/upgrade.md
deleted file mode 100644
index 18359566e..000000000
--- a/docs/upgrade.md
+++ /dev/null
@@ -1,104 +0,0 @@
----
-description: This is the walk through for transitioning from V4-V7 to v8
-icon: arrow-up-to-bracket
-layout:
- title:
- visible: true
- description:
- visible: true
- tableOfContents:
- visible: true
- outline:
- visible: false
- pagination:
- visible: true
----
-
-# Transition to v8
-
-{% hint style="danger" %}
-V6 introduced some breaking changes: Using a more strict config validation logic, replacing `md5` with `xxh128` as the default hashing algorithm, using a new database schema, among others.
-
-It's recommended to do a manual backup of your current `AppData` folder. You won't be able to rollback to a previous version after the transfer is completed.
-
-You can learn more about these changes on the [release announcement](https://github.com/Cyberdrop-DL/cyberdrop-dl/blob/main/CHANGELOG.md#600---2024-12-23)
-{% endhint %}
-
-{% hint style="warning" %}
-Even after a successful configuration migration, the program may not start if some values from the previous version’s config are no longer valid. Please follow the on-screen instructions to resolve the issue.
-
-You can use the [Config Options page](reference/configuration-options/README.md) as reference for valid config values
-{% endhint %}
-
-## Import V5, V6 or v7 config into v8
-
-Good news! If you have a v5-v7 config, CDL can import it. The program will automatically detect the config in the current folder and handle the migration process for you.
-
-All you have to do is replace your old start script (for Windows, that's the `.bat` file) with the v8 start script.
-
-Please note that after the migration is complete, you may still need to manually adjust some values in the config.
-
-If you are migrating from v5 and the migration fails, the database will be rolled back to its previous state. An automatic backup is also made before the migration begins. However, keep in mind that the backup only includes the database, not the config files.
-
-{% hint style="info" %}
-Support for v5 and v6 (config, database and auto-migration) is deprecated and will be removed in v9
-{% endhint %}
-
-## Import V4 config
-
-{% hint style="warning" %}
-V4 import is no longer supported. Last version with v4 support was `6.5.0`. To upgrade to the latest version, you need to perform a sequential upgrade. First, update CDL to `6.5.0`, import your v4 files, and then update to the latest version.
-
-You can install `6.5.0` with pip by running:
-
-```shell
-pip install cyberdrop-dl-patched==6.5.0
-```
-
-{% endhint %}
-
-Built into Cyberdrop-DL is a tool that allows you to import both your configs and your history DB from a v4 version of Cyberdrop-DL. You can use it by selecting "Import V4 Items".
-
-### Import Your V4 Configs</a>
-
-The config files will be located in the folder that you were previously running Cyberdrop-DL in. Start CDL, choose the option `Import v4 config` and follow the on screen instructions
-
-{% hint style="info" %}
-If you weren't using the config previously, you don't need to import it.
-
-However, if you were primarily using CLI Arguments with V4, some of the arguments has been replaced.
-{% endhint %}
-
-If you don't end up using the import feature, make sure you also change the default config in the program if that's something you want to do.
-
-### Import Your V4 Database</a>
-
-For a lot of people, the `download_history.sqlite` file will be in the same folder as your start file (or wherever you are running Cyberdrop-DL).
-
-If it's not there, you can find it here:
-
-Windows:
-
-```shell
-C:\Users\<USER>\AppData\Local\Cyberdrop-DL\Cyberdrop-DL\download_history.sqlite
-```
-
-macOS:
-
-```shell
-/Library/Application Support/Cyberdrop-DL/Cyberdrop-DL/download_history.sqlite
-```
-
-Linux:
-
-```shell
-/home/<USER>/.local/share/Cyberdrop-DL/Cyberdrop-DL/download_history.sqlite
-```
-
-To import it, start CDL, choose the option `Import v4 database` and follow the on screen instructions
-
-{% hint style="info" %}
-The old `download_history.sqlite` file is no longer used by Cyberdrop-DL. After you import it, you can delete the old one.
-
-If you don't want to import previous download history, you can just delete it.
-{% endhint %}
diff --git a/tests/test_database.py b/tests/test_database.py
index 732d06a0e..d3e1564ae 100644
--- a/tests/test_database.py
+++ b/tests/test_database.py
@@ -6,7 +6,10 @@ from typing import TYPE_CHECKING, cast
import pytest
-from cyberdrop_dl import scrape_mapper
+from cyberdrop_dl import aio, database, scrape_mapper
+from cyberdrop_dl.database import Database
+from cyberdrop_dl.database.tables import schema
+from cyberdrop_dl.exceptions import DatabaseError
from cyberdrop_dl.scrape_mapper import _create_item_from_row
from cyberdrop_dl.url_objects import AbsoluteHttpURL, ScrapeItem
from cyberdrop_dl.utils import dates, parse_url
@@ -166,3 +169,70 @@ class TestGetDownloadPath:
item.retry_path = retry_path = Path("a/retry/path")
download_path = item.compose_download_path("cyberdrop")
assert download_path == retry_path
+
+
+async def test_database_creation(tmp_cwd: Path) -> None:
+ db_file = tmp_cwd / "test_db.db"
+ db = Database(db_file)
+ async with db:
+ pass
+
+ assert db._is_new
+ size = await aio.get_size(db_file)
+ assert size
+ assert db.schema.up_to_date
+
+
+async def test_pre_allocation(tmp_cwd: Path) -> None:
+ db_file = tmp_cwd / "test_db.db"
+ async with database.connect(db_file) as db:
+ size = await aio.get_size(db_file)
+ assert size == 0
+
+ async with database.connect(db_file) as db:
+ await database._pre_allocate(db)
+
+ size = await aio.get_size(db_file)
+ assert size
+ assert size >= 100e6
+
+
+async def test_database_version_check(tmp_cwd: Path) -> None:
+ db_file = tmp_cwd / "test_db.db"
+ db = Database(db_file)
+ db_file.touch()
+ await db._connect()
+ try:
+ await db._create_tables()
+ assert db._is_new
+ await db.conn.execute("DROP TABLE 'schema_version'")
+ await db.conn.commit()
+ finally:
+ await db.conn.close()
+
+ db = Database(db_file)
+ await db._connect()
+ try:
+ assert not db._is_new
+ assert not db.schema.up_to_date
+ await db.schema.create()
+ assert db.schema._version is None
+ assert await db.schema._get_version() is None
+ version = schema.Version(8, 8, 8)
+ await db.schema.update(version)
+ assert not db.schema.up_to_date
+ assert await db.schema._get_version() == version
+ assert db.schema._version == version
+ with pytest.raises(DatabaseError):
+ db.schema.check_version()
+ finally:
+ await db.conn.close()
+
+
+async def test_db_schema_dump(tmp_cwd: Path) -> None:
+ db_file = tmp_cwd / "test_db.db"
+
+ async with Database(db_file) as db:
+ current_schema = await schema.dump(db.conn)
+
+ assert current_schema == schema.V9_15_0