use crate::agenda::{AgendaFilter, AgendaItem};
use crate::error::{KernelError, Result};
pub(crate) const AGENDA_REGISTRY_TABLE: &str = "_adk_kernel_agenda_migrations";
#[cfg(feature = "sqlite")]
const SQLITE_MIGRATIONS: &[(i64, &str, &str)] = &[(
1,
"create the kernel agenda table",
"\
CREATE TABLE IF NOT EXISTS adk_kernel_agenda (\
id TEXT PRIMARY KEY, \
partition_id TEXT NOT NULL, \
state TEXT NOT NULL, \
created_at BIGINT NOT NULL, \
item TEXT NOT NULL\
);\
CREATE INDEX IF NOT EXISTS adk_kernel_agenda_partition ON adk_kernel_agenda (partition_id, state, created_at, id);\
CREATE INDEX IF NOT EXISTS adk_kernel_agenda_state ON adk_kernel_agenda (state, created_at, id);",
)];
#[cfg(feature = "postgres")]
const POSTGRES_MIGRATIONS: &[(i64, &str, &str)] = &[(
1,
"create the kernel agenda table",
"\
CREATE TABLE IF NOT EXISTS adk_kernel_agenda (\
id TEXT COLLATE \"C\" PRIMARY KEY, \
partition_id TEXT NOT NULL, \
state TEXT NOT NULL, \
created_at BIGINT NOT NULL, \
item TEXT NOT NULL\
);\
CREATE INDEX IF NOT EXISTS adk_kernel_agenda_partition ON adk_kernel_agenda (partition_id, state, created_at, id);\
CREATE INDEX IF NOT EXISTS adk_kernel_agenda_state ON adk_kernel_agenda (state, created_at, id);",
)];
pub(crate) const PUT: &str = "\
INSERT INTO adk_kernel_agenda (id, partition_id, state, created_at, item) \
VALUES ($1, $2, $3, $4, $5) \
ON CONFLICT (id) DO UPDATE SET \
partition_id = excluded.partition_id, state = excluded.state, \
created_at = excluded.created_at, item = excluded.item";
pub(crate) const GET: &str = "SELECT item FROM adk_kernel_agenda WHERE id = $1";
pub(crate) const TRANSITION: &str = "\
UPDATE adk_kernel_agenda SET partition_id = $1, state = $2, created_at = $3, item = $4 \
WHERE id = $5 AND state = $6";
pub(crate) const DELETE: &str = "DELETE FROM adk_kernel_agenda WHERE id = $1";
pub(crate) fn created_at(item: &AgendaItem) -> i64 {
item.created_at.timestamp_micros()
}
pub(crate) fn list(filter: &AgendaFilter) -> (String, Vec<String>, Option<i64>) {
let mut conditions = Vec::new();
let mut binds = Vec::new();
if let Some(partition) = &filter.partition {
binds.push(partition.as_str().to_string());
conditions.push(format!("partition_id = ${}", binds.len()));
}
if !filter.states.is_empty() {
let mut placeholders = Vec::new();
for state in &filter.states {
binds.push(state.as_str().to_string());
placeholders.push(format!("${}", binds.len()));
}
conditions.push(format!("state IN ({})", placeholders.join(", ")));
}
let mut sql = "SELECT item FROM adk_kernel_agenda".to_string();
if !conditions.is_empty() {
sql.push_str(" WHERE ");
sql.push_str(&conditions.join(" AND "));
}
sql.push_str(" ORDER BY created_at, id");
let limit = filter.limit.map(|limit| i64::try_from(limit).unwrap_or(i64::MAX));
if limit.is_some() {
sql.push_str(&format!(" LIMIT ${}", binds.len() + 1));
}
(sql, binds, limit)
}
pub(crate) fn decode(backend: &'static str, item: &str) -> Result<AgendaItem> {
serde_json::from_str(item).map_err(|error| KernelError::Store {
backend,
reason: format!("an agenda row is corrupt: {error}"),
})
}
pub(crate) fn db_error(backend: &'static str, action: &str, error: &sqlx::Error) -> KernelError {
KernelError::Store { backend, reason: format!("could not {action} the agenda table: {error}") }
}
macro_rules! sql_agenda_store {
($store:ty, $backend:literal) => {
#[async_trait::async_trait]
impl $crate::agenda::AgendaStore for $store {
async fn put(&self, item: $crate::agenda::AgendaItem) -> $crate::error::Result<()> {
let json = serde_json::to_string(&item)?;
sqlx::query($crate::stores::agenda_sql::PUT)
.bind(&item.id)
.bind(item.partition.as_str())
.bind(item.state.kind().as_str())
.bind($crate::stores::agenda_sql::created_at(&item))
.bind(json)
.execute(&self.pool)
.await
.map_err(|e| $crate::stores::agenda_sql::db_error($backend, "write", &e))?;
Ok(())
}
async fn get(
&self,
id: &str,
) -> $crate::error::Result<Option<$crate::agenda::AgendaItem>> {
let row: Option<(String,)> = sqlx::query_as($crate::stores::agenda_sql::GET)
.bind(id)
.fetch_optional(&self.pool)
.await
.map_err(|e| $crate::stores::agenda_sql::db_error($backend, "read", &e))?;
row.map(|(item,)| $crate::stores::agenda_sql::decode($backend, &item)).transpose()
}
async fn list(
&self,
filter: &$crate::agenda::AgendaFilter,
) -> $crate::error::Result<Vec<$crate::agenda::AgendaItem>> {
let (sql, binds, limit) = $crate::stores::agenda_sql::list(filter);
let mut query = sqlx::query_as::<_, (String,)>(sqlx::AssertSqlSafe(sql));
for bind in binds {
query = query.bind(bind);
}
if let Some(limit) = limit {
query = query.bind(limit);
}
let rows = query
.fetch_all(&self.pool)
.await
.map_err(|e| $crate::stores::agenda_sql::db_error($backend, "list", &e))?;
rows.iter()
.map(|(item,)| $crate::stores::agenda_sql::decode($backend, item))
.collect()
}
async fn transition(
&self,
item: $crate::agenda::AgendaItem,
from: $crate::agenda::AgendaStateKind,
) -> $crate::error::Result<bool> {
let json = serde_json::to_string(&item)?;
let done = sqlx::query($crate::stores::agenda_sql::TRANSITION)
.bind(item.partition.as_str())
.bind(item.state.kind().as_str())
.bind($crate::stores::agenda_sql::created_at(&item))
.bind(json)
.bind(&item.id)
.bind(from.as_str())
.execute(&self.pool)
.await
.map_err(|e| $crate::stores::agenda_sql::db_error($backend, "update", &e))?;
Ok(done.rows_affected() > 0)
}
async fn delete(&self, id: &str) -> $crate::error::Result<bool> {
let done = sqlx::query($crate::stores::agenda_sql::DELETE)
.bind(id)
.execute(&self.pool)
.await
.map_err(|e| {
$crate::stores::agenda_sql::db_error($backend, "delete from", &e)
})?;
Ok(done.rows_affected() > 0)
}
}
};
}
#[cfg(feature = "sqlite")]
#[derive(Debug, Clone)]
pub struct SqliteAgendaStore {
pool: sqlx::SqlitePool,
}
#[cfg(feature = "sqlite")]
impl SqliteAgendaStore {
pub fn new(pool: sqlx::SqlitePool) -> Self {
Self { pool }
}
pub fn pool(&self) -> &sqlx::SqlitePool {
&self.pool
}
pub async fn migrate(&self) -> Result<()> {
adk_session::migration::sqlite_runner::run_sql_migrations(
&self.pool,
AGENDA_REGISTRY_TABLE,
SQLITE_MIGRATIONS,
|| async { Ok(false) },
)
.await
.map_err(|error| KernelError::Store { backend: "sqlite", reason: error.message })
}
}
#[cfg(feature = "sqlite")]
sql_agenda_store!(SqliteAgendaStore, "sqlite");
#[cfg(feature = "postgres")]
#[derive(Debug, Clone)]
pub struct PostgresAgendaStore {
pool: sqlx::PgPool,
}
#[cfg(feature = "postgres")]
impl PostgresAgendaStore {
pub fn new(pool: sqlx::PgPool) -> Self {
Self { pool }
}
pub fn pool(&self) -> &sqlx::PgPool {
&self.pool
}
pub async fn connect(database_url: &str) -> Result<Self> {
let pool =
sqlx::PgPool::connect(database_url).await.map_err(|error| KernelError::Store {
backend: "postgres",
reason: format!("could not connect: {error}"),
})?;
Ok(Self::new(pool))
}
pub async fn migrate(&self) -> Result<()> {
super::postgres::migrate_locked(
self.pool.clone(),
AGENDA_REGISTRY_TABLE,
POSTGRES_MIGRATIONS,
)
.await
}
}
#[cfg(feature = "postgres")]
sql_agenda_store!(PostgresAgendaStore, "postgres");
#[cfg(test)]
mod tests {
use super::*;
use crate::agenda::AgendaStateKind;
#[test]
fn list_numbers_parameters_in_order() {
assert_eq!(
list(&AgendaFilter::default()).0,
"SELECT item FROM adk_kernel_agenda ORDER BY created_at, id"
);
let filter = AgendaFilter::default()
.partition("work")
.states([AgendaStateKind::Proposed, AgendaStateKind::Scheduled])
.limit(5);
let (sql, binds, limit) = list(&filter);
assert_eq!(
sql,
"SELECT item FROM adk_kernel_agenda WHERE partition_id = $1 AND state IN ($2, $3) \
ORDER BY created_at, id LIMIT $4"
);
assert_eq!(binds, ["work", "proposed", "scheduled"]);
assert_eq!(limit, Some(5));
}
}