anitakar commented on a change in pull request #7217: [AIRFLOW-5946] Store 
source code in db
URL: https://github.com/apache/airflow/pull/7217#discussion_r383986936
 
 

 ##########
 File path: airflow/models/dagcode.py
 ##########
 @@ -0,0 +1,108 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+import logging
+from typing import List
+
+from sqlalchemy import Column, Index, Integer, String, Text, and_
+
+from airflow.models import Base
+from airflow.utils import timezone
+from airflow.utils.session import provide_session
+from airflow.utils.sqlalchemy import UtcDateTime
+
+log = logging.getLogger(__name__)
+
+
+class DagCodeModel(Base):
+    """A table for DAGs code.
+
+    dag_code table contains code of DAG files synchronized by scheduler.
+    This feature is controlled by:
+
+    * ``[core] store_serialized_dags = True``: enable this feature
+    * ``[core] store_code = True``: enable this feature
+
+    For details on dag serialization see SerializedDagModel
+    """
+    __tablename__ = 'dag_code'
+
+    fileloc = Column(String(2000), primary_key=True)
+    # The max length of fileloc exceeds the limit of indexing.
+    fileloc_hash = Column(Integer, primary_key=True)
+    last_updated = Column(UtcDateTime, nullable=False)
+    source_code = Column(Text(), nullable=False)
+
+    __table_args__ = (
+        Index('idx_fileloc_code_hash', fileloc_hash, unique=False),
+    )
+
+    def __init__(self, full_filepath: str):
+        self.fileloc = full_filepath
+        self.fileloc_hash = DagCodeModel.dag_fileloc_hash(self.fileloc)
+        self.last_updated = timezone.utcnow()
+        self.source_code = DagCodeModel._read_code(self.fileloc)
+
+    @classmethod
+    def _read_code(cls, fileloc: str):
+        try:
+            with open(fileloc, 'r') as source:
+                source_code = source.read()
+        except IOError:
+            source_code = "Couldn't read source file {}.".format(fileloc)
+        return source_code
+
+    @provide_session
+    def write_code(self, session=None):
+        """Writes code into database.
+
+        :param session: ORM Session
+        """
+        session.merge(self)
+
+    @classmethod
+    @provide_session
+    def remove_deleted_code(cls, alive_dag_filelocs: List[str], session=None):
+        """Deletes code not included in alive_dag_filelocs.
+
+        :param alive_dag_filelocs: file paths of alive DAGs
+        :param session: ORM Session
+        """
+        alive_fileloc_hashes = [
+            cls.dag_fileloc_hash(fileloc) for fileloc in alive_dag_filelocs]
+
+        log.debug("Deleting code from %s table ", cls.__tablename__)
+
+        session.execute(
+            cls.__table__.delete().where(
+                and_(cls.fileloc_hash.notin_(alive_fileloc_hashes),
+                     cls.fileloc.notin_(alive_dag_filelocs))))
+
+    @classmethod
+    def dag_fileloc_hash(cls, full_filepath: str) -> int:
+        """"Hashing file location for indexing.
+
+        :param full_filepath: full filepath of DAG file
+        :return: hashed full_filepath
+        """
+        # hashing is needed because the length of fileloc is 2000 as an 
Airflow convention,
+        # which is over the limit of indexing. If we can reduce the length of 
fileloc, then
+        # hashing is not needed.
+        import hashlib
+        return int.from_bytes(
+            hashlib.sha1(
+                full_filepath.encode('utf-8')).digest()[-2:],
+            byteorder='big', signed=False)
 
 Review comment:
   I agree. I shall create this migration

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services

Reply via email to