uranusjr commented on code in PR #33242:
URL: https://github.com/apache/airflow/pull/33242#discussion_r1293050158


##########
airflow/models/dag.py:
##########
@@ -2925,21 +2925,44 @@ def bulk_write_to_db(
         # Skip these queries entirely if no DAGs can be scheduled to save time.
         if any(dag.timetable.can_be_scheduled for dag in dags):
             # Get the latest dag run for each existing dag as a single query 
(avoid n+1 query)
-            most_recent_subq = (
-                select(DagRun.dag_id, 
func.max(DagRun.execution_date).label("max_execution_date"))
-                .where(
-                    DagRun.dag_id.in_(existing_dags),
-                    or_(DagRun.run_type == DagRunType.BACKFILL_JOB, 
DagRun.run_type == DagRunType.SCHEDULED),
+            if len(existing_dags) == 1:
+                # Index optimized fast path to avoid more complicated & slower 
groupby queryplan
+                most_recent_subq = (
+                    
select(func.max(DagRun.execution_date).label("max_execution_date"))
+                    .where(
+                        DagRun.dag_id == existing_dags[0],
+                        or_(
+                            DagRun.run_type == DagRunType.BACKFILL_JOB,
+                            DagRun.run_type == DagRunType.SCHEDULED,
+                        ),
+                    )
+                    .subquery()
                 )
-                .group_by(DagRun.dag_id)
-                .subquery()
-            )
-            most_recent_runs_iter = session.scalars(
-                select(DagRun).where(
-                    DagRun.dag_id == most_recent_subq.c.dag_id,
-                    DagRun.execution_date == 
most_recent_subq.c.max_execution_date,
+                most_recent_runs_iter = session.scalars(
+                    select(DagRun).where(
+                        DagRun.dag_id == existing_dags[0],

Review Comment:
   Would the optimization work if we use `DagRun.dag_id == 
most_recent_subq.c.dag_id` for both cases? If so we can reduce the code a lot.



-- 
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]

Reply via email to