//! SQL-backed Store implementation for SQLite and PostgreSQL. //! //! Uses `sqlx::Any` for database-agnostic queries. Enable features //! `sqlite` or `postgres` to select the backend. //! //! ```text //! kuatia_storage_sql::install_drivers()?; //! let pool = sqlx::any::AnyPoolOptions::new() //! .connect("sqlite::memory:").await?; //! let store = SqlStore::new(pool); //! store.migrate().await?; //! ``` //! //! [`install_drivers`] replaces `sqlx::any::install_default_drivers` and has to //! run before the pool connects; see its docs for why. //! //! The [`Store`](kuatia_storage::store::Store) sub-traits are each implemented in //! their own module (`account`, `posting`, `transfer`, `commit`, `event`, //! `book`, `projection`); shared row mappers and codecs live in `row`, the schema //! migrations in `migrate`, the SQLite/PostgreSQL divergence behind the //! `Dialect` seam in `dialect`, and the SQLite money functions in `sqlite_ext`. use sqlx::{Any, Pool}; use kuatia_storage::error::StoreError; use kuatia_types::autoid::AutoId; use crate::dialect::Dialect; mod account; mod asset; mod book; mod commit; mod dialect; mod event; mod migrate; mod posting; mod projection; mod row; #[cfg(feature = "sqlite")] mod sqlite_ext; mod transfer; /// Install the `sqlx::Any` drivers and, when the `sqlite` feature is on, the /// SQLite money functions. /// /// Call this instead of [`sqlx::any::install_default_drivers`], and call it /// **before** connecting any pool: the SQLite functions are registered as an /// auto-extension, so a connection opened earlier will not have them and every /// statement naming one fails to prepare. pub fn install_drivers() -> Result<(), StoreError> { sqlx::any::install_default_drivers(); install_sqlite_extensions() } /// Install just the SQLite money functions, for callers that install the /// `sqlx::Any` drivers themselves. Idempotent; a no-op without the `sqlite` /// feature. See [`install_drivers`] for the ordering requirement. pub fn install_sqlite_extensions() -> Result<(), StoreError> { #[cfg(feature = "sqlite")] { sqlite_ext::install()?; } Ok(()) } /// SQL-backed [`Store`](kuatia_storage::store::Store) implementation. pub struct SqlStore { pool: Pool, autoid: AutoId, /// Which backend this store talks to; resolved once at construction. dialect: Dialect, } impl SqlStore { /// Create a new SQL store wrapping an existing connection pool. The backend /// dialect is resolved from the pool's connection URL, so no query is issued /// here; call [`migrate`](Self::migrate) next to apply the schema. pub fn new(pool: Pool) -> Self { let dialect = Dialect::from_pool(&pool); Self { pool, autoid: AutoId::new(), dialect, } } }