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

should be straighforward
stored_datasets = {}
        for dataset in all_datasets:
            stored_dataset = session.query(DatasetModel).filter(DatasetModel.uri == dataset.uri).first()
            if stored_dataset:
                
                
                
                stored_dataset.is_orphaned = expression.false()
                stored_datasets[stored_dataset.uri] = stored_dataset
            else:
                session.add(dataset)
                stored_datasets[dataset.uri] = dataset
        session.flush()  
        del all_datasets
        
        for dag_id, uri_list in dag_references.items():
            dag_refs_needed = {
                DagScheduleDatasetReference(dataset_id=stored_datasets[uri].id, dag_id=dag_id)
                for uri in uri_list
            }
            dag_refs_stored = set(
                existing_dags.get(dag_id)
                and existing_dags.get(dag_id).schedule_dataset_references  
                or []
            )
            dag_refs_to_add = {x for x in dag_refs_needed if x not in dag_refs_stored}
            session.bulk_save_objects(dag_refs_to_add)
            for obj in dag_refs_stored - dag_refs_needed:
                session.delete(obj)