Skip to main content

kanban_persistence_sqlite/sqlite_store/
command_log.rs

1use chrono::Utc;
2use kanban_domain::KanbanResult;
3use sqlx::Row;
4
5use super::helpers::{db_err, fmt_dt};
6use super::SqliteStore;
7
8// ── Command log (audit foundation; not yet wired through SqliteBackend) ──
9
10impl SqliteStore {
11    /// Append a single command batch at logical index `batch_index`.
12    /// `commands_json` is the serde-JSON encoding of the `Vec<Command>` batch.
13    pub async fn append_command_batch(
14        &self,
15        batch_index: u64,
16        commands_json: &str,
17    ) -> KanbanResult<()> {
18        sqlx::query(
19            "INSERT INTO command_log (batch_index, commands_json, created_at) VALUES (?, ?, ?)",
20        )
21        .bind(batch_index as i64)
22        .bind(commands_json)
23        .bind(fmt_dt(&Utc::now()))
24        .execute(&self.pool)
25        .await
26        .map_err(db_err)?;
27        Ok(())
28    }
29
30    /// Load all persisted command batches in order. Returns the JSON strings
31    /// so callers can deserialise inside the domain layer.
32    pub async fn load_all_command_batches(&self) -> KanbanResult<Vec<String>> {
33        let rows = sqlx::query("SELECT commands_json FROM command_log ORDER BY batch_index ASC")
34            .fetch_all(&self.pool)
35            .await
36            .map_err(db_err)?;
37        let mut out = Vec::with_capacity(rows.len());
38        for row in &rows {
39            out.push(row.try_get::<String, _>("commands_json").map_err(db_err)?);
40        }
41        Ok(out)
42    }
43
44    /// Remove batches with logical index >= `after`. Retains [0, after).
45    pub async fn truncate_command_log_after(&self, after: u64) -> KanbanResult<()> {
46        sqlx::query("DELETE FROM command_log WHERE batch_index >= ?")
47            .bind(after as i64)
48            .execute(&self.pool)
49            .await
50            .map_err(db_err)?;
51        Ok(())
52    }
53
54    /// Remove the oldest `drop_count` batches and renumber the rest so the
55    /// surviving log starts at index 0.
56    pub async fn shift_command_log(&self, drop_count: u64) -> KanbanResult<()> {
57        if drop_count == 0 {
58            return Ok(());
59        }
60        let mut tx = self.pool.begin().await.map_err(db_err)?;
61        sqlx::query("DELETE FROM command_log WHERE batch_index < ?")
62            .bind(drop_count as i64)
63            .execute(&mut *tx)
64            .await
65            .map_err(db_err)?;
66        sqlx::query("UPDATE command_log SET batch_index = batch_index - ?")
67            .bind(drop_count as i64)
68            .execute(&mut *tx)
69            .await
70            .map_err(db_err)?;
71        tx.commit().await.map_err(db_err)?;
72        Ok(())
73    }
74}