Home Assistant Unofficial Reference 2024.12.1
repack.py
Go to the documentation of this file.
1 """Purge repack helper."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import TYPE_CHECKING
7 
8 from sqlalchemy import text
9 
10 from .const import SupportedDialect
11 from .db_schema import ALL_TABLES
12 
13 if TYPE_CHECKING:
14  from . import Recorder
15 
16 _LOGGER = logging.getLogger(__name__)
17 
18 
19 def repack_database(instance: Recorder) -> None:
20  """Repack based on engine type."""
21  assert instance.engine is not None
22  dialect_name = instance.engine.dialect.name
23 
24  # Execute sqlite command to free up space on disk
25  if dialect_name == SupportedDialect.SQLITE:
26  _LOGGER.debug("Vacuuming SQL DB to free space")
27  with instance.engine.connect() as conn:
28  conn.execute(text("VACUUM"))
29  conn.commit()
30  return
31 
32  # Execute postgresql vacuum command to free up space on disk
33  if dialect_name == SupportedDialect.POSTGRESQL:
34  _LOGGER.debug("Vacuuming SQL DB to free space")
35  with instance.engine.connect().execution_options(
36  isolation_level="AUTOCOMMIT"
37  ) as conn:
38  conn.execute(text("VACUUM"))
39  conn.commit()
40  return
41 
42  # Optimize mysql / mariadb tables to free up space on disk
43  if dialect_name == SupportedDialect.MYSQL:
44  _LOGGER.debug("Optimizing SQL DB to free space")
45  with instance.engine.connect() as conn:
46  conn.execute(text(f"OPTIMIZE TABLE {','.join(ALL_TABLES)}"))
47  conn.commit()
48  return
None repack_database(Recorder instance)
Definition: repack.py:19