Files
romm/backend/utils/database.py
Sam Dornan a429c4b9db perf(backend): add the missing gallery indexes and reconcile model/schema drift
Four query shapes had no index that could serve both their predicate and
their sort, and a class of foreign-key columns was relying on an implicit
index that only MariaDB and MySQL provide.

New portable indexes:

- `screenshots (rom_id, user_id)`. `Save.screenshot` / `State.screenshot`
  resolve a thumbnail per row, so this lookup runs once per card on the
  continue-playing rail. 0093 added the equivalent to `states` and noted
  `saves` already had it; `screenshots` was missed.
- `rom_user (user_id, rom_id)` and `rom_user (user_id, last_played)`.
  `unique_rom_user_props` leads with `rom_id`, which covers the gallery's
  outer join but not the reverse direction, where sorting or scoping by a
  per-user column starts from this table.
- `roms (platform_id, name_sort_key)`. The gallery is browsed one platform
  at a time and ordered by name, and no index carried both columns. On a
  120k-row library across 20 platforms this takes the first page from
  5.8ms/1568 buffers to 0.6ms/75 buffers. Deep offsets converge, since the
  skipped rows are walked either way.

New PostgreSQL-only foreign-key indexes:

MariaDB and MySQL index every foreign key whose column is not already some
index's leftmost prefix; PostgreSQL does not. Eight such columns are queried
directly or walked by `ON DELETE`, so they get a real index there. Creating
them everywhere would leave the other backends with duplicates, so they are
dialect-gated and exempt from autogenerate.

Model/schema reconciliation:

Fifteen live indexes existed only in the migrations. Worse, `alembic/env.py`
never imported six models, so `devices`, `client_tokens`, `device_save_sync`,
`sync_sessions`, `play_sessions` and `streaming_container_adoptions` were
absent from the metadata autogenerate compares against, and autogenerate in
fact failed outright resolving `saves.origin_device_id`. With the imports
fixed it would have proposed dropping every one of those indexes.

Declares all of them on their models, matches `PlaySession` to the unique
index 0076 actually created, and adds a test that fails on any future index
drift so this cannot silently recur.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WgeQBXh6SJyxXVHSL5EuoF
2026-09-07 13:46:35 +00:00

198 lines
7.4 KiB
Python

import json
from typing import Any, Sequence
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql as sa_pg
from sqlalchemy.orm import Session
from sqlalchemy.sql import ColumnElement, func
# Foreign-key columns that MariaDB/MySQL index implicitly but PostgreSQL does
# not, so migration 0122 creates them there only. Shared with `alembic/env.py`,
# which hides them from autogenerate: a model declaration would give the other
# backends a duplicate index.
POSTGRESQL_FK_INDEXES: tuple[tuple[str, str, list[str]], ...] = (
("collections", "ix_collections_user_id", ["user_id"]),
("smart_collections", "ix_smart_collections_user_id", ["user_id"]),
("rom_notes", "ix_rom_notes_user_id", ["user_id"]),
("firmware", "ix_firmware_platform_id", ["platform_id"]),
("collections_roms", "ix_collections_roms_rom_id", ["rom_id"]),
("music_playlist_tracks", "ix_music_playlist_tracks_rom_file_id", ["rom_file_id"]),
("music_favorite_tracks", "ix_music_favorite_tracks_rom_file_id", ["rom_file_id"]),
("play_sessions", "ix_play_sessions_rom_id", ["rom_id"]),
)
POSTGRESQL_FK_INDEX_NAMES = frozenset(name for _, name, _ in POSTGRESQL_FK_INDEXES)
# Search indexes built per dialect in 0084: a FULLTEXT index on MySQL/MariaDB,
# pg_trgm GIN indexes on PostgreSQL. No portable model declaration exists.
DIALECT_SEARCH_INDEX_NAMES = frozenset(
{
"idx_roms_name_fs_name_fulltext",
"idx_roms_name_trgm",
"idx_roms_fs_name_trgm",
}
)
# Indexes that exist in some databases but cannot be declared on a model, so
# autogenerate must not propose creating or dropping them.
AUTOGENERATE_EXEMPT_INDEX_NAMES = (
DIALECT_SEARCH_INDEX_NAMES | POSTGRESQL_FK_INDEX_NAMES
)
def CustomJSON(**kwargs: Any) -> sa.JSON:
"""Custom SQLAlchemy JSON type that uses JSONB on PostgreSQL."""
return sa.JSON(**kwargs).with_variant(sa_pg.JSONB(**kwargs), "postgresql")
def is_db_version_compatible(
conn: sa.Connection,
min_version: tuple[int, ...] | None = None,
) -> bool:
"""Check if the database server version complies with the given version constraints."""
if min_version is None:
return True
server_version = conn.engine.dialect.server_version_info
return bool(server_version and server_version >= min_version)
def is_postgresql(
conn: sa.Connection, min_version: tuple[int, ...] | None = None
) -> bool:
if conn.engine.name != "postgresql":
return False
return is_db_version_compatible(conn, min_version=min_version)
def is_mysql(conn: sa.Connection, min_version: tuple[int, ...] | None = None) -> bool:
if conn.engine.name != "mysql":
return False
return is_db_version_compatible(conn, min_version=min_version)
def is_mariadb(conn: sa.Connection, min_version: tuple[int, ...] | None = None) -> bool:
if conn.engine.name != "mariadb":
return False
return is_db_version_compatible(conn, min_version=min_version)
def json_array_contains_value(
column: sa.Column | Any, value: str | int, *, session: Session
) -> ColumnElement:
"""Check if a JSON array column contains the given value."""
conn = session.get_bind()
if is_postgresql(conn):
# In PostgreSQL, string values can be checked for containment using the `?` operator.
# For other types, we use the `@>` operator.
if isinstance(value, str):
return sa.type_coerce(column, sa_pg.JSONB).has_key(value)
return sa.type_coerce(column, sa_pg.JSONB).contains(
func.cast(value, sa_pg.JSONB)
)
elif is_mysql(conn) or is_mariadb(conn):
# In MySQL and MariaDB, JSON_CONTAINS requires a JSON-formatted string (even if it's an int).
return func.json_contains(column, json.dumps(value))
raise NotImplementedError(
f"json_array_contains_value is not implemented for engine: {conn.engine.name}"
)
def json_array_contains_any(
column: sa.Column | Any, values: Sequence[str] | Sequence[int], *, session: Session
) -> ColumnElement:
"""Check if a JSON array column contains any of the given values."""
if not values:
return sa.false()
# Optimize for single value case
if len(values) == 1:
return json_array_contains_value(column, values[0], session=session)
conn = session.get_bind()
if is_postgresql(conn):
# In PostgreSQL, string arrays can be checked for overlap using the `?|` operator.
# For other types, we combine element-wise checks with OR.
if isinstance(values[0], str):
return sa.type_coerce(column, sa_pg.JSONB).has_any(
sa.type_coerce(values, sa_pg.ARRAY(sa_pg.TEXT))
)
return sa.or_(
*[json_array_contains_value(column, v, session=session) for v in values]
)
elif is_mysql(conn) or is_mariadb(conn, min_version=(10, 9)):
# In MySQL and MariaDB, JSON_OVERLAPS requires a JSON-formatted string (even if it's an int).
return func.json_overlaps(column, json.dumps(values))
elif is_mariadb(conn):
# MariaDB before 10.9 does not have JSON_OVERLAPS, so we fall back to element-wise checks.
return sa.or_(
*[json_array_contains_value(column, v, session=session) for v in values]
)
raise NotImplementedError(
f"json_array_contains_any is not implemented for engine: {conn.engine.name}"
)
def json_array_contains_all(
column: sa.Column | Any, values: Sequence[Any], *, session: Session
) -> ColumnElement:
"""Check if a JSON array column contains all of the given values."""
if not values:
return sa.false()
conn = session.get_bind()
if is_postgresql(conn):
# In PostgreSQL, string arrays can be checked for containment using the `?&` operator.
# For other types, we combine element-wise checks with AND.
if isinstance(values[0], str):
return sa.type_coerce(column, sa_pg.JSONB).has_all(
sa.type_coerce(values, sa_pg.ARRAY(sa_pg.TEXT))
)
return sa.and_(
*[json_array_contains_value(column, v, session=session) for v in values]
)
elif is_mysql(conn) or is_mariadb(conn):
# In MySQL and MariaDB, JSON_CONTAINS requires a JSON-formatted string (even if it's an int).
return func.json_contains(column, json.dumps(values))
raise NotImplementedError(
f"json_array_contains_all is not implemented for engine: {conn.engine.name}"
)
LIKE_ESCAPE_CHAR = "\\"
def escape_like(term: str) -> str:
"""Escape LIKE wildcards so a search term matches literally (pass escape=LIKE_ESCAPE_CHAR to like())."""
return (
term.replace(LIKE_ESCAPE_CHAR, LIKE_ESCAPE_CHAR * 2)
.replace("%", f"{LIKE_ESCAPE_CHAR}%")
.replace("_", f"{LIKE_ESCAPE_CHAR}_")
)
def safe_str_to_bool(value: Any, default: bool = False) -> bool:
"""Safely convert a value to bool, returning default if conversion fails."""
try:
return value.strip().lower() in ("1", "true", "yes", "on")
except (ValueError, TypeError, AttributeError):
return default
def safe_float(value: Any, default: float = 0.0) -> float:
"""Safely convert a value to float, returning default if conversion fails."""
try:
return float(value)
except (ValueError, TypeError):
return default
def safe_int(value: Any, default: int = 0) -> int:
"""Safely convert a value to int, returning default if conversion fails."""
try:
return int(value)
except (ValueError, TypeError):
return default