From 84726ba9a2f76bf98e85a650cefcb84c8036fee8 Mon Sep 17 00:00:00 2001 From: Sam Dornan Date: Sat, 26 Sep 2026 19:08:25 -0400 Subject: [PATCH] refactor(backend): move FORCE INDEX hint and FULLTEXT match into sql_dialect (#4825) --- backend/handler/database/roms_handler.py | 10 ++-- backend/handler/database/saves_handler.py | 8 ++-- backend/tests/utils/test_sql_dialect.py | 57 ++++++++++++++++++++++- backend/utils/sql_dialect.py | 24 +++++++++- 4 files changed, 87 insertions(+), 12 deletions(-) diff --git a/backend/handler/database/roms_handler.py b/backend/handler/database/roms_handler.py index 32c217d5d..d6be4d0ed 100644 --- a/backend/handler/database/roms_handler.py +++ b/backend/handler/database/roms_handler.py @@ -35,7 +35,6 @@ from sqlalchemy import ( union, update, ) -from sqlalchemy.dialects import mysql from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import ( ColumnProperty, @@ -100,6 +99,7 @@ from utils.platform_slugs import UniversalPlatformSlug as UPS from utils.sql_dialect import ( Analyze, DialectCase, + fulltext_match, json_array_contains_all, json_array_contains_any, json_array_contains_value, @@ -234,11 +234,11 @@ def _nulls_last_ordering( return None, nulls_last(sort_key, descending) -def _fulltext_match(boolean_query: str) -> mysql.match: +def _fulltext_match(boolean_query: str) -> ColumnElement[Any]: """A MariaDB/MySQL FULLTEXT match of the ROM's name and filename.""" - return mysql.match( - Rom.name.expression, Rom.fs_name.expression, against=boolean_query - ).in_boolean_mode() + return fulltext_match( + Rom.name.expression, Rom.fs_name.expression, boolean_query=boolean_query + ) # Filter dropdowns read the narrow `roms_facets` mirror instead of `roms`, diff --git a/backend/handler/database/saves_handler.py b/backend/handler/database/saves_handler.py index f71af2de7..b5892b911 100644 --- a/backend/handler/database/saves_handler.py +++ b/backend/handler/database/saves_handler.py @@ -10,6 +10,7 @@ from decorators.database import begin_session from models.assets import SAVE_SLOT_VERSIONS_INDEX, Save from models.base import with_file_name_parts from models.rom import Rom +from utils.sql_dialect import force_index_on_mysql from .base_handler import DBBaseHandler, affected_rows from .deleted_assets_handler import DBDeletedAssetsHandler @@ -402,11 +403,10 @@ class DBSavesHandler(DBBaseHandler): _lock_slot(user_id, rom_id, slot, session) # Locks only this slot's rows and takes no snapshot, which MariaDB's # snapshot isolation would fail the delete against. - hint = f"FORCE INDEX ({SAVE_SLOT_VERSIONS_INDEX})" rows = session.execute( - past_keep.with_hint(Save, hint, "mariadb") - .with_hint(Save, hint, "mysql") - .with_for_update() + force_index_on_mysql( + past_keep, Save, SAVE_SLOT_VERSIONS_INDEX + ).with_for_update() ).all() fallback_hashes = fallback_hashes or {} unhashed = [ diff --git a/backend/tests/utils/test_sql_dialect.py b/backend/tests/utils/test_sql_dialect.py index 17ce74f88..e379c75aa 100644 --- a/backend/tests/utils/test_sql_dialect.py +++ b/backend/tests/utils/test_sql_dialect.py @@ -10,18 +10,27 @@ from tests.sql_dialects import ( ) from handler.database.base_handler import sync_engine +from models.assets import SAVE_SLOT_VERSIONS_INDEX, Save +from models.rom import Rom from utils.database import CustomJSON from utils.sql_dialect import ( Analyze, DialectCase, JsonArrayColumn, + force_index_on_mysql, + fulltext_match, json_array_contains_all, json_array_contains_any, json_array_contains_value, nulls_last, ) -_T = sa.table("t", sa.column("v", sa.Integer), sa.column("tags", CustomJSON())) +_T = sa.table( + "t", + sa.column("v", sa.Integer), + sa.column("tags", CustomJSON()), + sa.column("name", sa.String), +) def _where_sql(condition: sa.ColumnElement[bool], dialect: sa.Dialect) -> str: @@ -237,3 +246,49 @@ class TestAnalyze: def test_runs_on_the_running_engine(self): with sync_engine.begin() as connection: connection.execute(Analyze("roms")) + + +class TestForceIndexOnMysql: + @pytest.mark.parametrize( + ("dialect", "expected"), + [ + (MARIADB_DIALECT, "FROM t FORCE INDEX (ix_t_v)"), + (mysql.dialect(), "FROM t FORCE INDEX (ix_t_v)"), + (POSTGRESQL_DIALECT, "FROM t"), + ], + ) + def test_only_the_mysql_family_gets_the_hint( + self, dialect: sa.Dialect, expected: str + ): + statement = force_index_on_mysql(sa.select(_T.c.v), _T, "ix_t_v") + + assert compile_sql(statement, dialect).split("\n")[-1] == expected + + def test_runs_on_the_running_engine(self): + statement = force_index_on_mysql( + sa.select(Save.id), Save, SAVE_SLOT_VERSIONS_INDEX + ).with_for_update() + + with sync_engine.begin() as connection: + connection.execute(statement) + + +class TestFulltextMatch: + def test_matches_in_boolean_mode(self): + match = fulltext_match(_T.c.name, boolean_query="+zelda*") + + assert _where_sql(match, MARIADB_DIALECT) == ( + "MATCH (t.name) AGAINST (:param_1 IN BOOLEAN MODE)" + ) + + def test_runs_against_the_roms_fulltext_index(self): + """MySQL and MariaDB refuse a column list no FULLTEXT index spans exactly.""" + condition = DialectCase( + postgresql=sa.true(), + mysql=fulltext_match( + Rom.name.expression, Rom.fs_name.expression, boolean_query="+zelda*" + ), + ) + + with sync_engine.connect() as connection: + connection.execute(sa.select(Rom.id).where(condition)) diff --git a/backend/utils/sql_dialect.py b/backend/utils/sql_dialect.py index 83f782ba7..5fa860725 100644 --- a/backend/utils/sql_dialect.py +++ b/backend/utils/sql_dialect.py @@ -6,6 +6,7 @@ from typing import Any import sqlalchemy as sa from sqlalchemy import SQLColumnExpression +from sqlalchemy.dialects import mysql as sa_mysql from sqlalchemy.dialects import postgresql as sa_pg from sqlalchemy.ext.compiler import compiles from sqlalchemy.sql import ClauseElement, ColumnElement, func @@ -13,13 +14,15 @@ from sqlalchemy.sql.compiler import DDLCompiler, SQLCompiler from sqlalchemy.sql.ddl import ExecutableDDLElement from sqlalchemy.sql.elements import ClauseList from sqlalchemy.sql.operators import OperatorType, comma_op -from sqlalchemy.sql.selectable import FromClause +from sqlalchemy.sql.selectable import FromClause, Select from sqlalchemy.sql.visitors import InternalTraversal # A JSON column holding an array: `Mapped[list[str] | None]`, `Mapped[set[int]]`... type JsonArrayColumn = SQLColumnExpression[Collection[Any] | None] type JsonArrayValues = Sequence[str] | Sequence[int] +_MYSQL_FAMILY = ("mysql", "mariadb") + def _compiles_on_mysql_family[F: Callable[..., str]]( construct: type[ClauseElement], @@ -27,7 +30,9 @@ def _compiles_on_mysql_family[F: Callable[..., str]]( """Register a compiler for MySQL and MariaDB; `"mysql"` alone misses MariaDB.""" def decorate(fn: F) -> F: - return compiles(construct, "mariadb")(compiles(construct, "mysql")(fn)) + for dialect_name in _MYSQL_FAMILY: + fn = compiles(construct, dialect_name)(fn) + return fn return decorate @@ -95,6 +100,21 @@ def nulls_last[T](sort_key: SQLColumnExpression[T], descending: bool) -> Dialect ) +def force_index_on_mysql[S: Select[Any]]( + statement: S, table: FromClause | type[Any], index_name: str +) -> S: + """Make MySQL and MariaDB read `table` through `index_name`; PostgreSQL plans freely.""" + hint = f"FORCE INDEX ({index_name})" + for dialect_name in _MYSQL_FAMILY: + statement = statement.with_hint(table, hint, dialect_name) + return statement + + +def fulltext_match(*columns: ColumnElement[Any], boolean_query: str) -> sa_mysql.match: + """A boolean-mode match over one FULLTEXT index's columns, for a `mysql` branch.""" + return sa_mysql.match(*columns, against=boolean_query).in_boolean_mode() + + def _jsonb(column: JsonArrayColumn) -> ColumnElement[Any]: return sa.type_coerce(column, sa_pg.JSONB)