Cut the comments that explain rather than note: the migration's four-paragraph
docstring, the upload-path and digest-SQL docstrings, and the mark-missing note
in the scan loop. Drop an em-dash from LocationChip's header per CLAUDE.md.
Reword 0126's downgrade error so it no longer embeds a SELECT, which bandit
reads as string-built SQL, and mark the dialect-selected backfill nosec B608 the
way the other migrations do.
Add the LocationChip test its HashChip sibling already had, covering the copy
going through useClipboard (the composable is what applies the secure-context
guard).
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Key the unique roms index on a sha256 digest of the full path. Indexing
(platform_id, fs_path, fs_name) directly is 5804 bytes of utf8mb4, which MySQL
rejects with ER_TOO_LONG_KEY and MariaDB silently demotes to a hash index; the
digest column keeps it a 260-byte BTREE on every supported driver. It is derived
by the same @validates hook that maintains the other fs_name columns, and
resynced explicitly in update_rom and convert_rom_to_folder.
Migration 0126 backfills the digest in one dialect-branched UPDATE. A Python
executemany right after the ADD COLUMN silently applies only its first parameter
set on mariadb-connector, leaving the rest NULL. test_migrations pins the SQL
expression to compute_full_path_hash so the two cannot drift.
Drop the relocation pre-pass. mark_missing_roms already runs before the identify
loop, so a moved file reaches get_matching_missing_rom, which requires all three
hashes to agree (or a title_id, covering non-hashable platforms), refuses
ambiguous matches, re-parses filename tags and emits over the socket. The
pre-pass duplicated it with a weaker CRC-only check, hashed every candidate
twice, compared folder sizes against a total that excludes filtered files, and
ran on QUICK scans.
Send uploads to a folder the platform's structure will actually discover, so the
next scan does not flag a fresh upload as missing, and refuse with a 400 when
only the user can pick the folder.
Make 0126's downgrade refuse when duplicate file names exist instead of deleting
the roms (and their saves, notes and collection membership) that carry them.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Cut the docstrings back to the one paragraph the surrounding migrations use,
and drop the comments that restate the index name next to them.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The list covered firmware and the music tables but not saves.user_id,
states.user_id, screenshots.user_id, rom_file_user.user_id,
memory_cards.platform_id or streaming_container_adoptions.decided_by_user_id,
so a user delete still sequentially scanned the three largest per-user tables
on PostgreSQL, which is the case the pass set out to fix.
Add a test that recomputes the rule (a single-column foreign key whose column
leads no index, primary key or unique constraint) from the model metadata, so
the next model foreign key cannot be forgotten silently.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
`play_sessions.device_id` and `play_sessions.sync_session_id` were left out of
the PostgreSQL foreign-key list, which is inconsistent with the criterion 0124
states for itself: a column queried directly or walked by `ON DELETE` needs a
real index there. Every other index on the table leads with `user_id`, so
`device_id` is only ever a second column and `sync_session_id` appeared in no
index at all. Both are `ON DELETE SET NULL`, so deleting a device or a sync
session made PostgreSQL scan the whole table.
That scan grows with every session played. On a 60k-row table with 1200 rows
pointing at one device, the row lookup behind the SET NULL goes from a 7.6ms
sequential scan to a 0.14ms index probe, taking the statement from 53ms to
38ms; the remainder is row rewriting no index avoids.
The `device_id` query filter in `get_existing_session_keys` is already served
by `uq_play_session_identity`, since it leads with `user_id` too, so this is
about the delete path rather than that lookup.
MariaDB is unaffected: InnoDB already created implicit indexes on all three
columns, which is why these are dialect-gated.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WgeQBXh6SJyxXVHSL5EuoF
`trunk_check` reported `backend/utils/database.py` as unformatted. Adding the
index constants pulled the file into trunk's modified-file scope, which
surfaced a formatting deviation that predates this branch: black 26.5.1 drops
the redundant parentheses from an `except` tuple, which PEP 758 makes valid
syntax on the Python 3.14 this project requires. Three `except` clauses in
otherwise untouched helpers change as a result; the file cannot pass
`trunk fmt` without them.
Also collapses the AUTOGENERATE_EXEMPT_INDEX_NAMES assignment onto one line,
which is the same formatter's doing.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WgeQBXh6SJyxXVHSL5EuoF
Adding a composite index that leads with a foreign-key column lets InnoDB
re-point the constraint at it and discard the implicit single-column index.
Reversing 0122 then failed with "Cannot drop index 'ix_rom_user_user_rom':
needed in a foreign key constraint" on `rom_user.user_id`, and would have on
`screenshots.rom_id`. The downgrade now restores those two implicit indexes
first, and a full up/down/up cycle leaves the schema byte-identical to a
database that never ran the migration.
Also sets `path_separator = os` in alembic.ini, silencing the deprecation
warning about the legacy space/comma/colon path splitting. `prepend_sys_path`
holds a single entry, so the behaviour is unchanged.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WgeQBXh6SJyxXVHSL5EuoF
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
- Cast year to text in the /api/music years facet search so Postgres does
not error on lower(integer) (MariaDB/SQLite auto-cast, hiding it in CI)
- Escape LIKE wildcards in music search via new utils.database.escape_like
- Drop lazy="selectin" on RomFile.track_meta; eager-load only where the
metadata is serialized (get_rom already did; add the three soundtrack reads)
- Migration backfill uses a single query + fetchmany (repo idiom, see 0084)
instead of manual keyset paging, in both directions
- Guard the extensionless folder-conversion collision (stale row over a
directory the user already created on disk)
- Renumber migration 0093 -> 0094 after 0093_states_rom_user_index landed
Fix existing JSON array util `json_array_contains_value`, and add two
new utils: `json_array_contains_any` and `json_array_contains_all`.
These utils have been tested with arrays of strings and integers, on the
following database engine versions:
- PostgreSQL: 12, 13, 14, 15, 16, 17, 18
- MySQL: 8.0, 8.4, 9.0, 9.4
- MariaDB: 10.5, 10.6, 10.11, 11.4, 11.8, 12.0
Fix `json_array_contains_value` function to use the `@>` operator for
checking if a JSON array contains a value in PostgreSQL. This is
necessary because the `has_key` function only works for string values.
Also, remove `get_rom_collections` method, as it was doing the same
thing as `get_collections_by_rom_id`.
Fixes#1441.
This change introduces PostgreSQL compatibility, by implementing the
following changes:
* Use `JSONB` instead of `JSON` for PostgreSQL databases. This is
achieved by creating a custom `CustomJSON` type that uses `JSONB` on
PostgreSQL and `JSON` on other databases, leveraging the variant
mechanism of SQLAlchemy.
* Add `is_postgresql` function to check if the current database is
PostgreSQL. Commonly used for migrations, but can be used to determine
how to build queries based on the database engine.
* Add `json_array_contains_value` function to check if a JSON array
includes a specific value. This function is needed as it's
engine-specific.
Support for PostgreSQL is on a best-effort basis, and it relies on the
community for continued support and testing. The project's main database
is MariaDB.
Closes#667.