mirror of
https://github.com/rommapp/romm.git
synced 2026-12-04 12:52:19 +01:00
* chore(api): add indexes to roms * chore(api): add additional indexes * chore(api): widen indexes on rom table * perf(api): fast filtered and short searches on MariaDB, plus year, rating and game mode filter * chore(api): add ANALYZE TABLE at end of migration * pr-ready: drop the roms_search table * pr-ready: code-review * pr-ready: review-polish Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * pr-ready: prose Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * chore(api): use hand-coded list of columns * pr-ready: code-review Restore the schema before asserting in the 0163 schema tests, send platform_ids in the endpoint test, and fix two stale comments. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * pr-ready: simplify Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * pr-ready: review-polish Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * pr-ready: prose Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * pr-ready: prose Reword the comments code-review added to the 0163 schema tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(database): cover year_range_ms Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(database): raise the sort limit on MariaDB through the mysql driver The listener keyed on the dialect name, which is mysql when ROMM_DB_DRIVER=mysql reaches a MariaDB server. Check the dialect's is_mariadb instead. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: fix the sort limit tests on PostgreSQL and the _ms types The sort limit tests read is_mariadb from the test engine, which PostgreSQL's dialect lacks, so they now set it. _ms takes named date parts again, since mypy rejects a star tuple before tzinfo. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com> Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
120 lines
4.0 KiB
Python
120 lines
4.0 KiB
Python
import functools
|
|
import logging
|
|
import time
|
|
from typing import Any, cast
|
|
|
|
from sqlalchemy import Connection, CursorResult, Result, create_engine, event
|
|
from sqlalchemy.orm import sessionmaker
|
|
|
|
from config import DB_POOL_RECYCLE_SECONDS, DEV_SQL_ECHO
|
|
from logger.logger import log
|
|
from models import load_all_models
|
|
from utils.database import get_db_url
|
|
|
|
# A ping on a socket the server already closed blocks the worker until TCP gives
|
|
# up, so `pool_pre_ping` alone is not enough.
|
|
sync_engine = create_engine(
|
|
get_db_url(),
|
|
pool_pre_ping=True,
|
|
pool_recycle=DB_POOL_RECYCLE_SECONDS,
|
|
echo=False,
|
|
)
|
|
sync_session = sessionmaker(bind=sync_engine, expire_on_commit=False)
|
|
|
|
|
|
@functools.cache
|
|
def _warn_statement_binlog() -> None:
|
|
log.warning(
|
|
"binlog_format is STATEMENT, so database sessions stay at REPEATABLE READ; "
|
|
"concurrent writes may fail with 'Record has changed since last read'"
|
|
)
|
|
|
|
|
|
def read_committed(dbapi_connection: Any, connection_record: Any) -> None:
|
|
"""Run the session at READ COMMITTED, unless statement binary logging forbids it."""
|
|
cursor = dbapi_connection.cursor()
|
|
try:
|
|
cursor.execute("SELECT @@log_bin, @@binlog_format")
|
|
log_bin, binlog_format = cursor.fetchone()
|
|
# InnoDB refuses every write below REPEATABLE READ under STATEMENT logging.
|
|
if log_bin and binlog_format == "STATEMENT":
|
|
_warn_statement_binlog()
|
|
else:
|
|
cursor.execute("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED")
|
|
finally:
|
|
cursor.close()
|
|
dbapi_connection.commit()
|
|
|
|
|
|
# MariaDB's 1,024-byte default makes a sort on a long key re-read each wide row by
|
|
# id afterwards. This limit keeps the selected values in the sort instead.
|
|
SORT_DATA_LIMIT_BYTES = 1024 * 1024
|
|
|
|
|
|
def raise_sort_data_limit(dbapi_connection: Any, connection_record: Any) -> None:
|
|
"""Raise MariaDB's sort data limit so a sort on a long key keeps the row values."""
|
|
# MySQL deprecated this variable. The mysql driver can also reach a MariaDB server.
|
|
if not getattr(sync_engine.dialect, "is_mariadb", False):
|
|
return
|
|
cursor = dbapi_connection.cursor()
|
|
try:
|
|
cursor.execute(
|
|
f"SET SESSION max_length_for_sort_data = {SORT_DATA_LIMIT_BYTES}"
|
|
)
|
|
finally:
|
|
cursor.close()
|
|
|
|
|
|
# MariaDB 11.6+ at REPEATABLE READ fails a write to a row the transaction read
|
|
# before another one committed to it (error 1020). PostgreSQL defaults to this.
|
|
if sync_engine.dialect.name in ("mariadb", "mysql"):
|
|
event.listen(sync_engine, "connect", read_committed)
|
|
event.listen(sync_engine, "connect", raise_sort_data_limit)
|
|
|
|
# Disable SQLAlchemy logging as echo will print the queries
|
|
logging.getLogger("sqlalchemy.engine.Engine").handlers = [logging.NullHandler()]
|
|
|
|
|
|
if DEV_SQL_ECHO:
|
|
|
|
@event.listens_for(sync_engine, "before_cursor_execute")
|
|
def before_cursor_execute(
|
|
conn: Connection,
|
|
cursor: Any,
|
|
statement: str,
|
|
parameters: Any,
|
|
context: Any,
|
|
executemany: bool,
|
|
) -> None:
|
|
context._query_start_time = time.time()
|
|
print("--------START--------")
|
|
print(f"SQL: {statement}")
|
|
print(f"Parameters: {parameters}")
|
|
|
|
@event.listens_for(sync_engine, "after_cursor_execute")
|
|
def after_cursor_execute(
|
|
conn: Connection,
|
|
cursor: Any,
|
|
statement: str,
|
|
parameters: Any,
|
|
context: Any,
|
|
executemany: bool,
|
|
) -> None:
|
|
total_time = time.time() - context._query_start_time
|
|
print(f"Execution time: {total_time:.4f} seconds")
|
|
print("--------END--------")
|
|
|
|
|
|
class DBBaseHandler: ...
|
|
|
|
|
|
def affected_rows(result: Result[*tuple[Any, ...]]) -> int:
|
|
"""How many rows an UPDATE or DELETE run through `Session.execute` matched."""
|
|
# Session.execute is typed to return Result, but DML gets a CursorResult.
|
|
return cast(CursorResult[*tuple[Any, ...]], result).rowcount
|
|
|
|
|
|
# A process may load one model, whose relationships name others by string, and
|
|
# the mappers configure only once every one of them is loaded.
|
|
load_all_models()
|