-
-
Notifications
You must be signed in to change notification settings - Fork 667
Expand file tree
/
Copy pathroms_handler.py
More file actions
1835 lines (1645 loc) · 60 KB
/
Copy pathroms_handler.py
File metadata and controls
1835 lines (1645 loc) · 60 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import functools
import json
import re
from collections.abc import Iterable, Sequence
from datetime import datetime
from typing import Any
from redis.exceptions import WatchError
from sqlalchemy import (
Integer,
String,
Text,
and_,
case,
cast,
delete,
false,
func,
literal,
not_,
or_,
select,
text,
update,
)
from sqlalchemy.orm import (
Query,
QueryableAttribute,
Session,
joinedload,
load_only,
noload,
selectinload,
undefer,
)
from sqlalchemy.sql.elements import ColumnElement
from sqlalchemy.sql.selectable import Select
from config import ROMM_DB_DRIVER
from decorators.database import begin_session
from handler.metadata.base_handler import UniversalPlatformSlug as UPS
from handler.redis_handler import sync_cache
from models.assets import Save, Screenshot, State
from models.base import compute_file_name_parts
from models.platform import Platform
from models.rom import (
Rom,
RomFile,
RomFileCategory,
RomMetadata,
RomNote,
RomUser,
SiblingRom,
compute_name_sort_key,
)
from utils.database import (
json_array_contains_all,
json_array_contains_any,
json_array_contains_value,
)
from .base_handler import DBBaseHandler
EJS_SUPPORTED_PLATFORMS = [
UPS._3DO,
UPS.AMIGA,
UPS.AMIGA_CD,
UPS.AMIGA_CD32,
UPS.ARCADE,
UPS.NEOGEOAES,
UPS.NEOGEOMVS,
UPS.ATARI2600,
UPS.ATARI5200,
UPS.ATARI7800,
UPS.C_PLUS_4,
UPS.CPET,
UPS.C64,
UPS.C128,
UPS.COLECOVISION,
UPS.JAGUAR,
UPS.LYNX,
UPS.DOS,
UPS.NEO_GEO_POCKET,
UPS.NEO_GEO_POCKET_COLOR,
UPS.NES,
UPS.FAMICOM,
UPS.FDS,
UPS.N64,
UPS.N64DD,
UPS.NDS,
UPS.NINTENDO_DSI,
UPS.GB,
UPS.GBA,
UPS.GBC,
UPS.PC_FX,
UPS.PHILIPS_CD_I,
UPS.PSX,
UPS.PSP,
UPS.SEGACD,
UPS.SEGA32,
UPS.GENESIS,
UPS.SMS,
UPS.GAMEGEAR,
UPS.SATURN,
UPS.SNES,
UPS.SFAM,
UPS.TG16,
UPS.VIC_20,
UPS.VIRTUALBOY,
UPS.WONDERSWAN,
UPS.WONDERSWAN_COLOR,
]
RUFFLE_SUPPORTED_PLATFORMS = [
UPS.BROWSER,
]
# Used to remove native full-text SQL operators
FULLTEXT_BOOLEAN_OPERATORS_REGEX = re.compile(r'[+\-~<>()"@*]')
# 3 is the default minimum size in InnoDB
FULLTEXT_MIN_TOKEN_SIZE = 3
# Cached ROM filter values (genres/franchises/etc.) so it doesn't get
# recomputed on every call to /api/roms
ROM_FILTERS_CACHE_VERSION_KEY = "filter_values:ver"
ROM_FILTERS_CACHE_KEYS_PREFIX = "filter_values:keys"
ROM_FILTERS_CACHE_TTL = 60 * 60 * 24 * 7 # 7 days
def _cache_value_to_str(value: Any) -> str | None:
if value is None:
return None
if isinstance(value, bytes):
return value.decode()
return str(value)
def _filter_values_cache_version() -> str:
return _cache_value_to_str(sync_cache.get(ROM_FILTERS_CACHE_VERSION_KEY)) or "0"
def _filter_values_cache_keys_key(version: str) -> str:
return f"{ROM_FILTERS_CACHE_KEYS_PREFIX}:v{version}"
def _store_versioned_cache(redis_key: str, version: str, result: Any) -> None:
version_keys_set = _filter_values_cache_keys_key(version)
with sync_cache.pipeline() as pipe:
try:
pipe.watch(ROM_FILTERS_CACHE_VERSION_KEY)
current_version = (
_cache_value_to_str(pipe.get(ROM_FILTERS_CACHE_VERSION_KEY)) or "0"
)
if current_version != version:
pipe.unwatch()
else:
pipe.multi()
pipe.set(redis_key, json.dumps(result), ex=ROM_FILTERS_CACHE_TTL)
pipe.sadd(version_keys_set, redis_key)
pipe.expire(version_keys_set, ROM_FILTERS_CACHE_TTL)
pipe.execute()
except WatchError:
pass
def _create_metadata_id_case(
prefix: str,
id_column: ColumnElement,
platform_id_column: ColumnElement,
):
return case(
(
id_column.isnot(None),
func.concat(
f"{prefix}-",
platform_id_column,
"-",
id_column,
),
),
else_=None,
)
def with_details(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
kwargs["query"] = select(Rom).options(
# Ensure platform is loaded for main ROM objects
selectinload(Rom.platform),
selectinload(Rom.saves).options(
noload(Save.rom),
noload(Save.user),
),
selectinload(Rom.states).options(
noload(State.rom),
noload(State.user),
),
selectinload(Rom.screenshots).options(
noload(Screenshot.rom),
),
selectinload(Rom.rom_users).options(noload(RomUser.rom)),
selectinload(Rom.metadatum).options(noload(RomMetadata.rom)),
# Multi-file downloads, 3DS QR codes, and metadata matching
selectinload(Rom.files).options(
joinedload(RomFile.rom).load_only(Rom.fs_path, Rom.fs_name)
),
selectinload(Rom.sibling_roms).options(
noload(Rom.platform),
noload(Rom.metadatum),
# Per-sibling is_main_sibling resolution for the
# SiblingRomSchema needs each sibling's RomUser for the
# request user — the relationship is `lazy="raise"`, so
# it has to be eager-loaded here.
selectinload(Rom.rom_users).options(noload(RomUser.rom)),
load_only(
Rom.id,
Rom.name,
Rom.fs_name_no_tags,
Rom.fs_name_no_ext,
),
),
selectinload(Rom.collections),
selectinload(Rom.notes),
undefer(Rom.multi_file),
undefer(Rom.top_level_file_count),
undefer(Rom.has_manual_files),
undefer(Rom.has_soundtrack),
)
return func(*args, **kwargs)
return wrapper
class DBRomsHandler(DBBaseHandler):
@begin_session
@with_details
def add_rom(
self,
rom: Rom,
query: Query = None, # type: ignore
session: Session = None, # type: ignore
) -> Rom:
rom = session.merge(rom)
session.flush()
return session.scalar(query.filter_by(id=rom.id).limit(1))
@begin_session
@with_details
def get_rom(
self,
id: int,
*,
query: Query = None, # type: ignore
session: Session = None, # type: ignore
) -> Rom | None:
return session.scalar(query.filter_by(id=id).limit(1))
@begin_session
@with_details
def get_roms_by_ids(
self,
ids: list[int],
*,
query: Query = None, # type: ignore
session: Session = None, # type: ignore
) -> Sequence[Rom]:
"""Get multiple ROMs by their IDs."""
if not ids:
return []
return session.scalars(query.filter(Rom.id.in_(ids))).all()
def get_files_for_roms(
self,
rom_ids: list[int],
*,
session: Session,
) -> dict[int, list[RomFile]]:
"""Return {rom_id: [RomFile, ...]} for the given rom IDs in a single query.
Used by the list endpoint to serialize files without relying on the
query's relationship eager-load surviving pagination.
"""
if not rom_ids:
return {}
files = session.scalars(
select(RomFile).where(RomFile.rom_id.in_(rom_ids))
).all()
buckets: dict[int, list[RomFile]] = {rom_id: [] for rom_id in rom_ids}
for file in files:
buckets[file.rom_id].append(file)
return buckets
def get_siblings_for_roms(
self,
rom_ids: list[int],
user_id: int,
*,
session: Session,
) -> dict[int, list[tuple[Rom, bool]]]:
"""Return {rom_id: [(sibling Rom, is_main_sibling), ...]} in a single query.
Joins sibling_roms → roms (only the columns SiblingRomSchema needs) and
left-joins rom_user for the requesting user, so the per-user
`is_main_sibling` flag is resolved without hydrating the wide roms table
or its JSON metadata on every page.
"""
if not rom_ids:
return {}
rows = session.execute(
select(
SiblingRom.rom_id,
Rom,
func.coalesce(RomUser.is_main_sibling, false()).label(
"is_main_sibling"
),
)
.join(Rom, Rom.id == SiblingRom.sibling_rom_id)
.outerjoin(
RomUser,
and_(
RomUser.rom_id == SiblingRom.sibling_rom_id,
RomUser.user_id == user_id,
),
)
.where(SiblingRom.rom_id.in_(rom_ids))
.options(
load_only(
Rom.name,
Rom.fs_name_no_tags,
Rom.fs_name_no_ext,
)
)
).all()
# Dedupe by (parent rom, sibling id) so a duplicate join row doesn't
# surface the same sibling twice on the wire.
seen: dict[int, set[int]] = {rom_id: set() for rom_id in rom_ids}
buckets: dict[int, list[tuple[Rom, bool]]] = {rom_id: [] for rom_id in rom_ids}
for rom_id, sibling, is_main in rows:
if sibling.id in seen[rom_id]:
continue
seen[rom_id].add(sibling.id)
buckets[rom_id].append((sibling, bool(is_main)))
return buckets
def filter_by_platform_id(self, query: Query, platform_id: int):
return query.filter(Rom.platform_id == platform_id)
def _filter_by_platform_ids(
self, query: Query, platform_ids: Sequence[int]
) -> Query:
return query.filter(Rom.platform_id.in_(platform_ids))
def _filter_by_collection_id(
self, query: Query, session: Session, collection_id: int
):
from . import db_collection_handler
collection = db_collection_handler.get_collection(collection_id)
if collection:
return query.filter(Rom.id.in_(collection.rom_ids))
return query
def _filter_by_virtual_collection_id(
self, query: Query, session: Session, virtual_collection_id: str
):
from . import db_collection_handler
v_collection = db_collection_handler.get_virtual_collection(
virtual_collection_id
)
if v_collection:
return query.filter(Rom.id.in_(v_collection.rom_ids))
return query
def _filter_by_smart_collection_id(
self, query: Query, session: Session, smart_collection_id: int, user_id: int
):
from . import db_collection_handler
smart_collection = db_collection_handler.get_smart_collection(
smart_collection_id
)
if smart_collection:
# Ensure the latest ROMs are loaded
smart_collection = smart_collection.update_properties(user_id)
return query.filter(Rom.id.in_(smart_collection.rom_ids))
return query
def _build_fulltext_boolean_query(self, term: str) -> str | None:
words = FULLTEXT_BOOLEAN_OPERATORS_REGEX.sub(" ", term).split()
if not words or any(len(word) < FULLTEXT_MIN_TOKEN_SIZE for word in words):
return None
return " ".join(f"+{word}*" for word in words)
def _build_fulltext_relevance(self, search_term: str) -> str | None:
parts: list[str] = []
for term in search_term.split("|"):
words = FULLTEXT_BOOLEAN_OPERATORS_REGEX.sub(" ", term).split()
if len(words) > 1:
parts.append('"' + " ".join(words) + '"')
return " ".join(parts) if parts else None
def _filter_by_search_term(self, query: Query, search_term: str):
terms = [term.strip() for term in search_term.split("|")]
terms = [term for term in terms if term]
if not terms:
return query
if ROMM_DB_DRIVER in ("mariadb", "mysql"):
match_clauses: list[Any] = []
for idx, term in enumerate(terms):
boolean_query = self._build_fulltext_boolean_query(term)
if boolean_query is None:
match_clauses = []
break
param = f"fulltext_search_{idx}"
match_clauses.append(
text(
f"MATCH(roms.name, roms.fs_name) "
f"AGAINST(:{param} IN BOOLEAN MODE)"
).bindparams(**{param: boolean_query})
)
if match_clauses:
return query.filter(or_(*match_clauses))
# psql and full-text fallback
term_conditions = []
for term in terms:
word_conditions = [
or_(Rom.fs_name.ilike(f"%{word}%"), Rom.name.ilike(f"%{word}%"))
for word in term.split()
]
if word_conditions:
term_conditions.append(and_(*word_conditions))
return query.filter(or_(*term_conditions))
def _filter_by_matched(self, query: Query, value: bool) -> Query:
"""Filter based on whether the rom is matched to a metadata provider.
Args:
value: True for matched ROMs, False for unmatched ROMs
"""
predicate = or_(
Rom.igdb_id.isnot(None),
Rom.moby_id.isnot(None),
Rom.ss_id.isnot(None),
Rom.ra_id.isnot(None),
Rom.launchbox_id.isnot(None),
Rom.hasheous_id.isnot(None),
Rom.tgdb_id.isnot(None),
Rom.flashpoint_id.isnot(None),
)
if not value:
predicate = not_(predicate)
return query.filter(predicate)
def _filter_by_favorite(
self, query: Query, session: Session, value: bool, user_id: int | None
) -> Query:
"""Filter based on whether the rom is in the user's favorites collection."""
if not user_id:
return query
from . import db_collection_handler
favorites_collection = db_collection_handler.get_favorite_collection(user_id)
if favorites_collection:
predicate = Rom.id.in_(favorites_collection.rom_ids)
if not value:
predicate = not_(predicate)
return query.filter(predicate)
# If no favorites collection exists, return the original query if non-favorites
# were requested, or an empty query if favorites were requested.
if not value:
return query
return query.filter(false())
def _filter_by_duplicate(self, query: Query, value: bool) -> Query:
"""Filter based on whether the rom has duplicates."""
predicate = Rom.sibling_roms.any()
if not value:
predicate = not_(predicate)
return query.filter(predicate)
def _filter_by_playable(self, query: Query, value: bool) -> Query:
"""Filter based on whether the rom is playable on supported platforms."""
predicate = or_(
Platform.slug.in_(EJS_SUPPORTED_PLATFORMS),
Platform.slug.in_(RUFFLE_SUPPORTED_PLATFORMS),
)
if not value:
predicate = not_(predicate)
return query.join(Platform).filter(predicate)
def _filter_by_last_played(
self, query: Query, value: bool, user_id: int | None = None
) -> Query:
"""Filter based on whether the rom has a last played value for the user."""
if not user_id:
return query
has_last_played = (
RomUser.last_played.is_(None)
if not value
else RomUser.last_played.isnot(None)
)
return query.filter(has_last_played)
def _filter_by_has_ra(self, query: Query, value: bool) -> Query:
predicate = Rom.ra_id.isnot(None)
if not value:
predicate = not_(predicate)
return query.filter(predicate)
def _filter_by_missing_from_fs(self, query: Query, value: bool) -> Query:
predicate = Rom.missing_from_fs.isnot(False)
if not value:
predicate = not_(predicate)
return query.filter(predicate)
def _filter_by_verified(self, query: Query, value: bool) -> Query:
keys_to_check = [
"tosec_match",
"mame_arcade_match",
"mame_mess_match",
"nointro_match",
"redump_match",
"whdload_match",
"ra_match",
"fbneo_match",
"puredos_match",
]
if ROMM_DB_DRIVER == "postgresql":
conditions = " OR ".join(
f"(hasheous_metadata->>'{key}')::boolean" for key in keys_to_check
)
predicate = text(f"({conditions})")
if not value:
predicate = text(f"NOT ({conditions})")
return query.filter(predicate)
else:
predicate = or_(
*(Rom.hasheous_metadata[key].as_boolean() for key in keys_to_check)
)
if not value:
predicate = not_(predicate)
return query.filter(predicate)
def _filter_by_genres(
self,
query: Query,
*,
session: Session,
values: Sequence[str],
match_all: bool = False,
match_none: bool = False,
) -> Query:
op = json_array_contains_all if match_all else json_array_contains_any
condition = op(RomMetadata.genres, values, session=session)
return query.filter(~condition) if match_none else query.filter(condition)
def _filter_by_franchises(
self,
query: Query,
*,
session: Session,
values: Sequence[str],
match_all: bool = False,
match_none: bool = False,
) -> Query:
op = json_array_contains_all if match_all else json_array_contains_any
condition = op(RomMetadata.franchises, values, session=session)
return query.filter(~condition) if match_none else query.filter(condition)
def _filter_by_collections(
self,
query: Query,
*,
session: Session,
values: Sequence[str],
match_all: bool = False,
match_none: bool = False,
) -> Query:
op = json_array_contains_all if match_all else json_array_contains_any
condition = op(RomMetadata.collections, values, session=session)
return query.filter(~condition) if match_none else query.filter(condition)
def _filter_by_companies(
self,
query: Query,
*,
session: Session,
values: Sequence[str],
match_all: bool = False,
match_none: bool = False,
) -> Query:
op = json_array_contains_all if match_all else json_array_contains_any
condition = op(RomMetadata.companies, values, session=session)
return query.filter(~condition) if match_none else query.filter(condition)
def _filter_by_age_ratings(
self,
query: Query,
*,
session: Session,
values: Sequence[str],
match_all: bool = False,
match_none: bool = False,
) -> Query:
op = json_array_contains_all if match_all else json_array_contains_any
condition = op(RomMetadata.age_ratings, values, session=session)
return query.filter(~condition) if match_none else query.filter(condition)
def _filter_by_status(
self,
query: Query,
*,
session: Session,
values: Sequence[str],
match_all: bool = False,
match_none: bool = False,
):
if not values:
return query
status_filters = []
for selected_status in values:
if selected_status == "now_playing":
status_filters.append(RomUser.now_playing.is_(True))
elif selected_status == "backlogged":
status_filters.append(RomUser.backlogged.is_(True))
elif selected_status == "hidden":
status_filters.append(RomUser.hidden.is_(True))
else:
status_filters.append(RomUser.status == selected_status)
comb = and_ if match_all else or_
condition = comb(*status_filters)
# Apply negation if match_none, otherwise apply condition
query = query.filter(~condition) if match_none else query.filter(condition)
# Don't apply the hidden filter is hidden is set
if "hidden" in values:
return query
return query.filter(or_(RomUser.hidden.is_(False), RomUser.hidden.is_(None)))
def _filter_by_regions(
self,
query: Query,
*,
session: Session,
values: Sequence[str],
match_all: bool = False,
match_none: bool = False,
) -> Query:
op = json_array_contains_all if match_all else json_array_contains_any
condition = op(Rom.regions, values, session=session)
return query.filter(~condition) if match_none else query.filter(condition)
def _filter_by_languages(
self,
query: Query,
*,
session: Session,
values: Sequence[str],
match_all: bool = False,
match_none: bool = False,
) -> Query:
op = json_array_contains_all if match_all else json_array_contains_any
condition = op(Rom.languages, values, session=session)
return query.filter(~condition) if match_none else query.filter(condition)
def _filter_by_player_counts(
self,
query: Query,
*,
session: Session,
values: Sequence[str],
match_all: bool = False,
match_none: bool = False,
) -> Query:
condition = RomMetadata.player_count.in_(values)
if match_none:
return query.filter(not_(condition))
return query.filter(condition)
@begin_session
def filter_roms(
self,
query: Query,
platform_ids: Sequence[int] | None = None,
collection_id: int | None = None,
virtual_collection_id: str | None = None,
smart_collection_id: int | None = None,
search_term: str | None = None,
matched: bool | None = None,
favorite: bool | None = None,
duplicate: bool | None = None,
last_played: bool | None = None,
playable: bool | None = None,
has_ra: bool | None = None,
missing: bool | None = None,
verified: bool | None = None,
group_by_meta_id: bool = False,
genres: Sequence[str] | None = None,
franchises: Sequence[str] | None = None,
collections: Sequence[str] | None = None,
companies: Sequence[str] | None = None,
age_ratings: Sequence[str] | None = None,
statuses: Sequence[str] | None = None,
regions: Sequence[str] | None = None,
languages: Sequence[str] | None = None,
player_counts: Sequence[str] | None = None,
# Logic operators for multi-value filters
genres_logic: str = "any",
franchises_logic: str = "any",
collections_logic: str = "any",
companies_logic: str = "any",
age_ratings_logic: str = "any",
regions_logic: str = "any",
languages_logic: str = "any",
statuses_logic: str = "any",
player_counts_logic: str = "any",
user_id: int | None = None,
updated_after: datetime | None = None,
include_file_stats: bool = False,
include_files: bool = False,
session: Session = None, # type: ignore
) -> Query[Rom]:
from handler.scan_handler import MetadataSource
query = query.options(
# Ensure platform is loaded for main ROM objects
selectinload(Rom.platform),
# Display properties for the current user (last_played)
selectinload(Rom.rom_users).options(noload(RomUser.rom)),
# Sort table by metadata (first_release_date)
selectinload(Rom.metadatum).options(noload(RomMetadata.rom)),
# Show sibling rom badges on cards
selectinload(Rom.sibling_roms).options(
noload(Rom.platform), noload(Rom.metadatum)
),
# Notes indicator on cards
selectinload(Rom.notes),
)
# Only load files (and the RomFile.rom backref needed by `is_top_level` /
# `file_name_for_download`) when the caller iterates them — e.g. the
# feed endpoints. The gallery/list and filter-value paths serialize
# SimpleRomSchema without files, so they skip this entirely.
if include_files:
query = query.options(
selectinload(Rom.files).options(
joinedload(RomFile.rom).load_only(Rom.fs_path, Rom.fs_name)
)
)
# Correlated subqueries and only undefer when the caller serializes the
# gallery-card flags. Feeds and filter-value lookups don't need them.
if include_file_stats:
query = query.options(
undefer(Rom.multi_file),
undefer(Rom.top_level_file_count),
undefer(Rom.has_manual_files),
undefer(Rom.has_soundtrack),
)
# Handle platform filtering - platform filtering always uses OR logic since ROMs belong to only one platform
if platform_ids:
query = self._filter_by_platform_ids(query, platform_ids)
if collection_id:
query = self._filter_by_collection_id(query, session, collection_id)
if virtual_collection_id:
query = self._filter_by_virtual_collection_id(
query, session, virtual_collection_id
)
if smart_collection_id and user_id:
query = self._filter_by_smart_collection_id(
query, session, smart_collection_id, user_id
)
if search_term:
query = self._filter_by_search_term(query, search_term)
if matched is not None:
query = self._filter_by_matched(query, value=matched)
if favorite is not None:
query = self._filter_by_favorite(
query, session=session, value=favorite, user_id=user_id
)
if duplicate is not None:
query = self._filter_by_duplicate(query, value=duplicate)
if last_played is not None:
query = self._filter_by_last_played(
query, value=last_played, user_id=user_id
)
if playable is not None:
query = self._filter_by_playable(query, value=playable)
if has_ra is not None:
query = self._filter_by_has_ra(query, value=has_ra)
if missing is not None:
query = self._filter_by_missing_from_fs(query, value=missing)
if verified is not None:
query = self._filter_by_verified(query, value=verified)
if updated_after:
query = query.filter(Rom.updated_at > updated_after)
# BEWARE YE WHO ENTERS HERE 💀
if group_by_meta_id:
# Convert NULL is_main_sibling to 0 (false) so it sorts after true values
is_main_sibling_order = (
func.coalesce(cast(RomUser.is_main_sibling, Integer), 0).desc()
if user_id
else literal(1)
)
# Create a subquery that identifies the primary ROM in each group
# Priority order: is_main_sibling (desc), then by fs_name_no_ext (asc)
base_subquery = query.subquery()
group_subquery = (
select(base_subquery.c.id)
.select_from(base_subquery)
.with_only_columns(
base_subquery.c.id,
base_subquery.c.fs_name_no_ext,
base_subquery.c.platform_id,
base_subquery.c.igdb_id,
base_subquery.c.ss_id,
base_subquery.c.moby_id,
base_subquery.c.ra_id,
base_subquery.c.hasheous_id,
base_subquery.c.launchbox_id,
base_subquery.c.tgdb_id,
base_subquery.c.flashpoint_id,
)
.outerjoin(
RomUser,
and_(
base_subquery.c.id == RomUser.rom_id, RomUser.user_id == user_id
),
)
.add_columns(
func.row_number()
.over(
partition_by=func.coalesce(
_create_metadata_id_case(
MetadataSource.IGDB,
base_subquery.c.igdb_id,
base_subquery.c.platform_id,
),
_create_metadata_id_case(
MetadataSource.SS,
base_subquery.c.ss_id,
base_subquery.c.platform_id,
),
_create_metadata_id_case(
MetadataSource.MOBY,
base_subquery.c.moby_id,
base_subquery.c.platform_id,
),
_create_metadata_id_case(
MetadataSource.RA,
base_subquery.c.ra_id,
base_subquery.c.platform_id,
),
_create_metadata_id_case(
MetadataSource.HASHEOUS,
base_subquery.c.hasheous_id,
base_subquery.c.platform_id,
),
_create_metadata_id_case(
MetadataSource.LAUNCHBOX,
base_subquery.c.launchbox_id,
base_subquery.c.platform_id,
),
_create_metadata_id_case(
MetadataSource.TGDB,
base_subquery.c.tgdb_id,
base_subquery.c.platform_id,
),
_create_metadata_id_case(
MetadataSource.FLASHPOINT,
base_subquery.c.flashpoint_id,
base_subquery.c.platform_id,
),
_create_metadata_id_case(
"romm",
base_subquery.c.id,
base_subquery.c.platform_id,
),
),
order_by=[
is_main_sibling_order,
base_subquery.c.fs_name_no_ext.asc(),
],
)
.label("row_num"),
)
.subquery()
)
# Add a filter to the original query to only include the primary ROM from each group
query = query.filter(
Rom.id.in_(
session.query(group_subquery.c.id).filter(
group_subquery.c.row_num == 1
)
)
)
# Optimize JOINs - only join tables when needed
needs_metadata_join = any(
[genres, franchises, collections, companies, age_ratings, player_counts]
)
if needs_metadata_join:
query = query.outerjoin(RomMetadata)
# Apply metadata and rom-level filters efficiently
filters_to_apply = [
(genres, genres_logic, self._filter_by_genres),
(franchises, franchises_logic, self._filter_by_franchises),
(collections, collections_logic, self._filter_by_collections),
(companies, companies_logic, self._filter_by_companies),
(age_ratings, age_ratings_logic, self._filter_by_age_ratings),
(regions, regions_logic, self._filter_by_regions),
(languages, languages_logic, self._filter_by_languages),
(player_counts, player_counts_logic, self._filter_by_player_counts),
]
for values, logic, filter_func in filters_to_apply:
if values:
query = filter_func(
query,
session=session,
values=values,
match_all=(logic == "all"),
match_none=(logic == "none"),
)
# The RomUser table is already joined if user_id is set
if statuses and user_id:
query = self._filter_by_status(
query,
session=session,
values=statuses,
match_all=(statuses_logic == "all"),
match_none=(statuses_logic == "none"),
)
elif user_id:
query = query.filter(
or_(RomUser.hidden.is_(False), RomUser.hidden.is_(None))
)
return query
@begin_session
def get_roms_query(
self,
*,
order_by: str = "",
order_dir: str = "asc",
search_term: str | None = None,
user_id: int | None = None,
session: Session = None, # type: ignore
) -> tuple[Query[Rom], Any]:
query = select(Rom)
if user_id:
query = query.outerjoin(
RomUser, and_(RomUser.rom_id == Rom.id, RomUser.user_id == user_id)
)