Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor: add common db table class (#1965)

NTFSvolumeaaa1d0988b99
diff --git a/.zed/settings.json b/.zed/settings.json
index 429575c86..74244e551 100644
--- a/.zed/settings.json
+++ b/.zed/settings.json
@@ -1,39 +1,39 @@
{
- "disable_ai": true,
- "format_on_save": "on",
- "project_name": "cyberdrop-dl",
- "languages": {
- "Python": {
- "show_whitespaces": "all",
- "show_edit_predictions": true,
- "hard_tabs": false,
- "format_on_save": "on",
- "formatter": {
- "language_server": {
- "name": "ruff"
- }
- },
- "language_servers": ["ruff", "basedpyright"]
- }
+ "disable_ai": true,
+ "format_on_save": "on",
+ "languages": {
+ "Python": {
+ "show_whitespaces": "all",
+ "show_edit_predictions": true,
+ "hard_tabs": false,
+ "format_on_save": "on",
+ "formatter": {
+ "language_server": {
+ "name": "ruff",
+ },
+ },
+ "language_servers": ["ruff", "basedpyright"],
},
- "lsp": {
- "basedpyright": {
- "settings": {
- "python": {
- "pythonPath": ".venv/bin/python"
- },
- "basedpyright.analysis": {
- "diagnosticMode": "openFilesOnly"
- }
- }
- }
+ },
+ "lsp": {
+ "basedpyright": {
+ "settings": {
+ "python": {
+ "pythonPath": ".venv/bin/python",
+ },
+ "basedpyright.analysis": {
+ "diagnosticMode": "openFilesOnly",
+ },
+ },
},
- "file_scan_exclusions": [
- "**/.git",
- "**/.vscode",
- "**/.venv",
- "**/.ruff_cache",
- "**/.pytest_cache",
- "**/.tox"
- ]
+ },
+ "file_scan_exclusions": [
+ "**/.git",
+ "**/.vscode",
+ "**/__pycache__",
+ "**/.venv",
+ "**/.ruff_cache",
+ "**/.pytest_cache",
+ "**/.tox",
+ ],
}
diff --git a/cyberdrop_dl/database/__init__.py b/cyberdrop_dl/database/__init__.py
index f12651af2..351913096 100644
--- a/cyberdrop_dl/database/__init__.py
+++ b/cyberdrop_dl/database/__init__.py
@@ -1,121 +1,3 @@
-from __future__ import annotations
+from ._db import Database, connect, pre_allocate_100mb
-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 AsyncGenerator, Iterable
- 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
-
-
-async def connect(path: Path) -> AsyncGenerator[aiosqlite.Connection]:
- db_conn = await _connect(path)
- try:
- yield db_conn
- finally:
- await db_conn.close()
-
-
[email protected](slots=True)
-class Database:
- _db_path: Path
- ignore_history: bool = False
-
- history: HistoryTable = dataclasses.field(init=False)
- hash: HashTable = dataclasses.field(init=False)
- schema: SchemaVersionTable = 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)
-
- @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 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.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.conn.execute_fetchall(query, parameters) # pyright: ignore[reportReturnType]
-
- async def __aexit__(self, *_: object) -> None:
- await self.conn.close()
-
-
-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."""
-
- 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
-
- 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"]
+__all__ = ["Database", "connect", "pre_allocate_100mb"]
diff --git a/cyberdrop_dl/database/_db.py b/cyberdrop_dl/database/_db.py
new file mode 100644
index 000000000..1d5fc883d
--- /dev/null
+++ b/cyberdrop_dl/database/_db.py
@@ -0,0 +1,118 @@
+from __future__ import annotations
+
+import contextlib
+import dataclasses
+from typing import TYPE_CHECKING, Self
+
+import aiosqlite
+
+from cyberdrop_dl import aio
+from cyberdrop_dl.database.hash import HashTable
+from cyberdrop_dl.database.history import HistoryTable
+from cyberdrop_dl.database.schema import SchemaTable
+
+if TYPE_CHECKING:
+ from collections.abc import AsyncGenerator
+ 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
+
+
+async def connect(path: Path) -> AsyncGenerator[aiosqlite.Connection]:
+ db_conn = await _connect(path)
+ try:
+ yield db_conn
+ finally:
+ await db_conn.close()
+
+
[email protected](slots=True)
+class Database:
+ path: Path
+ ignore_history: bool = False
+
+ history: HistoryTable = dataclasses.field(init=False)
+ hash: HashTable = dataclasses.field(init=False)
+ schema: SchemaTable = 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 = SchemaTable(self)
+
+ @property
+ def conn(self) -> aiosqlite.Connection:
+ return self._conn
+
+ async def _connect(self) -> None:
+ self._is_new = not await aio.get_size(self.path)
+ self._conn = await _connect(self.path)
+
+ @contextlib.asynccontextmanager
+ async def connect(self) -> AsyncGenerator[Self]:
+ await self._connect()
+ try:
+ yield self
+ finally:
+ await self.conn.close()
+
+ async def _create_tables(self) -> None:
+ await self.schema.create()
+ if not self._is_new:
+ self.schema.check_version()
+ await pre_allocate_100mb(self.conn)
+ await self.history.create()
+ await self.hash.create()
+ if self._is_new:
+ await self.schema.update()
+
+ async def create_tables(self) -> None:
+ try:
+ await self._create_tables()
+ except Exception:
+ if self._is_new:
+ await self.conn.close()
+ try:
+ await aio.unlink(self.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()
+
+ async def __aenter__(self) -> Self:
+ await self._connect()
+ await self.create_tables()
+ return self
+
+ async def __aexit__(self, *_: object) -> None:
+ await self.conn.close()
+
+
+async def pre_allocate_100mb(db_conn: aiosqlite.Connection) -> None:
+ """Pre-allocate 100MB of space to the SQL file just in case the user runs out of disk space."""
+
+ 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
+
+ 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()
diff --git a/cyberdrop_dl/database/tables/definitions.py b/cyberdrop_dl/database/definitions.py
similarity index 89%
rename from cyberdrop_dl/database/tables/definitions.py
rename to cyberdrop_dl/database/definitions.py
index bbab09d33..5dc3526e4 100644
--- a/cyberdrop_dl/database/tables/definitions.py
+++ b/cyberdrop_dl/database/definitions.py
@@ -1,4 +1,4 @@
-create_history = """CREATE TABLE IF NOT EXISTS media (
+CREATE_HISTORY = """CREATE TABLE IF NOT EXISTS media (
domain TEXT,
url_path TEXT,
referer TEXT,
@@ -14,14 +14,14 @@ create_history = """CREATE TABLE IF NOT EXISTS media (
PRIMARY KEY (domain, url_path, original_filename)
);"""
-create_schema_version = """
+CREATE_SCHEMA = """
CREATE TABLE IF NOT EXISTS schema_version (
version VARCHAR(50) NOT NULL PRIMARY KEY,
applied_on TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
"""
-create_files = """
+CREATE_FILES = """
CREATE TABLE IF NOT EXISTS files (
folder TEXT,
download_filename TEXT,
@@ -34,7 +34,7 @@ CREATE TABLE IF NOT EXISTS files (
"""
-create_hash = """
+CREATE_HASH = """
CREATE TABLE IF NOT EXISTS hash (
folder TEXT,
download_filename TEXT,
@@ -43,15 +43,14 @@ CREATE TABLE IF NOT EXISTS hash (
PRIMARY KEY (folder, download_filename, hash_type),
FOREIGN KEY (folder, download_filename) REFERENCES files(folder, download_filename)
);
-
"""
-create_hash_index = """
+CREATE_HASH_INDEX = """
CREATE INDEX IF NOT EXISTS idx_hash_type_hash ON hash (hash_type, hash);
"""
-create_media_index = """
+CREATE_MEDIA_INDEX = """
CREATE INDEX IF NOT EXISTS idx_media_referer_completed
ON media (referer, completed);
diff --git a/cyberdrop_dl/database/tables/hash.py b/cyberdrop_dl/database/hash.py
similarity index 92%
rename from cyberdrop_dl/database/tables/hash.py
rename to cyberdrop_dl/database/hash.py
index e6b1a62f3..a00e9eef4 100644
--- a/cyberdrop_dl/database/tables/hash.py
+++ b/cyberdrop_dl/database/hash.py
@@ -5,46 +5,32 @@ import logging
from pathlib import Path
from typing import TYPE_CHECKING, cast
-from .definitions import create_files, create_hash, create_hash_index
+from cyberdrop_dl.database import table
+from cyberdrop_dl.database.definitions import CREATE_FILES, CREATE_HASH, CREATE_HASH_INDEX
if TYPE_CHECKING:
import aiosqlite
from yarl import URL
- from cyberdrop_dl.database import Database
-
logger = logging.getLogger(__name__)
[email protected](slots=True, frozen=True)
-class HashTable:
- _database: Database
[email protected](slots=True)
+class HashTable(table.Table):
cwd: Path = dataclasses.field(init=False, default_factory=lambda: Path.cwd().expanduser().resolve())
- @property
- def db_conn(self) -> aiosqlite.Connection:
- return self._database.conn
-
async def create(self) -> None:
for query in (
- create_files,
- create_hash,
- create_hash_index,
+ CREATE_FILES,
+ CREATE_HASH,
+ CREATE_HASH_INDEX,
):
_ = await self.db_conn.execute(query)
await self.db_conn.commit()
async def get_file_hash_exists(self, path: Path | str, hash_type: str) -> str | None:
- """gets the hash from a complete file path
-
- Args:
- full_path: Full path to the file to check.
-
- Returns:
- hash if exists
- """
query = "SELECT hash FROM hash WHERE folder=? AND download_filename=? AND hash_type=? AND hash IS NOT NULL"
try:
path = self.cwd / path
diff --git a/cyberdrop_dl/database/tables/history.py b/cyberdrop_dl/database/history.py
similarity index 94%
rename from cyberdrop_dl/database/tables/history.py
rename to cyberdrop_dl/database/history.py
index 731dcd3e4..ecd35c519 100644
--- a/cyberdrop_dl/database/tables/history.py
+++ b/cyberdrop_dl/database/history.py
@@ -1,13 +1,13 @@
from __future__ import annotations
import contextlib
-import dataclasses
import logging
import time
from sqlite3 import IntegrityError, Row
from typing import TYPE_CHECKING, Any, cast
-from .definitions import create_history, create_media_index
+from cyberdrop_dl.database import table
+from cyberdrop_dl.database.definitions import CREATE_HISTORY, CREATE_MEDIA_INDEX
if TYPE_CHECKING:
import datetime
@@ -17,7 +17,6 @@ if TYPE_CHECKING:
from yarl import URL
from cyberdrop_dl.crawlers.crawler import Crawler
- from cyberdrop_dl.database import Database
from cyberdrop_dl.url_objects import MediaItem
@@ -25,28 +24,16 @@ _FETCH_MANY_SIZE: int = 1000
logger = logging.getLogger(__name__)
[email protected](slots=True, frozen=True)
-class HistoryTable:
- _database: Database
-
- @property
- def db_conn(self) -> aiosqlite.Connection:
- return self._database.conn
-
+class HistoryTable(table.Table):
async def create(self) -> None:
- await self.db_conn.execute(create_history)
- await self.db_conn.executescript(create_media_index)
+ 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 apply_fixes(self.db_conn)
- async def delete_invalid_rows(self) -> None:
- query = "DELETE FROM media WHERE download_filename = '' "
- await self.db_conn.execute(query)
- await self.db_conn.commit()
-
async def check_complete(self, domain: str, db_path: str) -> tuple[str, bool]:
"""Checks whether an individual file has completed given its domain and url path."""
if self._database.ignore_history:
@@ -69,8 +56,7 @@ class HistoryTable:
return {}
query = "SELECT url_path, completed FROM media WHERE domain = ? and album_id = ?"
- cursor = await self.db_conn.execute(query, (domain, album_id))
- rows = await cursor.fetchall()
+ rows = await self.db_conn.execute_fetchall(query, (domain, album_id))
return {row[0]: bool(row[1]) for row in rows}
async def set_album_id(self, domain: str, media_item: MediaItem) -> None:
diff --git a/cyberdrop_dl/database/tables/schema.py b/cyberdrop_dl/database/schema.py
similarity index 65%
rename from cyberdrop_dl/database/tables/schema.py
rename to cyberdrop_dl/database/schema.py
index 56b9055fa..18c13d151 100644
--- a/cyberdrop_dl/database/tables/schema.py
+++ b/cyberdrop_dl/database/schema.py
@@ -2,55 +2,48 @@ from __future__ import annotations
import dataclasses
import logging
-from typing import TYPE_CHECKING, NamedTuple
+from typing import TYPE_CHECKING, NamedTuple, final
import aiosqlite
+from cyberdrop_dl.database import table
+from cyberdrop_dl.database.definitions import CREATE_SCHEMA
from cyberdrop_dl.exceptions import DatabaseError
-from .definitions import create_schema_version
-
if TYPE_CHECKING:
import aiosqlite
- from cyberdrop_dl.database import Database
-
+@final
class Version(NamedTuple):
major: int
- minor: int
- patch: int
+ minor: int = 0
+ patch: int = 0
@staticmethod
def parse(string: str) -> Version:
- return Version(*map(int, string.split(".")[:3]))
+ parts = string.split(".")
+ if not parts or len(parts) > 3:
+ raise ValueError(f"Invalid version string {string}")
+ return Version(*map(int, parts))
def __str__(self) -> str:
return ".".join(map(str, self))
-CURRENT_APP_SCHEMA_VERSION = Version(10, 0, 0)
-REQUIRED_APP_SCHEMA_VERSION = Version(9, 15, 0)
+CURRENT_VERSION = Version(10, 0, 0)
+REQUIRED_VERSION = Version(9, 15, 0)
logger = logging.getLogger(__name__)
@dataclasses.dataclass(slots=True)
-class SchemaVersionTable:
- _database: Database
- _up_to_date: bool = False
- _version: Version | None = None
-
- @property
- def up_to_date(self) -> bool:
- return self._up_to_date
+class SchemaTable(table.Table):
+ up_to_date: bool = False
+ version: Version | None = None
- @property
- def db_conn(self) -> aiosqlite.Connection:
- return self._database.conn
-
- async def _get_version(self) -> Version | None:
- if not await self._database.exists("schema_version"):
+ async def get_version(self) -> Version | None:
+ if not await table.exists(self.db_conn, "schema_version"):
return None
query = "SELECT version FROM schema_version ORDER BY ROWID DESC LIMIT 1;"
cursor = await self.db_conn.execute(query)
@@ -58,30 +51,28 @@ class SchemaVersionTable:
return Version.parse(row["version"])
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)
+ logger.info(f"Expected database schema: {CURRENT_VERSION!s}")
+ self.version = await self.get_version()
+ logger.info(f"Current database schema: {self.version!s}")
+ await self.db_conn.execute(CREATE_SCHEMA)
await self.db_conn.commit()
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:
+ if self.version is None:
+ raise DatabaseError(f"Database has no schema information. Minimum required version: {REQUIRED_VERSION}")
+ if self.version < REQUIRED_VERSION:
raise DatabaseError(
- f"Incompatible database version detected. Current: {self._version!s} , Minimum required: {REQUIRED_APP_SCHEMA_VERSION!s}"
+ f"Incompatible database version detected. Current: {self.version!s} , Minimum required: {REQUIRED_VERSION!s}"
)
- if self._version >= CURRENT_APP_SCHEMA_VERSION:
- self._up_to_date = True
+ if self.version >= CURRENT_VERSION:
+ self.up_to_date = True
- async def update(self, version: Version = CURRENT_APP_SCHEMA_VERSION) -> None:
+ async def update(self, version: Version = CURRENT_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
+ self.version = version
+ self.up_to_date = version >= CURRENT_VERSION
logger.info(f"Updated database schema to {version!s}")
diff --git a/cyberdrop_dl/database/table.py b/cyberdrop_dl/database/table.py
new file mode 100644
index 000000000..028c4582f
--- /dev/null
+++ b/cyberdrop_dl/database/table.py
@@ -0,0 +1,28 @@
+from __future__ import annotations
+
+import dataclasses
+from abc import ABC, abstractmethod
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ import aiosqlite
+
+ from cyberdrop_dl.database import Database
+
+
[email protected](slots=True)
+class Table(ABC):
+ _database: Database = dataclasses.field(repr=False)
+
+ @property
+ def db_conn(self) -> aiosqlite.Connection:
+ return self._database.conn
+
+ @abstractmethod
+ async def create(self) -> None: ...
+
+
+async def exists(db_conn: aiosqlite.Connection, table: str) -> bool:
+ query = "SELECT 1 FROM sqlite_master WHERE type='table' AND name= ? ;"
+ cursor = await db_conn.execute(query, (table,))
+ return await cursor.fetchone() is not None
diff --git a/cyberdrop_dl/database/tables/__init__.py b/cyberdrop_dl/database/tables/__init__.py
deleted file mode 100644
index 54a6663e3..000000000
--- a/cyberdrop_dl/database/tables/__init__.py
+++ /dev/null
@@ -1,5 +0,0 @@
-from .hash import HashTable
-from .history import HistoryTable
-from .schema import SchemaVersionTable
-
-__all__ = ["HashTable", "HistoryTable", "SchemaVersionTable"]
diff --git a/cyberdrop_dl/database/transfer.py b/cyberdrop_dl/database/transfer.py
index 461b5f7e7..55809d83f 100644
--- a/cyberdrop_dl/database/transfer.py
+++ b/cyberdrop_dl/database/transfer.py
@@ -8,8 +8,8 @@ from pathlib import Path
from typing import LiteralString
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.database.history import apply_fixes
+from cyberdrop_dl.database.schema import CURRENT_VERSION, Version
from cyberdrop_dl.logs import setup_console_logging
from cyberdrop_dl.utils import dates
from cyberdrop_dl.utils.filepath import sanitize_filename
@@ -149,15 +149,15 @@ def run(db_path: Path, *, force: bool = False) -> None:
logger.info("Detected schema version: %s", old_version)
- if not force and old_version == CURRENT_APP_SCHEMA_VERSION:
+ if not force and old_version == CURRENT_VERSION:
logger.info(
"Database is already at the latest schema (%s). Use --force to re-run.",
- CURRENT_APP_SCHEMA_VERSION,
+ CURRENT_VERSION,
)
return
now = sanitize_filename(str(dates.now()))
- new_path = db_path.with_name(f"{db_path.stem}_{CURRENT_APP_SCHEMA_VERSION}_{now}{db_path.suffix}")
+ new_path = db_path.with_name(f"{db_path.stem}_{CURRENT_VERSION}_{now}{db_path.suffix}")
logger.debug("Creating new database at: %s", new_path)
_create_new_database(new_path)
@@ -181,12 +181,12 @@ def run(db_path: Path, *, force: bool = False) -> None:
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)
+ logger.info("New schema version: %s", CURRENT_VERSION)
def _create_new_database(path: Path) -> None:
async def connect() -> None:
- async with database.Database(_db_path=path, ignore_history=True):
+ async with database.Database(path, ignore_history=True):
pass
asyncio.run(connect())
diff --git a/tests/test_database.py b/tests/test_database.py
index d3e1564ae..0047c0913 100644
--- a/tests/test_database.py
+++ b/tests/test_database.py
@@ -7,8 +7,7 @@ from typing import TYPE_CHECKING, cast
import pytest
from cyberdrop_dl import aio, database, scrape_mapper
-from cyberdrop_dl.database import Database
-from cyberdrop_dl.database.tables import schema
+from cyberdrop_dl.database import Database, 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
@@ -190,7 +189,7 @@ async def test_pre_allocation(tmp_cwd: Path) -> None:
assert size == 0
async with database.connect(db_file) as db:
- await database._pre_allocate(db)
+ await database.pre_allocate_100mb(db)
size = await aio.get_size(db_file)
assert size
@@ -199,34 +198,26 @@ async def test_pre_allocation(tmp_cwd: Path) -> None:
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:
+ async with Database(db_file).connect() as db:
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:
+ async with Database(db_file).connect() as db:
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
+ 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
+ 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: