adk_kernel/control/store/sqlite.rs
1//! The SQLite [`ControlStore`](super::ControlStore) (spec 3.3 §10 K3, K4; feature
2//! `sqlite`).
3
4use super::sql::{REGISTRY_TABLE, sql_control_store};
5use crate::error::{KernelError, Result};
6
7/// Migrations of [`SqliteControlStore`], recorded in `_adk_kernel_control_migrations`.
8const MIGRATIONS: &[(i64, &str, &str)] = &[(
9 1,
10 "create kernel area settings and away cursor tables",
11 "\
12CREATE TABLE IF NOT EXISTS adk_kernel_area_settings (\
13 partition_id TEXT PRIMARY KEY, \
14 record TEXT NOT NULL\
15);\
16CREATE TABLE IF NOT EXISTS adk_kernel_away_cursors (\
17 user_id TEXT NOT NULL, \
18 viewer TEXT NOT NULL, \
19 seq INTEGER NOT NULL, \
20 record TEXT NOT NULL, \
21 PRIMARY KEY (user_id, viewer)\
22);",
23)];
24
25/// A [`ControlStore`](super::ControlStore) in SQLite (spec 3.3 §10 K3, K4; feature
26/// `sqlite`).
27///
28/// In the CLI it lives in `harness.db` on the same pool as the harness and process stores:
29/// its tables are `adk_kernel_area_settings` and `adk_kernel_away_cursors`, and
30/// [`migrate`](Self::migrate) records its steps in `_adk_kernel_control_migrations`. Call
31/// `migrate` once before use.
32///
33/// # Example
34///
35/// ```rust
36/// use adk_kernel::control::{AwayCursor, ControlStore, SqliteControlStore};
37///
38/// # #[tokio::main(flavor = "current_thread")]
39/// # async fn main() -> adk_kernel::Result<()> {
40/// let pool = sqlx::SqlitePool::connect("sqlite::memory:").await.unwrap();
41/// let store = SqliteControlStore::new(pool);
42/// store.migrate().await?;
43/// store.advance_cursor(AwayCursor::new("ana", "home", 7, chrono::Utc::now())).await?;
44/// assert_eq!(store.cursor("ana", "home").await?.unwrap().seq, 7);
45/// # Ok(())
46/// # }
47/// ```
48#[derive(Debug, Clone)]
49pub struct SqliteControlStore {
50 pool: sqlx::SqlitePool,
51}
52
53impl SqliteControlStore {
54 /// A store over `pool`, such as the pool of `harness.db`.
55 pub fn new(pool: sqlx::SqlitePool) -> Self {
56 Self { pool }
57 }
58
59 /// The pool the store writes to.
60 pub fn pool(&self) -> &sqlx::SqlitePool {
61 &self.pool
62 }
63
64 /// Creates or upgrades the store's tables. Idempotent.
65 ///
66 /// # Errors
67 ///
68 /// Returns [`KernelError::Store`] when a statement fails, or when the database was
69 /// migrated by a newer release.
70 pub async fn migrate(&self) -> Result<()> {
71 adk_session::migration::sqlite_runner::run_sql_migrations(
72 &self.pool,
73 REGISTRY_TABLE,
74 MIGRATIONS,
75 || async { Ok(false) },
76 )
77 .await
78 .map_err(|error| KernelError::Store { backend: "sqlite", reason: error.message })
79 }
80}
81
82sql_control_store!(SqliteControlStore, "sqlite");