kanban_persistence_sqlite/sqlite_store/
command_log.rs1use chrono::Utc;
2use kanban_domain::KanbanResult;
3use sqlx::Row;
4
5use super::helpers::{db_err, fmt_dt};
6use super::SqliteStore;
7
8impl SqliteStore {
11 async fn append_command_batch_with_conn(
12 conn: &mut sqlx::SqliteConnection,
13 batch_index: u64,
14 commands_json: &str,
15 ) -> KanbanResult<()> {
16 sqlx::query(
17 "INSERT INTO command_log (batch_index, commands_json, created_at) VALUES (?, ?, ?)",
18 )
19 .bind(batch_index as i64)
20 .bind(commands_json)
21 .bind(fmt_dt(&Utc::now()))
22 .execute(&mut *conn)
23 .await
24 .map_err(db_err)?;
25 Ok(())
26 }
27
28 pub async fn append_command_batch(
31 &self,
32 batch_index: u64,
33 commands_json: &str,
34 ) -> KanbanResult<()> {
35 let commands_json = commands_json.to_string();
36 self.db_conn(|conn| {
37 Box::pin(async move {
38 Self::append_command_batch_with_conn(conn, batch_index, &commands_json).await
39 })
40 })
41 .await
42 }
43
44 async fn load_all_command_batches_with_conn(
45 conn: &mut sqlx::SqliteConnection,
46 ) -> KanbanResult<Vec<String>> {
47 let rows = sqlx::query("SELECT commands_json FROM command_log ORDER BY batch_index ASC")
48 .fetch_all(&mut *conn)
49 .await
50 .map_err(db_err)?;
51 let mut out = Vec::with_capacity(rows.len());
52 for row in &rows {
53 out.push(row.try_get::<String, _>("commands_json").map_err(db_err)?);
54 }
55 Ok(out)
56 }
57
58 pub async fn load_all_command_batches(&self) -> KanbanResult<Vec<String>> {
61 self.db_conn(|conn| {
62 Box::pin(async move { Self::load_all_command_batches_with_conn(conn).await })
63 })
64 .await
65 }
66
67 async fn truncate_command_log_after_with_conn(
68 conn: &mut sqlx::SqliteConnection,
69 after: u64,
70 ) -> KanbanResult<()> {
71 sqlx::query("DELETE FROM command_log WHERE batch_index >= ?")
72 .bind(after as i64)
73 .execute(&mut *conn)
74 .await
75 .map_err(db_err)?;
76 Ok(())
77 }
78
79 pub async fn truncate_command_log_after(&self, after: u64) -> KanbanResult<()> {
81 self.db_conn(|conn| {
82 Box::pin(async move { Self::truncate_command_log_after_with_conn(conn, after).await })
83 })
84 .await
85 }
86
87 async fn shift_command_log_with_conn(
88 conn: &mut sqlx::SqliteConnection,
89 drop_count: u64,
90 ) -> KanbanResult<()> {
91 if drop_count == 0 {
92 return Ok(());
93 }
94 sqlx::query("DELETE FROM command_log WHERE batch_index < ?")
95 .bind(drop_count as i64)
96 .execute(&mut *conn)
97 .await
98 .map_err(db_err)?;
99 sqlx::query("UPDATE command_log SET batch_index = batch_index - ?")
100 .bind(drop_count as i64)
101 .execute(&mut *conn)
102 .await
103 .map_err(db_err)?;
104 Ok(())
105 }
106
107 pub async fn shift_command_log(&self, drop_count: u64) -> KanbanResult<()> {
113 self.db_conn(|conn| {
114 Box::pin(async move { Self::shift_command_log_with_conn(conn, drop_count).await })
115 })
116 .await
117 }
118}