wrolpi/wrolpi/media_path.py
lrnselfreliance dab333124e
Upgrade to SQLAlchemy 2.0 (synchronous) (#803)
SQLAlchemy 1.3 has been end-of-life since 2021, and alembic was held at 1.10
because newer releases need SQLAlchemy 2.  This is a mechanical port; the code
stays synchronous.

- SQLAlchemy[asyncio]==2.0.54, alembic==1.20.0.
- Model annotations use Mapped[...] (2.0 rejects bare annotations on mapped
  attributes); declarative_base moves to sqlalchemy.orm.
- Plain SQL strings go through text() or exec_driver_sql; schema_ddl.execute_sql
  accepts a SQLAlchemy Connection or a raw sqlite3 connection, so rebuild_fts
  works from the baseline migration again.
- Session.get replaces Query.get; session.in_transaction() replaces
  session.transaction; cache_ok on MediaPathType and FancyJSON.
- The tag-directory sync query joins through TagFile's relationships instead of
  the legacy two-entity outerjoin.
- Section-hint rows use attribute access (2.0 rows are tuples).
- Migrations run on an AUTOCOMMIT connection, matching 1.3, where each
  statement committed on its own.  2.0 autobegins, so the unique-stem
  migration's read snapshot could not become a writer after its helpers wrote
  on another connection ("database is locked").  The begin listener emits no
  BEGIN for AUTOCOMMIT connections.
- Newer alembic compares column types: WrolpiKV now describes the TEXT table
  its migration created.
- The test database installs its DDL inside engine.begin(); 2.0 connections
  no longer autocommit, so the FTS tables were rolled back.
- Dependabot now holds SQLAlchemy at 2.0 instead of 1.3.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 15:08:40 -06:00

35 lines
1 KiB
Python

import pathlib
from typing import Union
from sqlalchemy import types
PATH_TYPE = Union[str, pathlib.Path]
class MediaPathType(types.TypeDecorator): # noqa
impl = types.String
cache_ok = True
def process_bind_param(self, value, dialect):
"""Convert paths into what the DB expects. (pathlib.Path -> str)"""
if value is None:
return value
if value == '':
raise ValueError('MediaPath cannot be empty')
if isinstance(value, pathlib.Path):
if not value.is_absolute():
# Resolve relative paths against media directory, not cwd
from wrolpi.common import get_media_directory
value = get_media_directory() / value
value = str(value)
if not isinstance(value, str):
raise ValueError(f'Invalid MediaPath type ({type(value)}): {value}')
return value
def process_result_value(self, value, dialect):
if value:
return pathlib.Path(value)