1use crate::agenda::{AgendaFilter, AgendaItem};
10use crate::error::{KernelError, Result};
11
12pub(crate) const AGENDA_REGISTRY_TABLE: &str = "_adk_kernel_agenda_migrations";
14
15#[cfg(feature = "sqlite")]
17const SQLITE_MIGRATIONS: &[(i64, &str, &str)] = &[(
18 1,
19 "create the kernel agenda table",
20 "\
21CREATE TABLE IF NOT EXISTS adk_kernel_agenda (\
22 id TEXT PRIMARY KEY, \
23 partition_id TEXT NOT NULL, \
24 state TEXT NOT NULL, \
25 created_at BIGINT NOT NULL, \
26 item TEXT NOT NULL\
27);\
28CREATE INDEX IF NOT EXISTS adk_kernel_agenda_partition ON adk_kernel_agenda (partition_id, state, created_at, id);\
29CREATE INDEX IF NOT EXISTS adk_kernel_agenda_state ON adk_kernel_agenda (state, created_at, id);",
30)];
31
32#[cfg(feature = "postgres")]
35const POSTGRES_MIGRATIONS: &[(i64, &str, &str)] = &[(
36 1,
37 "create the kernel agenda table",
38 "\
39CREATE TABLE IF NOT EXISTS adk_kernel_agenda (\
40 id TEXT COLLATE \"C\" PRIMARY KEY, \
41 partition_id TEXT NOT NULL, \
42 state TEXT NOT NULL, \
43 created_at BIGINT NOT NULL, \
44 item TEXT NOT NULL\
45);\
46CREATE INDEX IF NOT EXISTS adk_kernel_agenda_partition ON adk_kernel_agenda (partition_id, state, created_at, id);\
47CREATE INDEX IF NOT EXISTS adk_kernel_agenda_state ON adk_kernel_agenda (state, created_at, id);",
48)];
49
50pub(crate) const PUT: &str = "\
51INSERT INTO adk_kernel_agenda (id, partition_id, state, created_at, item) \
52VALUES ($1, $2, $3, $4, $5) \
53ON CONFLICT (id) DO UPDATE SET \
54 partition_id = excluded.partition_id, state = excluded.state, \
55 created_at = excluded.created_at, item = excluded.item";
56
57pub(crate) const GET: &str = "SELECT item FROM adk_kernel_agenda WHERE id = $1";
58
59pub(crate) const TRANSITION: &str = "\
60UPDATE adk_kernel_agenda SET partition_id = $1, state = $2, created_at = $3, item = $4 \
61WHERE id = $5 AND state = $6";
62
63pub(crate) const DELETE: &str = "DELETE FROM adk_kernel_agenda WHERE id = $1";
64
65pub(crate) fn created_at(item: &AgendaItem) -> i64 {
67 item.created_at.timestamp_micros()
68}
69
70pub(crate) fn list(filter: &AgendaFilter) -> (String, Vec<String>, Option<i64>) {
72 let mut conditions = Vec::new();
73 let mut binds = Vec::new();
74 if let Some(partition) = &filter.partition {
75 binds.push(partition.as_str().to_string());
76 conditions.push(format!("partition_id = ${}", binds.len()));
77 }
78 if !filter.states.is_empty() {
79 let mut placeholders = Vec::new();
80 for state in &filter.states {
81 binds.push(state.as_str().to_string());
82 placeholders.push(format!("${}", binds.len()));
83 }
84 conditions.push(format!("state IN ({})", placeholders.join(", ")));
85 }
86 let mut sql = "SELECT item FROM adk_kernel_agenda".to_string();
87 if !conditions.is_empty() {
88 sql.push_str(" WHERE ");
89 sql.push_str(&conditions.join(" AND "));
90 }
91 sql.push_str(" ORDER BY created_at, id");
92 let limit = filter.limit.map(|limit| i64::try_from(limit).unwrap_or(i64::MAX));
93 if limit.is_some() {
94 sql.push_str(&format!(" LIMIT ${}", binds.len() + 1));
95 }
96 (sql, binds, limit)
97}
98
99pub(crate) fn decode(backend: &'static str, item: &str) -> Result<AgendaItem> {
101 serde_json::from_str(item).map_err(|error| KernelError::Store {
102 backend,
103 reason: format!("an agenda row is corrupt: {error}"),
104 })
105}
106
107pub(crate) fn db_error(backend: &'static str, action: &str, error: &sqlx::Error) -> KernelError {
109 KernelError::Store { backend, reason: format!("could not {action} the agenda table: {error}") }
110}
111
112macro_rules! sql_agenda_store {
115 ($store:ty, $backend:literal) => {
116 #[async_trait::async_trait]
117 impl $crate::agenda::AgendaStore for $store {
118 async fn put(&self, item: $crate::agenda::AgendaItem) -> $crate::error::Result<()> {
119 let json = serde_json::to_string(&item)?;
120 sqlx::query($crate::stores::agenda_sql::PUT)
121 .bind(&item.id)
122 .bind(item.partition.as_str())
123 .bind(item.state.kind().as_str())
124 .bind($crate::stores::agenda_sql::created_at(&item))
125 .bind(json)
126 .execute(&self.pool)
127 .await
128 .map_err(|e| $crate::stores::agenda_sql::db_error($backend, "write", &e))?;
129 Ok(())
130 }
131
132 async fn get(
133 &self,
134 id: &str,
135 ) -> $crate::error::Result<Option<$crate::agenda::AgendaItem>> {
136 let row: Option<(String,)> = sqlx::query_as($crate::stores::agenda_sql::GET)
137 .bind(id)
138 .fetch_optional(&self.pool)
139 .await
140 .map_err(|e| $crate::stores::agenda_sql::db_error($backend, "read", &e))?;
141 row.map(|(item,)| $crate::stores::agenda_sql::decode($backend, &item)).transpose()
142 }
143
144 async fn list(
145 &self,
146 filter: &$crate::agenda::AgendaFilter,
147 ) -> $crate::error::Result<Vec<$crate::agenda::AgendaItem>> {
148 let (sql, binds, limit) = $crate::stores::agenda_sql::list(filter);
149 let mut query = sqlx::query_as::<_, (String,)>(sqlx::AssertSqlSafe(sql));
150 for bind in binds {
151 query = query.bind(bind);
152 }
153 if let Some(limit) = limit {
154 query = query.bind(limit);
155 }
156 let rows = query
157 .fetch_all(&self.pool)
158 .await
159 .map_err(|e| $crate::stores::agenda_sql::db_error($backend, "list", &e))?;
160 rows.iter()
161 .map(|(item,)| $crate::stores::agenda_sql::decode($backend, item))
162 .collect()
163 }
164
165 async fn transition(
166 &self,
167 item: $crate::agenda::AgendaItem,
168 from: $crate::agenda::AgendaStateKind,
169 ) -> $crate::error::Result<bool> {
170 let json = serde_json::to_string(&item)?;
171 let done = sqlx::query($crate::stores::agenda_sql::TRANSITION)
172 .bind(item.partition.as_str())
173 .bind(item.state.kind().as_str())
174 .bind($crate::stores::agenda_sql::created_at(&item))
175 .bind(json)
176 .bind(&item.id)
177 .bind(from.as_str())
178 .execute(&self.pool)
179 .await
180 .map_err(|e| $crate::stores::agenda_sql::db_error($backend, "update", &e))?;
181 Ok(done.rows_affected() > 0)
182 }
183
184 async fn delete(&self, id: &str) -> $crate::error::Result<bool> {
185 let done = sqlx::query($crate::stores::agenda_sql::DELETE)
186 .bind(id)
187 .execute(&self.pool)
188 .await
189 .map_err(|e| {
190 $crate::stores::agenda_sql::db_error($backend, "delete from", &e)
191 })?;
192 Ok(done.rows_affected() > 0)
193 }
194 }
195 };
196}
197
198#[cfg(feature = "sqlite")]
221#[derive(Debug, Clone)]
222pub struct SqliteAgendaStore {
223 pool: sqlx::SqlitePool,
224}
225
226#[cfg(feature = "sqlite")]
227impl SqliteAgendaStore {
228 pub fn new(pool: sqlx::SqlitePool) -> Self {
230 Self { pool }
231 }
232
233 pub fn pool(&self) -> &sqlx::SqlitePool {
235 &self.pool
236 }
237
238 pub async fn migrate(&self) -> Result<()> {
245 adk_session::migration::sqlite_runner::run_sql_migrations(
246 &self.pool,
247 AGENDA_REGISTRY_TABLE,
248 SQLITE_MIGRATIONS,
249 || async { Ok(false) },
250 )
251 .await
252 .map_err(|error| KernelError::Store { backend: "sqlite", reason: error.message })
253 }
254}
255
256#[cfg(feature = "sqlite")]
257sql_agenda_store!(SqliteAgendaStore, "sqlite");
258
259#[cfg(feature = "postgres")]
276#[derive(Debug, Clone)]
277pub struct PostgresAgendaStore {
278 pool: sqlx::PgPool,
279}
280
281#[cfg(feature = "postgres")]
282impl PostgresAgendaStore {
283 pub fn new(pool: sqlx::PgPool) -> Self {
285 Self { pool }
286 }
287
288 pub fn pool(&self) -> &sqlx::PgPool {
290 &self.pool
291 }
292
293 pub async fn connect(database_url: &str) -> Result<Self> {
299 let pool =
300 sqlx::PgPool::connect(database_url).await.map_err(|error| KernelError::Store {
301 backend: "postgres",
302 reason: format!("could not connect: {error}"),
303 })?;
304 Ok(Self::new(pool))
305 }
306
307 pub async fn migrate(&self) -> Result<()> {
315 super::postgres::migrate_locked(
316 self.pool.clone(),
317 AGENDA_REGISTRY_TABLE,
318 POSTGRES_MIGRATIONS,
319 )
320 .await
321 }
322}
323
324#[cfg(feature = "postgres")]
325sql_agenda_store!(PostgresAgendaStore, "postgres");
326
327#[cfg(test)]
328mod tests {
329 use super::*;
330 use crate::agenda::AgendaStateKind;
331
332 #[test]
333 fn list_numbers_parameters_in_order() {
334 assert_eq!(
335 list(&AgendaFilter::default()).0,
336 "SELECT item FROM adk_kernel_agenda ORDER BY created_at, id"
337 );
338 let filter = AgendaFilter::default()
339 .partition("work")
340 .states([AgendaStateKind::Proposed, AgendaStateKind::Scheduled])
341 .limit(5);
342 let (sql, binds, limit) = list(&filter);
343 assert_eq!(
344 sql,
345 "SELECT item FROM adk_kernel_agenda WHERE partition_id = $1 AND state IN ($2, $3) \
346 ORDER BY created_at, id LIMIT $4"
347 );
348 assert_eq!(binds, ["work", "proposed", "scheduled"]);
349 assert_eq!(limit, Some(5));
350 }
351}