From 8a1931601d3b105ad585ef39840c8251ebdb44a2 Mon Sep 17 00:00:00 2001 From: Mike Bayer Date: Fri, 21 Jan 2022 10:19:02 -0500 Subject: Skip PK returned as None for RETURNING, server side default Fixed regression where the ORM exception that is to be raised when an INSERT silently fails to actually insert a row (such as from a trigger) would not be reached, due to a runtime exception raised ahead of time due to the missing primary key value, thus raising an uninformative exception rather than the correct one. For 1.4 and above, a new ``FlushError`` is added for this case that's raised earlier than the previous "null identity" exception was for 1.3, as a situation where the number of rows actually INSERTed does not match what was expected is a more critical situation in 1.4 as it prevents batching of multiple objects from working correctly. This is separate from the case where a newly fetched primary key is fetched as NULL, which continues to raise the existing "null identity" exception. Fixes: #7594 Change-Id: Ie8e181e3472f09f389cca757c5e58e61b15c7d79 --- lib/sqlalchemy/orm/persistence.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) (limited to 'lib/sqlalchemy') diff --git a/lib/sqlalchemy/orm/persistence.py b/lib/sqlalchemy/orm/persistence.py index 6696b34d5..b3381b039 100644 --- a/lib/sqlalchemy/orm/persistence.py +++ b/lib/sqlalchemy/orm/persistence.py @@ -1177,6 +1177,22 @@ def _emit_insert_statements( c.inserted_primary_key_rows, c.returned_defaults_rows or (), ): + if inserted_primary_key is None: + # this is a real problem and means that we didn't + # get back as many PK rows. we can't continue + # since this indicates PK rows were missing, which + # means we likely mis-populated records starting + # at that point with incorrectly matched PK + # values. + raise orm_exc.FlushError( + "Multi-row INSERT statement for %s did not " + "produce " + "the correct number of INSERTed rows for " + "RETURNING. Ensure there are no triggers or " + "special driver issues preventing INSERT from " + "functioning properly." % mapper_rec + ) + for pk, col in zip( inserted_primary_key, mapper._pks_by_table[table], @@ -1225,6 +1241,15 @@ def _emit_insert_statements( ) primary_key = result.inserted_primary_key + if primary_key is None: + raise orm_exc.FlushError( + "Single-row INSERT statement for %s " + "did not produce a " + "new primary key result " + "being invoked. Ensure there are no triggers or " + "special driver issues preventing INSERT from " + "functioning properly." % (mapper_rec,) + ) for pk, col in zip( primary_key, mapper._pks_by_table[table] ): -- cgit v1.2.1