Used in https://github.com/mhenc/airflow/blob/master/airflow/dag_processing/manager.py#L613

should be straighforward
"""
        Return (and lock) a list of Dag objects that are due to create a new DagRun.
        This will return a resultset of rows that is row-level-locked with a "SELECT ... FOR UPDATE" query,
        you should ensure that any scheduling decisions are made in a single transaction -- as soon as the
        transaction is committed it will be unlocked.
        """
        from airflow.models.dataset import DagScheduleDatasetReference, DatasetDagRunQueue as DDRQ
        
        dataset_triggered_dag_info = {
            x.dag_id: (x.first_queued_time, x.last_queued_time)
            for x in session.query(
                DagScheduleDatasetReference.dag_id,
                func.max(DDRQ.created_at).label("last_queued_time"),
                func.min(DDRQ.created_at).label("first_queued_time"),
            )
            .join(DagScheduleDatasetReference.queue_records, isouter=True)
            .group_by(DagScheduleDatasetReference.dag_id)
            .having(func.count() == func.sum(case((DDRQ.target_dag_id.is_not(None), 1), else_=0)))
            .all()
        }
        dataset_triggered_dag_ids = set(dataset_triggered_dag_info.keys())
        if dataset_triggered_dag_ids:
            exclusion_list = {
                x.dag_id
                for x in (
                    session.query(DagModel.dag_id)
                    .join(DagRun.dag_model)
                    .filter(DagRun.state.in_((DagRunState.QUEUED, DagRunState.RUNNING)))
                    .filter(DagModel.dag_id.in_(dataset_triggered_dag_ids))