manipatnam commented on code in PR #63874:
URL: https://github.com/apache/airflow/pull/63874#discussion_r3338597053
##########
airflow-core/src/airflow/models/renderedtifields.py:
##########
@@ -239,13 +242,62 @@ def get_k8s_pod_yaml(cls, ti: TaskInstance, session:
Session = NEW_SESSION) -> d
@provide_session
@retry_db_transaction
- def write(self, session: Session):
+ def write(self, session: Session = NEW_SESSION):
"""
Write instance to database.
+ Uses a database-level upsert (INSERT ... ON CONFLICT DO UPDATE) to
+ atomically insert or update the record, avoiding race conditions that
+ can occur with session.merge() when concurrent requests (e.g. from
+ client-side timeout retries) target the same primary key.
+
:param session: SqlAlchemy Session
"""
- session.merge(self)
+ dialect_name = get_dialect_name(session)
+
+ values = {
+ "dag_id": self.dag_id,
+ "task_id": self.task_id,
+ "run_id": self.run_id,
+ "map_index": self.map_index,
+ "rendered_fields": self.rendered_fields,
+ "k8s_pod_yaml": self.k8s_pod_yaml,
+ }
+ update_on_conflict = {
+ "rendered_fields": self.rendered_fields,
+ "k8s_pod_yaml": self.k8s_pod_yaml,
+ }
+
+ stmt: MySQLInsert | PostgreSQLInsert | SQLiteInsert
+
+ if dialect_name == "postgresql":
Review Comment:
Done. Extracted a shared `build_upsert_stmt(dialect, model, conflict_cols,
values, update_fields)` helper next to `get_dialect_name` in
`utils/sqlalchemy.py` and pointed both `variable.py` and `renderedtifields.py`
at it. The duplicated `MySQLInsert/PostgreSQLInsert/SQLiteInsert`
`TYPE_CHECKING `imports are gone from both models now.
The shared helper uses this PR's strict `else: raise ValueError` rather than
the old silent SQLite fallthrough, so `variable.py`'s upsert is now strict on
unknown dialects as well.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]