From e40a373c4b25e385c1beefa2973f2228862e3c5c Mon Sep 17 00:00:00 2001
From: "J. Nick Koston" <nick@koston.org>
Date: Tue, 11 Apr 2023 16:39:19 -1000
Subject: [PATCH] Call sqlite pragma optimize during periodic cleanup task
 (#91245)

https://www.sqlite.org/pragma.html#pragma_optimize

> To achieve the best long-term query performance without the need to do a detailed engineering analysis of the application schema and SQL, it is recommended that applications run "PRAGMA optimize" (with no arguments) just before closing each database connection. Long-running applications might also benefit from setting a timer to run "PRAGMA optimize" every few hours.

> This pragma is usually a no-op or nearly so and is very fast.

Since we keep the recorder connection open for the entire time HA
is running we fall into the long-running application bucket
---
 homeassistant/components/recorder/util.py | 1 +
 1 file changed, 1 insertion(+)

diff --git a/homeassistant/components/recorder/util.py b/homeassistant/components/recorder/util.py
index 04b1f43bc1b..5e0fb8b59d6 100644
--- a/homeassistant/components/recorder/util.py
+++ b/homeassistant/components/recorder/util.py
@@ -673,6 +673,7 @@ def periodic_db_cleanups(instance: Recorder) -> None:
         _LOGGER.debug("WAL checkpoint")
         with instance.engine.connect() as connection:
             connection.execute(text("PRAGMA wal_checkpoint(TRUNCATE);"))
+            connection.execute(text("PRAGMA OPTIMIZE;"))
 
 
 @contextmanager
-- 
GitLab