Skip to main content

kanban_persistence_sqlite/sqlite_store/
metadata.rs

1use chrono::{DateTime, Utc};
2use kanban_domain::{KanbanError, KanbanResult};
3use kanban_persistence::PersistenceMetadata;
4
5use super::helpers::{db_err, p_dt, p_uuid, run};
6use super::{MetadataRow, SqliteStore};
7
8impl SqliteStore {
9    /// Read the metadata singleton row from the DB. Cheap (single row, indexed by primary key).
10    /// Returns `Ok(None)` if the row is absent — only possible on a brand-new DB
11    /// before `load_or_create_instance_id` has run, which the public API doesn't expose.
12    pub fn read_metadata_sync(&self) -> KanbanResult<Option<PersistenceMetadata>> {
13        run(async {
14            let row: Option<MetadataRow> = sqlx::query_as(
15                "SELECT instance_id, saved_at, writer_version, writer_commit, schema_version \
16                 FROM metadata WHERE id = 1",
17            )
18            .fetch_optional(&self.pool)
19            .await
20            .map_err(db_err)?;
21            let Some(row) = row else {
22                return Ok(None);
23            };
24            let instance_id = p_uuid(&row.0)?;
25            let saved_at = p_dt(&row.1)?;
26            Ok(Some(PersistenceMetadata {
27                instance_id,
28                saved_at,
29                writer_version: row.2,
30                writer_commit: row.3,
31                format_version: Some(row.4),
32            }))
33        })
34    }
35
36    /// Record the current binary as the most-recent writer of this DB by
37    /// stamping `saved_at`, `writer_version`, and `writer_commit` into the
38    /// metadata singleton row. Returns the timestamp it wrote so callers can
39    /// echo it back into a `PersistenceMetadata` without re-reading the row.
40    ///
41    /// Separated from [`checkpoint`] so each function does one thing — see
42    /// the post-PR-288 review for the SRP rationale.
43    pub async fn stamp_writer(&self) -> KanbanResult<DateTime<Utc>> {
44        let now = Utc::now();
45        sqlx::query(
46            "UPDATE metadata SET saved_at = ?, writer_version = ?, writer_commit = ? WHERE id = 1",
47        )
48        .bind(now.to_rfc3339())
49        .bind(kanban_core::KANBAN_VERSION)
50        .bind(kanban_core::KANBAN_COMMIT)
51        .execute(&self.pool)
52        .await
53        .map_err(|e| KanbanError::Database(e.to_string()))?;
54        Ok(now)
55    }
56
57    /// Truncate the WAL. Pure I/O step; does not touch the writer-stamp
58    /// columns. Callers that want a durable save with attribution should
59    /// invoke [`stamp_writer`] alongside this.
60    pub async fn checkpoint(&self) -> KanbanResult<()> {
61        sqlx::query("PRAGMA wal_checkpoint(TRUNCATE)")
62            .execute(&self.pool)
63            .await
64            .map_err(|e| KanbanError::Database(e.to_string()))?;
65        Ok(())
66    }
67}