dstandish commented on a change in pull request #20838:
URL: https://github.com/apache/airflow/pull/20838#discussion_r812430460



##########
File path: airflow/utils/db_cleanup.py
##########
@@ -0,0 +1,307 @@
+# 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 contextlib import AbstractContextManager
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
+
+from pendulum import DateTime
+from sqlalchemy import and_, false, func
+from sqlalchemy.exc import OperationalError
+
+from airflow.cli.simple_table import AirflowConsole
+from airflow.jobs.base_job import BaseJob
+from airflow.models import (
+    Base,
+    DagModel,
+    DagRun,
+    ImportError,
+    Log,
+    RenderedTaskInstanceFields,
+    SlaMiss,
+    TaskFail,
+    TaskInstance,
+    TaskReschedule,
+    XCom,
+)
+from airflow.utils import timezone
+from airflow.utils.session import NEW_SESSION, provide_session
+
+if TYPE_CHECKING:
+    from sqlalchemy.orm import Query, Session
+    from sqlalchemy.orm.attributes import InstrumentedAttribute
+    from sqlalchemy.sql.schema import Column
+
+
+@dataclass
+class _TableConfig:
+    """
+    Config class for performing cleanup on a table
+
+    :param orm_model: the table
+    :param recency_column: date column to filter by
+    :param keep_last: whether the last record should be kept even if it's 
older than clean_before_timestamp
+    :param keep_last_filters: the "keep last" functionality will preserve the 
most recent record
+        in the table.  to ignore certain records even if they are the latest 
in the table, you can
+        supply additional filters here (e.g. externally triggered dag runs)
+    :param keep_last_group_by: if keeping the last record, can keep the last 
record for each group
+    :param warn_if_missing: If True, then we'll suppress "table missing" 
exception and log a warning.
+        If False then the exception will go uncaught.
+    """
+
+    orm_model: Base
+    recency_column: Union["Column", "InstrumentedAttribute"]
+    keep_last: bool = False
+    keep_last_filters: Optional[Any] = None
+    keep_last_group_by: Optional[Any] = None
+    warn_if_missing: bool = False
+
+    def __lt__(self, other):
+        return self.orm_model.__tablename__ < self.orm_model.__tablename__
+
+    @property
+    def readable_config(self):
+        return dict(
+            table=self.orm_model.__tablename__,
+            recency_column=str(self.recency_column),
+            keep_last=self.keep_last,
+            keep_last_filters=[str(x) for x in self.keep_last_filters] if 
self.keep_last_filters else None,
+            keep_last_group_by=str(self.keep_last_group_by),
+            warn_if_missing=str(self.warn_if_missing),
+        )
+
+
+config_list: List[_TableConfig] = [
+    _TableConfig(orm_model=BaseJob, recency_column=BaseJob.latest_heartbeat),
+    _TableConfig(orm_model=DagModel, recency_column=DagModel.last_parsed_time),
+    _TableConfig(
+        orm_model=DagRun,
+        recency_column=DagRun.start_date,
+        keep_last=True,
+        keep_last_filters=[DagRun.external_trigger == false()],
+        keep_last_group_by=DagRun.dag_id,
+    ),
+    _TableConfig(orm_model=ImportError, recency_column=ImportError.timestamp),
+    _TableConfig(orm_model=Log, recency_column=Log.dttm),
+    _TableConfig(
+        orm_model=RenderedTaskInstanceFields, 
recency_column=RenderedTaskInstanceFields.execution_date
+    ),
+    _TableConfig(orm_model=SlaMiss, recency_column=SlaMiss.timestamp),
+    _TableConfig(orm_model=TaskFail, recency_column=TaskFail.start_date),
+    _TableConfig(orm_model=TaskInstance, 
recency_column=TaskInstance.start_date),
+    _TableConfig(orm_model=TaskReschedule, 
recency_column=TaskReschedule.start_date),
+    _TableConfig(orm_model=XCom, recency_column=XCom.timestamp),
+]
+try:
+    from celery.backends.database.models import Task, TaskSet
+
+    config_list.extend(
+        [
+            _TableConfig(orm_model=Task, recency_column=Task.date_done, 
warn_if_missing=True),
+            _TableConfig(orm_model=TaskSet, recency_column=TaskSet.date_done, 
warn_if_missing=True),
+        ]
+    )
+except ImportError:
+    pass
+
+config_dict: Dict[str, _TableConfig] = {x.orm_model.__tablename__: x for x in 
sorted(config_list)}

Review comment:
       maybe "need" is a bit strong.  But, i think the intention is, that for 
user experience, it's best when the table outputs are sorted.  So e.g. when you 
are reviewing a list of tables, if perhaps you're scanning for one, if it's 
sorted, it will be easier to find.  And, since we only add the celery models 
when they are there to add, we can't just build the list already  completely 
sorted.  Or we could i guess but the code would be slightly messier.  WDYT?




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