Skip to content

Commit 556e1e3

Browse files
authored
refactor(packaging): Use SQLAlchemy event for Filename registry (Fixes #576) (#18934)
* refactor(packaging): Use SQLAlchemy event for Filename registry (Fixes #576) * refactor(packaging): Use SQLAlchemy event for Filename registry (Fixes #576) * refactor(packaging): Use SQLAlchemy event for Filename registry (Fixes #576)
1 parent 6ff631b commit 556e1e3

File tree

2 files changed

+18
-5
lines changed

2 files changed

+18
-5
lines changed

warehouse/forklift/legacy.py

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1516,11 +1516,6 @@ def file_upload(request):
15161516
f"Invalid attestations supplied during upload: {e}",
15171517
)
15181518

1519-
# TODO: This should be handled by some sort of database trigger or a
1520-
# SQLAlchemy hook or the like instead of doing it inline in this
1521-
# view.
1522-
request.db.add(Filename(filename=filename))
1523-
15241519
# Store the information about the file in the database.
15251520
file_ = File(
15261521
release=release,

warehouse/packaging/models.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
Text,
2626
UniqueConstraint,
2727
cast,
28+
event,
2829
func,
2930
or_,
3031
orm,
@@ -1215,3 +1216,20 @@ class AlternateRepository(db.Model):
12151216
name: Mapped[str]
12161217
url: Mapped[str]
12171218
description: Mapped[str]
1219+
1220+
1221+
@event.listens_for(File, "after_insert")
1222+
def add_filename_to_registry(mapper, connection, target):
1223+
"""
1224+
Log the new filename to the Filename (file_registry) table.
1225+
1226+
This event listener is triggered *after* a new `File` object is
1227+
successfully inserted into the database.
1228+
1229+
We use a direct connection-level insert (`connection.execute()`)
1230+
instead of `session.add(Filename(...))` to avoid an `SAWarning`.
1231+
Modifying the session *during* the flush process (which is when
1232+
this hook runs) is not a supported operation. This method
1233+
bypasses the session's unit-of-work tracking and is safe here.
1234+
"""
1235+
connection.execute(Filename.__table__.insert(), {"filename": target.filename})

0 commit comments

Comments
 (0)