Ensure all mysql tables get optimized (#71538)

This commit is contained in:
J. Nick Koston 2022-05-08 14:15:06 -05:00 committed by GitHub
parent 2eaaa525f4
commit 6922209ddb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 14 additions and 18 deletions

View File

@ -61,12 +61,11 @@ TABLE_STATISTICS_META = "statistics_meta"
TABLE_STATISTICS_RUNS = "statistics_runs"
TABLE_STATISTICS_SHORT_TERM = "statistics_short_term"
# Only add TABLE_STATE_ATTRIBUTES and TABLE_EVENT_DATA
# to the below list once we want to check for their
# instance in the sanity check.
ALL_TABLES = [
TABLE_STATES,
TABLE_STATE_ATTRIBUTES,
TABLE_EVENTS,
TABLE_EVENT_DATA,
TABLE_RECORDER_RUNS,
TABLE_SCHEMA_CHANGES,
TABLE_STATISTICS,
@ -75,6 +74,14 @@ ALL_TABLES = [
TABLE_STATISTICS_SHORT_TERM,
]
TABLES_TO_CHECK = [
TABLE_STATES,
TABLE_EVENTS,
TABLE_RECORDER_RUNS,
TABLE_SCHEMA_CHANGES,
]
EMPTY_JSON_OBJECT = "{}"

View File

@ -7,6 +7,7 @@ from typing import TYPE_CHECKING
from sqlalchemy import text
from .const import SupportedDialect
from .models import ALL_TABLES
if TYPE_CHECKING:
from . import Recorder
@ -41,6 +42,6 @@ def repack_database(instance: Recorder) -> None:
if dialect_name == SupportedDialect.MYSQL:
_LOGGER.debug("Optimizing SQL DB to free space")
with instance.engine.connect() as conn:
conn.execute(text("OPTIMIZE TABLE states, events, recorder_runs"))
conn.execute(text(f"OPTIMIZE TABLE {','.join(ALL_TABLES)}"))
conn.commit()
return

View File

@ -27,13 +27,9 @@ import homeassistant.util.dt as dt_util
from .const import DATA_INSTANCE, SQLITE_URL_PREFIX, SupportedDialect
from .models import (
ALL_TABLES,
TABLE_RECORDER_RUNS,
TABLE_SCHEMA_CHANGES,
TABLE_STATISTICS,
TABLE_STATISTICS_META,
TABLE_STATISTICS_RUNS,
TABLE_STATISTICS_SHORT_TERM,
TABLES_TO_CHECK,
RecorderRuns,
process_timestamp,
)
@ -213,15 +209,7 @@ def last_run_was_recently_clean(cursor: CursorFetchStrategy) -> bool:
def basic_sanity_check(cursor: CursorFetchStrategy) -> bool:
"""Check tables to make sure select does not fail."""
for table in ALL_TABLES:
# The statistics tables may not be present in old databases
if table in [
TABLE_STATISTICS,
TABLE_STATISTICS_META,
TABLE_STATISTICS_RUNS,
TABLE_STATISTICS_SHORT_TERM,
]:
continue
for table in TABLES_TO_CHECK:
if table in (TABLE_RECORDER_RUNS, TABLE_SCHEMA_CHANGES):
cursor.execute(f"SELECT * FROM {table};") # nosec # not injection
else: