Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Allow auto pruning of the query table #29936

Merged
merged 4 commits into from
Aug 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 109 additions & 0 deletions superset/commands/sql_lab/query.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
# 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
import time
from datetime import datetime, timedelta

import sqlalchemy as sa

from superset import db
from superset.commands.base import BaseCommand
from superset.models.sql_lab import Query

logger = logging.getLogger(__name__)


# pylint: disable=consider-using-transaction
class QueryPruneCommand(BaseCommand):
"""
Command to prune the query table by deleting rows older than the specified retention period.

This command deletes records from the `Query` table that have not been changed within the
specified number of days. It helps in maintaining the database by removing outdated entries
and freeing up space.

Attributes:
retention_period_days (int): The number of days for which records should be retained.
Records older than this period will be deleted.
"""

def __init__(self, retention_period_days: int):
"""
:param retention_period_days: Number of days to keep in the query table
"""
self.retention_period_days = retention_period_days

Check warning on line 48 in superset/commands/sql_lab/query.py

View check run for this annotation

Codecov / codecov/patch

superset/commands/sql_lab/query.py#L48

Added line #L48 was not covered by tests

def run(self) -> None:
"""
Executes the prune command
"""
batch_size = 999 # SQLite has a IN clause limit of 999
total_deleted = 0
start_time = time.time()

Check warning on line 56 in superset/commands/sql_lab/query.py

View check run for this annotation

Codecov / codecov/patch

superset/commands/sql_lab/query.py#L54-L56

Added lines #L54 - L56 were not covered by tests

# Select all IDs that need to be deleted
ids_to_delete = (

Check warning on line 59 in superset/commands/sql_lab/query.py

View check run for this annotation

Codecov / codecov/patch

superset/commands/sql_lab/query.py#L59

Added line #L59 was not covered by tests
db.session.execute(
sa.select(Query.id).where(
Query.changed_on
< datetime.now() - timedelta(days=self.retention_period_days)
)
)
.scalars()
.all()
)

total_rows = len(ids_to_delete)

Check warning on line 70 in superset/commands/sql_lab/query.py

View check run for this annotation

Codecov / codecov/patch

superset/commands/sql_lab/query.py#L70

Added line #L70 was not covered by tests

logger.info("Total rows to be deleted: %s", total_rows)

Check warning on line 72 in superset/commands/sql_lab/query.py

View check run for this annotation

Codecov / codecov/patch

superset/commands/sql_lab/query.py#L72

Added line #L72 was not covered by tests

next_logging_threshold = 1

Check warning on line 74 in superset/commands/sql_lab/query.py

View check run for this annotation

Codecov / codecov/patch

superset/commands/sql_lab/query.py#L74

Added line #L74 was not covered by tests

# Iterate over the IDs in batches
for i in range(0, total_rows, batch_size):
batch_ids = ids_to_delete[i : i + batch_size]

Check warning on line 78 in superset/commands/sql_lab/query.py

View check run for this annotation

Codecov / codecov/patch

superset/commands/sql_lab/query.py#L77-L78

Added lines #L77 - L78 were not covered by tests

# Delete the selected batch using IN clause
result = db.session.execute(sa.delete(Query).where(Query.id.in_(batch_ids)))

Check warning on line 81 in superset/commands/sql_lab/query.py

View check run for this annotation

Codecov / codecov/patch

superset/commands/sql_lab/query.py#L81

Added line #L81 was not covered by tests

# Update the total number of deleted records
total_deleted += result.rowcount

Check warning on line 84 in superset/commands/sql_lab/query.py

View check run for this annotation

Codecov / codecov/patch

superset/commands/sql_lab/query.py#L84

Added line #L84 was not covered by tests

# Explicitly commit the transaction given that if an error occurs, we want to ensure that the
# records that have been deleted so far are committed
db.session.commit()

Check warning on line 88 in superset/commands/sql_lab/query.py

View check run for this annotation

Codecov / codecov/patch

superset/commands/sql_lab/query.py#L88

Added line #L88 was not covered by tests

# Log the number of deleted records every 1% increase in progress
percentage_complete = (total_deleted / total_rows) * 100
if percentage_complete >= next_logging_threshold:
logger.info(

Check warning on line 93 in superset/commands/sql_lab/query.py

View check run for this annotation

Codecov / codecov/patch

superset/commands/sql_lab/query.py#L91-L93

Added lines #L91 - L93 were not covered by tests
"Deleted %s rows from the query table older than %s days (%d%% complete)",
total_deleted,
self.retention_period_days,
percentage_complete,
)
next_logging_threshold += 1

Check warning on line 99 in superset/commands/sql_lab/query.py

View check run for this annotation

Codecov / codecov/patch

superset/commands/sql_lab/query.py#L99

Added line #L99 was not covered by tests

elapsed_time = time.time() - start_time
minutes, seconds = divmod(elapsed_time, 60)
formatted_time = f"{int(minutes):02}:{int(seconds):02}"
logger.info(

Check warning on line 104 in superset/commands/sql_lab/query.py

View check run for this annotation

Codecov / codecov/patch

superset/commands/sql_lab/query.py#L101-L104

Added lines #L101 - L104 were not covered by tests
"Pruning complete: %s rows deleted in %s", total_deleted, formatted_time
)

def validate(self) -> None:
pass

Check warning on line 109 in superset/commands/sql_lab/query.py

View check run for this annotation

Codecov / codecov/patch

superset/commands/sql_lab/query.py#L109

Added line #L109 was not covered by tests
6 changes: 6 additions & 0 deletions superset/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -999,6 +999,12 @@ class CeleryConfig: # pylint: disable=too-few-public-methods
"task": "reports.prune_log",
"schedule": crontab(minute=0, hour=0),
},
# Uncomment to enable pruning of the query table
# "prune_query": {
# "task": "prune_query",
# "schedule": crontab(minute=0, hour=0, day_of_month=1),
# "options": {"retention_period_days": 180},
# },
}


Expand Down
14 changes: 14 additions & 0 deletions superset/tasks/scheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
from superset.commands.report.exceptions import ReportScheduleUnexpectedError
from superset.commands.report.execute import AsyncExecuteReportScheduleCommand
from superset.commands.report.log_prune import AsyncPruneReportScheduleLogCommand
from superset.commands.sql_lab.query import QueryPruneCommand
from superset.daos.report import ReportScheduleDAO
from superset.extensions import celery_app
from superset.stats_logger import BaseStatsLogger
Expand Down Expand Up @@ -119,3 +120,16 @@
logger.warning("A timeout occurred while pruning report schedule logs: %s", ex)
except CommandException:
logger.exception("An exception occurred while pruning report schedule logs")


@celery_app.task(name="prune_query")
def prune_query() -> None:
stats_logger: BaseStatsLogger = app.config["STATS_LOGGER"]
stats_logger.incr("prune_query")

Check warning on line 128 in superset/tasks/scheduler.py

View check run for this annotation

Codecov / codecov/patch

superset/tasks/scheduler.py#L127-L128

Added lines #L127 - L128 were not covered by tests

try:
QueryPruneCommand(

Check warning on line 131 in superset/tasks/scheduler.py

View check run for this annotation

Codecov / codecov/patch

superset/tasks/scheduler.py#L130-L131

Added lines #L130 - L131 were not covered by tests
prune_query.request.properties.get("retention_period_days")
).run()
except CommandException as ex:
logger.exception("An error occurred while pruning queries: %s", ex)

Check warning on line 135 in superset/tasks/scheduler.py

View check run for this annotation

Codecov / codecov/patch

superset/tasks/scheduler.py#L134-L135

Added lines #L134 - L135 were not covered by tests
Loading