Home Assistant Unofficial Reference 2024.12.1
schema.py
Go to the documentation of this file.
1 """Statistics schema repairs."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import TYPE_CHECKING
7 
8 from ...db_schema import Statistics, StatisticsMeta, StatisticsShortTerm
9 from ..schema import (
10  correct_db_schema_precision,
11  correct_db_schema_utf8,
12  validate_db_schema_precision,
13  validate_table_schema_has_correct_collation,
14  validate_table_schema_supports_utf8,
15 )
16 
17 if TYPE_CHECKING:
18  from ... import Recorder
19 
20 _LOGGER = logging.getLogger(__name__)
21 
22 
23 def validate_db_schema(instance: Recorder) -> set[str]:
24  """Do some basic checks for common schema errors caused by manual migration."""
25  schema_errors: set[str] = set()
26  schema_errors |= validate_table_schema_supports_utf8(
27  instance, StatisticsMeta, (StatisticsMeta.statistic_id,)
28  )
29  for table in (Statistics, StatisticsShortTerm):
30  schema_errors |= validate_db_schema_precision(instance, table)
31  schema_errors |= validate_table_schema_has_correct_collation(instance, table)
32  if schema_errors:
33  _LOGGER.debug(
34  "Detected statistics schema errors: %s", ", ".join(sorted(schema_errors))
35  )
36  return schema_errors
37 
38 
40  instance: Recorder,
41  schema_errors: set[str],
42 ) -> None:
43  """Correct issues detected by validate_db_schema."""
44  correct_db_schema_utf8(instance, StatisticsMeta, schema_errors)
45  for table in (Statistics, StatisticsShortTerm):
46  correct_db_schema_precision(instance, table, schema_errors)
47  correct_db_schema_utf8(instance, table, schema_errors)
None correct_db_schema_precision(Recorder instance, type[DeclarativeBase] table_object, set[str] schema_errors)
Definition: schema.py:256
set[str] validate_table_schema_has_correct_collation(Recorder instance, type[DeclarativeBase] table_object)
Definition: schema.py:68
None correct_db_schema_utf8(Recorder instance, type[DeclarativeBase] table_object, set[str] schema_errors)
Definition: schema.py:238
set[str] validate_db_schema_precision(Recorder instance, type[DeclarativeBase] table_object)
Definition: schema.py:150
set[str] validate_table_schema_supports_utf8(Recorder instance, type[DeclarativeBase] table_object, tuple[InstrumentedAttribute,...] columns)
Definition: schema.py:47
None correct_db_schema(Recorder instance, set[str] schema_errors)
Definition: schema.py:42