mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-28 19:06:19 -05:00
* A malformed config entry is skipped and counted instead of failing the import An entry that is not a mapping (or whose key is not text, or a list that is not a list) made the whole file fail to import in playlists.yaml, repos.yaml, download_manager.yaml and tags.yaml (tag_files/tag_zims), and a non-text name did in domains.yaml. Each is now skipped and counted in import_skipped, so the config is not saved over it, and the rest of the file imports. A Channel whose `downloads` is not a list keeps its Downloads. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * An unreadable entry keeps no row and does not make a section present The key of an entry too malformed to name a row is now `Unreadable(position)`. It is still counted in import_skipped, but `present` ignores it, so a section whose entries are all unreadable removes nothing (as an empty section), instead of deleting every row. A playlist whose `items` is not a list keeps its items, and a Channel Download whose url is not text is counted (its Channel keeps its Downloads) instead of failing the import. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
108 lines
4.7 KiB
Python
108 lines
4.7 KiB
Python
"""Importing a database config: read its file, diff it against a snapshot of the database, then write only the
|
|
differences in one short write (see `ConfigFile.import_config`).
|
|
|
|
A config declares a `ConfigSection` for each kind of row it saves (tags.yaml has Tags and the files they tag).
|
|
Rows are compared as plain data keyed the way the file names them (a URL, a name, a path), so the snapshot needs no
|
|
ORM objects and the read can finish before any slow preparation starts.
|
|
"""
|
|
import operator
|
|
import pathlib
|
|
from dataclasses import dataclass, field
|
|
from typing import Any, Callable, Dict, Hashable, Iterable, List, Set, Tuple
|
|
|
|
from sqlalchemy.orm import Session
|
|
|
|
from wrolpi.common import get_media_directory
|
|
|
|
|
|
@dataclass
|
|
class SectionDiff:
|
|
"""What applying a config file changes in one section. Rows are the file's, as `ConfigSection.file_rows`
|
|
returns them."""
|
|
added: Dict[Hashable, dict] = field(default_factory=dict)
|
|
changed: Dict[Hashable, dict] = field(default_factory=dict)
|
|
removed: Set[Hashable] = field(default_factory=set)
|
|
|
|
def __bool__(self):
|
|
return bool(self.added or self.changed or self.removed)
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Unreadable:
|
|
"""The invalid key of an entry too malformed to name a row (not a mapping, no name). It is counted as skipped, so
|
|
the file is not saved over it, but it keeps no row, and on its own it does not make a section present."""
|
|
position: int
|
|
|
|
|
|
def listed(file_rows: dict, invalid_keys: set) -> bool:
|
|
"""Whether a section lists anything: a row, or an invalid row it names."""
|
|
return bool(file_rows) or any(not isinstance(i, Unreadable) for i in invalid_keys)
|
|
|
|
|
|
class ConfigSection:
|
|
"""One kind of row a database config saves.
|
|
|
|
Subclasses define how a file row and a database row become the same comparable dict (the values the config
|
|
saves, keyed by `key`), and how to write the differences."""
|
|
name: str = None
|
|
|
|
def file_rows(self, config: dict) -> Tuple[Dict[Hashable, dict], Set[Hashable]]:
|
|
"""The rows this section of `config` (the file's data) lists, keyed, plus the keys of rows that are invalid.
|
|
An invalid row is skipped, but its key counts as listed, so it is never deleted."""
|
|
raise NotImplementedError()
|
|
|
|
def db_rows(self, session: Session) -> Dict[Hashable, dict]:
|
|
"""The rows the config saves, keyed and compared like `file_rows`. Rows the config never saves are left
|
|
out: they are never "removed"."""
|
|
raise NotImplementedError()
|
|
|
|
def upsert(self, session: Session, rows: Dict[Hashable, dict]):
|
|
"""Write these added or changed rows. Fetch the current rows by key first: one may have been created or
|
|
deleted since the snapshot."""
|
|
raise NotImplementedError()
|
|
|
|
def present(self, config: dict, file_rows: dict, invalid_keys: set) -> bool:
|
|
"""Whether the file lists this section at all; an empty section cannot be told apart from a lost or blanked
|
|
file, so it removes nothing."""
|
|
return listed(file_rows, invalid_keys)
|
|
|
|
def same(self, file_row: dict, db_row: dict) -> bool:
|
|
"""Whether a file row is already in the database."""
|
|
return file_row == db_row
|
|
|
|
def delete(self, session: Session, keys: Set[Hashable]):
|
|
"""Delete the rows with these keys. A row deleted since the snapshot, or no longer saved by the config, is
|
|
left alone."""
|
|
raise NotImplementedError()
|
|
|
|
|
|
def diff_section(file_rows: Dict[Hashable, dict], invalid_keys: Set[Hashable], db_rows: Dict[Hashable, dict],
|
|
deletes: bool, same: Callable[[dict, dict], bool] = operator.eq, present: bool = None) \
|
|
-> SectionDiff:
|
|
"""Compare a section's file rows with its database rows. `deletes`: rows the file no longer lists are removed.
|
|
A section that is not `present` (by default, an empty one) never removes anything: it cannot be told apart from
|
|
a lost or blanked file."""
|
|
diff = SectionDiff()
|
|
for key, row in file_rows.items():
|
|
if key not in db_rows:
|
|
diff.added[key] = row
|
|
elif not same(row, db_rows[key]):
|
|
diff.changed[key] = row
|
|
if present is None:
|
|
present = listed(file_rows, invalid_keys)
|
|
if deletes and present:
|
|
diff.removed = db_rows.keys() - file_rows.keys() - invalid_keys
|
|
return diff
|
|
|
|
|
|
def media_relative(path) -> str:
|
|
"""A path as a config names it: relative to the media directory."""
|
|
path = pathlib.Path(path)
|
|
return str(path.relative_to(get_media_directory()) if path.is_absolute() else path)
|
|
|
|
|
|
def chunks(items: Iterable[Any], size: int = 500) -> Iterable[List[Any]]:
|
|
"""Split `items` for `IN (...)` queries (SQLite limits the parameters of one statement)."""
|
|
items = list(items)
|
|
for i in range(0, len(items), size):
|
|
yield items[i:i + size]
|