1#
2# Licensed to the Apache Software Foundation (ASF) under one
3# or more contributor license agreements. See the NOTICE file
4# distributed with this work for additional information
5# regarding copyright ownership. The ASF licenses this file
6# to you under the Apache License, Version 2.0 (the
7# "License"); you may not use this file except in compliance
8# with the License. You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing,
13# software distributed under the License is distributed on an
14# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15# KIND, either express or implied. See the License for the
16# specific language governing permissions and limitations
17# under the License.
18from __future__ import annotations
19
20from typing import TYPE_CHECKING
21
22import dill
23from sqlalchemy import BigInteger, Column, Integer, PickleType
24
25from airflow.models.base import Base
26from airflow.utils import timezone
27from airflow.utils.sqlalchemy import UtcDateTime
28
29if TYPE_CHECKING:
30 from airflow.models.dag import DAG
31
32
33class DagPickle(Base):
34 """
35 Represents a version of a DAG and becomes a source of truth for a BackfillJob execution.
36
37 Dags can originate from different places (user repos, main repo, ...) and also get executed
38 in different places (different executors). A pickle is a native python serialized object,
39 and in this case gets stored in the database for the duration of the job.
40
41 The executors pick up the DagPickle id and read the dag definition from the database.
42 """
43
44 id = Column(Integer, primary_key=True)
45 pickle = Column(PickleType(pickler=dill))
46 created_dttm = Column(UtcDateTime, default=timezone.utcnow)
47 pickle_hash = Column(BigInteger)
48
49 __tablename__ = "dag_pickle"
50
51 def __init__(self, dag: DAG) -> None:
52 self.dag_id = dag.dag_id
53 if hasattr(dag, "template_env"):
54 dag.template_env = None # type: ignore[attr-defined]
55 self.pickle_hash = hash(dag)
56 self.pickle = dag