Bladeren bron

Make kuatia the only crate an application depends on

Opening a ledger on SQLite meant naming kuatia, kuatia-storage-sql and sqlx in
one manifest, then rebuilding the pool by hand at every call site. Two details
had to be right each time and were written down in only one place, the
dashboard's helper: the SQLite money functions are registered as an
auto-extension, so a connection opened before install_drivers lacks them, and
sqlite::memory: gives each connection its own database, so a pool wider than
one connection splits the ledger into a copy per connection.
SqlStore::connect and Ledger::connect own both. The backend reaches a caller as
kuatia::sql behind a feature, so an application on the in-memory store or a
hand-written one still compiles no sqlx.

The quick example in the README named an asset by a hand-minted AssetId, which
the asset registry had already made unusable: an amount is built from the
handle the registry returns, and a commit in an unregistered asset is refused.
Nothing compiled the snippet, so the breakage was invisible, and the crate
README had gone further and was calling verbs that take a separate asset and
amount. The example is now the source of a program the compiler checks, and a
test fails if the README stops matching it.
C 3 dagen geleden
bovenliggende
commit
70b9992a2d

+ 24 - 0
CHANGELOG.md

@@ -7,6 +7,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
 
 ## [Unreleased]
 
+### Added
+
+- `kuatia` is now the only crate an application names in `Cargo.toml`. It
+  re-exports `kuatia-core`, `kuatia-types` and `kuatia-storage`, and the SQL
+  backend as `kuatia::sql` behind a new `sqlite` or `postgres` feature. The
+  other crates stay published for custom development, such as a hand-written
+  `Store`.
+- `SqlStore::connect(db_url)` and `Ledger::connect(db_url)` open a database and
+  apply the schema, so opening a ledger no longer means naming `sqlx` and
+  building the pool by hand. Both own the two traps that cost callers before:
+  the SQLite driver must be installed before any connection opens, and
+  `sqlite::memory:` gives each connection its own database, so a wider pool
+  splits the ledger.
+- `kuatia::prelude` exports `SqlStore` under the `sql` feature.
+- A `quickstart` example, which the top-level README's quick example is held to
+  by a test.
+
+### Fixed
+
+- The quick example in the README named an asset by a hand-minted `AssetId`,
+  which the asset registry made unusable: an amount needs the handle the
+  registry returns. `crates/kuatia/README.md` and `doc/crates.md` still showed
+  the pre-registry builder verbs taking a separate asset and amount.
+
 ## [0.4.0] - 2026-12-02
 
 ### Upgrading to 0.4.0

+ 0 - 3
Cargo.lock

@@ -1029,7 +1029,6 @@ dependencies = [
  "kuatia-types",
  "serde",
  "serde_json",
- "sqlx",
  "tokio",
  "tracing",
 ]
@@ -1052,10 +1051,8 @@ dependencies = [
  "kuatia",
  "kuatia-core",
  "kuatia-storage",
- "kuatia-storage-sql",
  "serde",
  "serde_json",
- "sqlx",
  "tera",
  "tokio",
  "tower-http",

+ 1 - 1
Cargo.toml

@@ -18,7 +18,7 @@ kuatia-money = { path = "crates/kuatia-money", version = "0.4.0" }
 kuatia-types = { path = "crates/kuatia-types", version = "0.4.0" }
 kuatia-core = { path = "crates/kuatia-core", version = "0.4.0" }
 kuatia-storage = { path = "crates/kuatia-storage", version = "0.4.0" }
-kuatia-storage-sql = { path = "crates/kuatia-storage-sql", version = "0.4.0" }
+kuatia-storage-sql = { path = "crates/kuatia-storage-sql", version = "0.4.0", default-features = false }
 
 # External crates
 serde = { version = "1", features = ["derive"] }

+ 76 - 14
README.md

@@ -31,7 +31,7 @@ reconstructs every balance, so the ledger is auditable by construction. See
 ├─────────────────────────────────────────────────────┤
 │               kuatia-core (pure)                    │
 │                                                     │
-│  Types:         Account · Transfer · Posting · Cent │
+│  Types:        Account · Transfer · Posting · Amount│
 │  Validation:    validate_and_plan()                 │
 │  Hashing:       double-SHA256, content-addressed    │
 │  Selection:     greedy posting selection            │
@@ -40,37 +40,99 @@ reconstructs every balance, so the ledger is auditable by construction. See
 
 ## Crates
 
+An application depends on **kuatia** alone. It re-exports the whole chain, the
+SQL backend as `kuatia::sql` behind the `sqlite` or `postgres` feature, so the
+crates below it are reachable without being named in a manifest. They are
+published for custom development: a hand-written `Store`, or an embedding of
+the pure core with no async layer at all.
+
 | Crate | Purpose |
 |-------|---------|
-| **kuatia-types** | Domain types — `AccountId`, `Posting`, `Transfer`, `Cent`, etc. |
-| **kuatia-core** | Pure, sans-IO decision logic — validation, hashing, posting selection. |
-| **kuatia-storage** | `Store` trait (7 sub-traits), `InMemoryStore`, `store_tests!` conformance macro. |
-| **kuatia-storage-sql** | SQL-backed `Store` — SQLite and PostgreSQL via sqlx. |
-| **kuatia** | Async resource layer: `Ledger`, the atomic commit engine, intent-layer API. |
+| **kuatia** | What you depend on. Async resource layer: `Ledger`, the atomic commit engine, intent-layer API. |
+| **kuatia-core** | Pure, sans-IO decision logic: validation, hashing, posting selection. |
+| **kuatia-types** | Domain types: `AccountId`, `Posting`, `Transfer`, `Asset`, `Amount`. |
+| **kuatia-money** | The `Cent` monetary type behind `Amount`. Its integer width is swappable and never appears in a public signature. |
+| **kuatia-storage** | `Store` trait (8 sub-traits), `InMemoryStore`, `store_tests!` conformance macro. |
+| **kuatia-storage-sql** | SQL-backed `Store`: SQLite and PostgreSQL via sqlx. |
 
 ## Quick Example
 
+`kuatia` is the only crate to name in `Cargo.toml`:
+
+```toml
+[dependencies]
+kuatia = "0.4"
+tokio = { version = "1", features = ["full"] }
+```
+
+An asset is registered by code on first sight, and the handle it returns is
+what every amount is denominated in. `"100.00"` parses at that asset's own
+scale. Alice and Bob forbid overdraft, so neither can go negative; `external`
+is the boundary account where value enters and leaves, and it permits
+overdraft, so it goes negative by exactly what the ledger holds.
+
 ```rust
-use kuatia::ledger::Ledger;
-use kuatia::mem_store::InMemoryStore;
-use kuatia_core::*;
+use kuatia::prelude::*;
 
 #[tokio::main]
 async fn main() -> Result<(), Box<dyn std::error::Error>> {
     let ledger = Ledger::new(InMemoryStore::new());
 
-    let usd = AssetId::new(1);
+    let usd = ledger.asset("USD", "$", 2).await?;
+
     let alice = AccountId::new(1);
     let bob = AccountId::new(2);
-    let bank = AccountId::new(3); // external account
-
-    // Create accounts, deposit, pay...
-    // See doc/crates.md for the full API reference.
+    let external = AccountId::new(99);
+
+    ledger
+        .create_account(Account::debit_must_not_exceed_credit(alice))
+        .await?;
+    ledger
+        .create_account(Account::debit_must_not_exceed_credit(bob))
+        .await?;
+    ledger.create_account(Account::new(external)).await?;
+
+    ledger
+        .commit(
+            TransferBuilder::new()
+                .deposit(alice, ("100.00", &usd), external)
+                .build()?,
+        )
+        .await?;
+
+    ledger
+        .commit(
+            TransferBuilder::new()
+                .pay(alice, bob, ("25.00", &usd))
+                .build()?,
+        )
+        .await?;
+
+    println!("alice: {}", ledger.balance(&alice, &usd).await?);
+    println!("bob:   {}", ledger.balance(&bob, &usd).await?);
 
     Ok(())
 }
 ```
 
+That is `crates/kuatia/examples/quickstart.rs` verbatim. Run it with
+`cargo run -p kuatia --example quickstart`; a test fails if the two drift.
+
+### Persistence
+
+The SQLite and PostgreSQL backend is a feature of the same crate:
+
+```toml
+kuatia = { version = "0.4", features = ["sqlite"] }
+```
+
+```rust
+let ledger = Ledger::connect("sqlite://ledger.db?mode=rwc").await?;
+```
+
+Only that line changes. The URL scheme picks the backend, and `connect`
+installs the driver, sizes the pool and applies the schema.
+
 ## Documentation
 
 [`doc/`](doc/README.md) holds the full documentation: the model, the accounting

+ 1 - 3
crates/kuatia-dashboard/Cargo.toml

@@ -12,15 +12,13 @@ name = "kuatia-dashboard"
 path = "src/main.rs"
 
 [dependencies]
-kuatia = { path = "../kuatia", version = "0.4.0" }
+kuatia = { path = "../kuatia", version = "0.4.0", features = ["sqlite", "postgres"] }
 kuatia-core = { workspace = true }
 kuatia-storage = { workspace = true }
-kuatia-storage-sql = { workspace = true, features = ["postgres"] }
 
 tokio = { workspace = true, features = ["full"] }
 serde = { workspace = true }
 serde_json = { workspace = true }
-sqlx = { workspace = true, features = ["sqlite", "postgres"] }
 
 axum = "0.8"
 clap = { version = "4", features = ["derive", "env"] }

+ 1 - 26
crates/kuatia-dashboard/src/seed.rs

@@ -7,7 +7,6 @@ use std::sync::Arc;
 
 use kuatia::ledger::Ledger;
 use kuatia_core::{Account, AccountId, Asset, TransferBuilder};
-use kuatia_storage_sql::SqlStore;
 
 /// Well-known account ids used by the demo.
 pub const TREASURY: AccountId = AccountId::new(1);
@@ -39,32 +38,8 @@ pub fn account_label(id: AccountId) -> Option<&'static str> {
 /// Connect to the ledger database at `db_url` and create the schema. The URL
 /// scheme selects the backend (e.g. `sqlite::memory:`,
 /// `sqlite://kuatia.db`, `postgres://user:pass@host/db`).
-///
-/// The pool is capped at a single connection: `sqlite::memory:` gives each
-/// connection its own separate database, so more than one would split the
-/// ledger; one connection is also fine for a low-traffic dashboard on a file or
-/// Postgres backend.
 pub async fn connect(db_url: &str) -> Result<Arc<Ledger>, Box<dyn Error>> {
-    kuatia_storage_sql::install_drivers()?;
-    let pool = sqlx::any::AnyPoolOptions::new()
-        .max_connections(1)
-        .connect(&sqlite_creatable(db_url))
-        .await?;
-    let store = SqlStore::new(pool);
-    store.migrate().await?;
-    let ledger = Arc::new(Ledger::new(store));
-    Ok(ledger)
-}
-
-/// A SQLite backend will not create a missing file unless the URL asks for it,
-/// so add `mode=rwc` to a file-backed `sqlite:` URL that does not already set a
-/// mode. In-memory and non-SQLite URLs pass through unchanged.
-fn sqlite_creatable(db_url: &str) -> String {
-    if !db_url.starts_with("sqlite:") || db_url.contains(":memory:") || db_url.contains("mode=") {
-        return db_url.to_string();
-    }
-    let sep = if db_url.contains('?') { '&' } else { '?' };
-    format!("{db_url}{sep}mode=rwc")
+    Ok(Arc::new(Ledger::connect(db_url).await?))
 }
 
 /// Seed the demo data only if the ledger has no accounts yet. Returns `true` if

+ 19 - 3
crates/kuatia-storage-sql/README.md

@@ -33,15 +33,31 @@ function and sees the blob. See ADR-0024.
 
 ## Usage
 
-`install_drivers()` replaces `sqlx::any::install_default_drivers()` and must run
-**before** the pool connects: it registers the SQLite money functions as an
-auto-extension, so a connection opened earlier would not have them.
+Most callers never name this crate: `kuatia` re-exports it as `kuatia::sql`
+behind its `sqlite` or `postgres` feature, and `Ledger::connect(url)` wraps the
+whole of the below.
+
+```rust
+use kuatia_storage_sql::SqlStore;
+
+let store = SqlStore::connect("sqlite::memory:").await?;
+```
+
+`connect` installs the drivers, caps the pool at one connection and applies the
+schema. Supply your own pool to size it differently, and then two things are
+yours to get right. `install_drivers()` replaces
+`sqlx::any::install_default_drivers()` and must run **before** the pool
+connects: it registers the SQLite money functions as an auto-extension, so a
+connection opened earlier would not have them. And `sqlite::memory:` gives each
+connection its own separate database, so a pool wider than one connection
+splits the ledger into a copy per connection.
 
 ```rust
 use kuatia_storage_sql::{SqlStore, install_drivers};
 
 install_drivers()?;
 let pool = sqlx::any::AnyPoolOptions::new()
+    .max_connections(1)
     .connect("sqlite::memory:").await?;
 let store = SqlStore::new(pool);
 store.migrate().await?;

+ 35 - 5
crates/kuatia-storage-sql/src/lib.rs

@@ -4,13 +4,11 @@
 //! `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?;
+//! let store = SqlStore::connect("sqlite::memory:").await?;
 //! ```
 //!
+//! [`SqlStore::connect`] owns the driver install, the pool and the migration.
+//! A caller that needs its own pool uses [`SqlStore::new`] instead, and then
 //! [`install_drivers`] replaces `sqlx::any::install_default_drivers` and has to
 //! run before the pool connects; see its docs for why.
 //!
@@ -20,6 +18,7 @@
 //! migrations in `migrate`, the SQLite/PostgreSQL divergence behind the
 //! `Dialect` seam in `dialect`, and the SQLite money functions in `sqlite_ext`.
 
+use sqlx::any::AnyPoolOptions;
 use sqlx::{Any, Pool};
 
 use kuatia_storage::error::StoreError;
@@ -84,4 +83,35 @@ impl SqlStore {
             dialect,
         }
     }
+
+    /// Open the ledger database at `db_url` and apply the schema. The URL scheme
+    /// selects the backend (`sqlite::memory:`, `sqlite://kuatia.db`,
+    /// `postgres://user:pass@host/db`).
+    ///
+    /// The pool is capped at a single connection because `sqlite::memory:` gives
+    /// each connection its own separate database, so a wider pool would split
+    /// the ledger into one copy per connection. Build the pool yourself and pass
+    /// it to [`new`](Self::new) to size it for a file or Postgres backend.
+    pub async fn connect(db_url: &str) -> Result<Self, StoreError> {
+        install_drivers()?;
+        let pool = AnyPoolOptions::new()
+            .max_connections(1)
+            .connect(&sqlite_creatable(db_url))
+            .await
+            .map_err(|e| StoreError::Internal(format!("connect to {db_url}: {e}")))?;
+        let store = Self::new(pool);
+        store.migrate().await?;
+        Ok(store)
+    }
+}
+
+/// A SQLite backend will not create a missing file unless the URL asks for it,
+/// so add `mode=rwc` to a file-backed `sqlite:` URL that does not already set a
+/// mode. In-memory and non-SQLite URLs pass through unchanged.
+fn sqlite_creatable(db_url: &str) -> String {
+    if !db_url.starts_with("sqlite:") || db_url.contains(":memory:") || db_url.contains("mode=") {
+        return db_url.to_string();
+    }
+    let sep = if db_url.contains('?') { '&' } else { '?' };
+    format!("{db_url}{sep}mode=rwc")
 }

+ 41 - 4
crates/kuatia/Cargo.toml

@@ -15,14 +15,25 @@ workspace = true
 
 [features]
 default = []
+# The SQL backend, re-exported as `kuatia::sql` so a caller needs no second
+# crate. Off by default: an in-memory or custom store should not compile sqlx.
+sql = ["dep:kuatia-storage-sql"]
+sqlite = ["sql", "kuatia-storage-sql/sqlite"]
+postgres = ["sql", "kuatia-storage-sql/postgres"]
 # Bubble the i128 Cent backing up to the outermost crate. Enabling
 # `kuatia/i128` swaps the integer width across the whole dependency chain.
-i128 = ["kuatia-types/i128", "kuatia-core/i128", "kuatia-storage/i128"]
+i128 = [
+    "kuatia-types/i128",
+    "kuatia-core/i128",
+    "kuatia-storage/i128",
+    "kuatia-storage-sql?/i128",
+]
 
 [dependencies]
 kuatia-types.workspace = true
 kuatia-core.workspace = true
 kuatia-storage.workspace = true
+kuatia-storage-sql = { workspace = true, optional = true }
 tokio = { workspace = true, features = ["sync", "rt", "macros"] }
 serde.workspace = true
 serde_json.workspace = true
@@ -32,6 +43,32 @@ tracing.workspace = true
 
 [dev-dependencies]
 tokio = { workspace = true, features = ["full"] }
-# For the runnable examples — connect to a real SQLite-backed ledger.
-kuatia-storage-sql.workspace = true
-sqlx = { workspace = true, features = ["sqlite"] }
+
+# Listed explicitly because the SQLite-backed ones need the feature that
+# re-exports the backend, and naming any example turns autodiscovery off.
+[[example]]
+name = "quickstart"
+
+[[example]]
+name = "create_accounts"
+required-features = ["sqlite"]
+
+[[example]]
+name = "fund_and_trade"
+required-features = ["sqlite"]
+
+[[example]]
+name = "withdraw"
+required-features = ["sqlite"]
+
+[[example]]
+name = "overdraft"
+required-features = ["sqlite"]
+
+[[example]]
+name = "inflight_hold"
+required-features = ["sqlite"]
+
+[[example]]
+name = "escrow"
+required-features = ["sqlite"]

+ 35 - 15
crates/kuatia/README.md

@@ -6,6 +6,12 @@ Composes `kuatia-core` (validation) and `kuatia-storage` (persistence) into an
 atomic commit engine: resolve, validate, then apply the whole transfer in one
 store transaction.
 
+This is the only crate an application depends on. The whole chain is re-exported
+here, the SQL backend as `kuatia::sql` behind the `sqlite` or `postgres`
+feature, and `kuatia::prelude::*` brings the domain types, the builders and the
+stores into scope. The other crates stay published for custom development, such
+as a hand-written `Store`.
+
 ## API layers
 
 ### Intent layer (highest level)
@@ -13,18 +19,22 @@ store transaction.
 Build transfers with `TransferBuilder`, then commit them:
 
 ```rust
+let usd = ledger.asset("USD", "$", 2).await?;
 let transfer = TransferBuilder::new()
-    .deposit(alice, usd, Cent::from(100), bank)
-    .build();
+    .deposit(alice, ("100.00", &usd), bank)
+    .build()?;
 let receipt = ledger.commit(transfer).await?;
 ```
 
+Every verb takes one `amount`, which carries the asset it is denominated in, so
+`build()` is where a bad amount surfaces.
+
 | Builder method | Description |
 |---------------|-------------|
-| `.pay(from, to, asset, amount)` | Transfer with automatic posting selection and change |
-| `.deposit(to, asset, amount, external)` | Fund an account from an external source |
-| `.withdraw(from, asset, amount, external)` | Send value to an external destination |
-| `.movement(from, to, asset, amount)` | Raw movement for custom operations |
+| `.pay(from, to, amount)` | Transfer with automatic posting selection and change |
+| `.deposit(to, amount, external)` | Fund an account from an external source |
+| `.withdraw(from, amount, external)` | Send value to an external destination |
+| `.movement(from, to, amount)` | Raw movement for custom operations |
 
 ### Commit
 
@@ -72,25 +82,35 @@ commits them in order and reverses the committed ones LIFO on failure:
 use kuatia::workflow::run_transfers;
 
 let receipts = run_transfers(&ledger, &[
-    TransferBuilder::new().deposit(alice, usd, amount, bank)?.build(),
-    TransferBuilder::new().pay(alice, bob, usd, amount).build(),
+    TransferBuilder::new().deposit(alice, ("100.00", &usd), bank).build()?,
+    TransferBuilder::new().pay(alice, bob, ("40.00", &usd)).build()?,
 ])
 .await?;
 ```
 
 ## Examples
 
-Runnable programs in [`examples/`](examples/) connect to a real SQLite-backed
-ledger (via `sqlx`) and walk through the core operations:
+`quickstart` runs on the in-memory store, so it needs no feature and no
+database:
+
+```sh
+cargo run -p kuatia --example quickstart
+```
+
+The rest in [`examples/`](examples/) open a real SQLite-backed ledger with
+`Ledger::connect("sqlite::memory:")`, so they need the backend feature:
 
 ```sh
-cargo run -p kuatia --example create_accounts   # create user/system/external accounts
-cargo run -p kuatia --example fund_and_trade     # fund two accounts in different assets, then swap
-cargo run -p kuatia --example withdraw           # fund an account, then withdraw out of the ledger
+cargo run -p kuatia --features sqlite --example create_accounts   # user/system/external accounts
+cargo run -p kuatia --features sqlite --example fund_and_trade    # fund two assets, then swap
+cargo run -p kuatia --features sqlite --example withdraw          # withdraw out of the ledger
+cargo run -p kuatia --features sqlite --example overdraft         # the shortfall posting
+cargo run -p kuatia --features sqlite --example inflight_hold     # authorize, confirm, void
+cargo run -p kuatia --features sqlite --example escrow            # per-agreement subaccounts
 ```
 
-Each opens an in-memory SQLite database (`sqlite::memory:`); point the
-connection string at a file or a Postgres URL for a persistent ledger.
+Point the connection string at a file (`sqlite://ledger.db`) or a Postgres URL
+for a persistent ledger.
 
 ## See also
 

+ 2 - 19
crates/kuatia/examples/create_accounts.rs

@@ -7,13 +7,11 @@
 
 use std::collections::BTreeMap;
 
-use kuatia::ledger::Ledger;
-use kuatia_core::*;
-use kuatia_storage_sql::SqlStore;
+use kuatia::prelude::*;
 
 #[tokio::main]
 async fn main() -> Result<(), Box<dyn std::error::Error>> {
-    let ledger = connect().await?;
+    let ledger = Ledger::connect("sqlite::memory:").await?;
 
     // The common case is one line: a version-1 account.
     ledger
@@ -48,18 +46,3 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
 
     Ok(())
 }
-
-/// Open a fresh in-memory SQLite database, run migrations, and wrap it in a
-/// `Ledger`. Point the connection string at a file (e.g.
-/// `"sqlite://ledger.db?mode=rwc"`) or a Postgres URL for a persistent ledger.
-async fn connect() -> Result<Ledger, Box<dyn std::error::Error>> {
-    kuatia_storage_sql::install_drivers()?;
-    let pool = sqlx::any::AnyPoolOptions::new()
-        .max_connections(1)
-        .connect("sqlite::memory:")
-        .await?;
-    let store = SqlStore::new(pool);
-    store.migrate().await?;
-    let ledger = Ledger::new(store);
-    Ok(ledger)
-}

+ 2 - 16
crates/kuatia/examples/escrow.rs

@@ -12,9 +12,7 @@
 //! cargo run -p kuatia --example escrow
 //! ```
 
-use kuatia::ledger::Ledger;
-use kuatia_core::*;
-use kuatia_storage_sql::SqlStore;
+use kuatia::prelude::*;
 
 /// Top-level account every agreement's escrow hangs off as a subaccount, so one
 /// agreement's money can never be spent by another and each closes on its own.
@@ -26,7 +24,7 @@ fn escrow_for(agreement: i64) -> AccountId {
 
 #[tokio::main]
 async fn main() -> Result<(), Box<dyn std::error::Error>> {
-    let ledger = connect().await?;
+    let ledger = Ledger::connect("sqlite::memory:").await?;
 
     let buyer = AccountId::new(1);
     let seller = AccountId::new(2);
@@ -150,15 +148,3 @@ async fn report(
     println!("{}", line.trim_end());
     Ok(())
 }
-
-async fn connect() -> Result<Ledger, Box<dyn std::error::Error>> {
-    kuatia_storage_sql::install_drivers()?;
-    let pool = sqlx::any::AnyPoolOptions::new()
-        .max_connections(1)
-        .connect("sqlite::memory:")
-        .await?;
-    let store = SqlStore::new(pool);
-    store.migrate().await?;
-    let ledger = Ledger::new(store);
-    Ok(ledger)
-}

+ 2 - 16
crates/kuatia/examples/fund_and_trade.rs

@@ -5,13 +5,11 @@
 //! cargo run -p kuatia --example fund_and_trade
 //! ```
 
-use kuatia::ledger::Ledger;
-use kuatia_core::*;
-use kuatia_storage_sql::SqlStore;
+use kuatia::prelude::*;
 
 #[tokio::main]
 async fn main() -> Result<(), Box<dyn std::error::Error>> {
-    let ledger = connect().await?;
+    let ledger = Ledger::connect("sqlite::memory:").await?;
 
     let alice = AccountId::new(1);
     let bob = AccountId::new(2);
@@ -85,15 +83,3 @@ async fn print_balances(
     );
     Ok(())
 }
-
-async fn connect() -> Result<Ledger, Box<dyn std::error::Error>> {
-    kuatia_storage_sql::install_drivers()?;
-    let pool = sqlx::any::AnyPoolOptions::new()
-        .max_connections(1)
-        .connect("sqlite::memory:")
-        .await?;
-    let store = SqlStore::new(pool);
-    store.migrate().await?;
-    let ledger = Ledger::new(store);
-    Ok(ledger)
-}

+ 1 - 17
crates/kuatia/examples/inflight_hold.rs

@@ -15,12 +15,11 @@ use std::sync::Arc;
 use std::time::Duration;
 
 use kuatia::prelude::*;
-use kuatia_storage_sql::SqlStore;
 use tokio::time::sleep;
 
 #[tokio::main]
 async fn main() -> Result<(), Box<dyn std::error::Error>> {
-    let ledger = connect().await?;
+    let ledger = Ledger::connect("sqlite::memory:").await?;
 
     let customer = AccountId::new(1);
     let merchant = AccountId::new(2);
@@ -150,18 +149,3 @@ async fn print_status(
     }
     Ok(())
 }
-
-/// Open a fresh in-memory SQLite database, run migrations, and wrap it in a
-/// `Ledger`. Point the connection string at a file or a Postgres URL for a
-/// persistent ledger.
-async fn connect() -> Result<Ledger, Box<dyn std::error::Error>> {
-    kuatia_storage_sql::install_drivers()?;
-    let pool = sqlx::any::AnyPoolOptions::new()
-        .max_connections(1)
-        .connect("sqlite::memory:")
-        .await?;
-    let store = SqlStore::new(pool);
-    store.migrate().await?;
-    let ledger = Ledger::new(store);
-    Ok(ledger)
-}

+ 2 - 16
crates/kuatia/examples/overdraft.rs

@@ -7,13 +7,11 @@
 //! ```
 
 use kuatia::error::LedgerError;
-use kuatia::ledger::Ledger;
-use kuatia_core::*;
-use kuatia_storage_sql::SqlStore;
+use kuatia::prelude::*;
 
 #[tokio::main]
 async fn main() -> Result<(), Box<dyn std::error::Error>> {
-    let ledger = connect().await?;
+    let ledger = Ledger::connect("sqlite::memory:").await?;
 
     let treasury = AccountId::new(1);
     let wallet = AccountId::new(2);
@@ -105,15 +103,3 @@ async fn print_postings(
     }
     Ok(())
 }
-
-async fn connect() -> Result<Ledger, Box<dyn std::error::Error>> {
-    kuatia_storage_sql::install_drivers()?;
-    let pool = sqlx::any::AnyPoolOptions::new()
-        .max_connections(1)
-        .connect("sqlite::memory:")
-        .await?;
-    let store = SqlStore::new(pool);
-    store.migrate().await?;
-    let ledger = Ledger::new(store);
-    Ok(ledger)
-}

+ 50 - 0
crates/kuatia/examples/quickstart.rs

@@ -0,0 +1,50 @@
+//! Register an asset, open two accounts, fund one from the boundary and pay the
+//! other. Needs no database and no feature, so it is the shortest whole program
+//! the ledger has.
+//!
+//! Run with:
+//! ```sh
+//! cargo run -p kuatia --example quickstart
+//! ```
+
+use kuatia::prelude::*;
+
+#[tokio::main]
+async fn main() -> Result<(), Box<dyn std::error::Error>> {
+    let ledger = Ledger::new(InMemoryStore::new());
+
+    let usd = ledger.asset("USD", "$", 2).await?;
+
+    let alice = AccountId::new(1);
+    let bob = AccountId::new(2);
+    let external = AccountId::new(99);
+
+    ledger
+        .create_account(Account::debit_must_not_exceed_credit(alice))
+        .await?;
+    ledger
+        .create_account(Account::debit_must_not_exceed_credit(bob))
+        .await?;
+    ledger.create_account(Account::new(external)).await?;
+
+    ledger
+        .commit(
+            TransferBuilder::new()
+                .deposit(alice, ("100.00", &usd), external)
+                .build()?,
+        )
+        .await?;
+
+    ledger
+        .commit(
+            TransferBuilder::new()
+                .pay(alice, bob, ("25.00", &usd))
+                .build()?,
+        )
+        .await?;
+
+    println!("alice: {}", ledger.balance(&alice, &usd).await?);
+    println!("bob:   {}", ledger.balance(&bob, &usd).await?);
+
+    Ok(())
+}

+ 2 - 16
crates/kuatia/examples/withdraw.rs

@@ -5,13 +5,11 @@
 //! cargo run -p kuatia --example withdraw
 //! ```
 
-use kuatia::ledger::Ledger;
-use kuatia_core::*;
-use kuatia_storage_sql::SqlStore;
+use kuatia::prelude::*;
 
 #[tokio::main]
 async fn main() -> Result<(), Box<dyn std::error::Error>> {
-    let ledger = connect().await?;
+    let ledger = Ledger::connect("sqlite::memory:").await?;
 
     let alice = AccountId::new(1);
     let external = AccountId::new(99);
@@ -57,15 +55,3 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
 
     Ok(())
 }
-
-async fn connect() -> Result<Ledger, Box<dyn std::error::Error>> {
-    kuatia_storage_sql::install_drivers()?;
-    let pool = sqlx::any::AnyPoolOptions::new()
-        .max_connections(1)
-        .connect("sqlite::memory:")
-        .await?;
-    let store = SqlStore::new(pool);
-    store.migrate().await?;
-    let ledger = Ledger::new(store);
-    Ok(ledger)
-}

+ 3 - 0
crates/kuatia/src/ledger.rs

@@ -11,6 +11,7 @@
 //! - `balance`: per-subaccount balance queries.
 //! - `query`: read-only queries and book CRUD (thin `Store` pass-throughs that
 //!   relabel `StoreError` as [`LedgerError`]).
+//! - `connect`: opening the SQL backend, under the `sql` feature.
 //!
 //! The inflight-hold API is a further cluster, in [`crate::inflight`].
 
@@ -27,6 +28,8 @@ use crate::error::LedgerError;
 mod asset;
 mod balance;
 mod commit;
+#[cfg(feature = "sql")]
+mod connect;
 mod lifecycle;
 mod projection;
 mod query;

+ 19 - 0
crates/kuatia/src/ledger/connect.rs

@@ -0,0 +1,19 @@
+//! Opening a ledger on the SQL backend without naming `sqlx` or the storage
+//! crate: see [`Ledger::connect`].
+
+use kuatia_storage_sql::SqlStore;
+
+use crate::error::LedgerError;
+use crate::ledger::Ledger;
+
+impl Ledger {
+    /// Open the ledger database at `db_url`, apply the schema, and wrap it.
+    ///
+    /// The URL scheme selects the backend (`sqlite::memory:`,
+    /// `sqlite://kuatia.db`, `postgres://user:pass@host/db`). Pool sizing and
+    /// the SQLite driver setup belong to [`SqlStore::connect`]; build the store
+    /// yourself and pass it to [`new`](Ledger::new) to choose them.
+    pub async fn connect(db_url: &str) -> Result<Self, LedgerError> {
+        Ok(Self::new(SqlStore::connect(db_url).await?))
+    }
+}

+ 12 - 1
crates/kuatia/src/lib.rs

@@ -4,13 +4,24 @@
 //! trait abstracts storage, and the [`Ledger`](crate::ledger::Ledger) struct resolves a
 //! transfer and hands it to the store as one atomic commit (ADR-0023) behind an
 //! async API.
+//!
+//! It is the only crate an application names in `Cargo.toml`: the whole chain
+//! is re-exported here, the SQL backend as [`sql`] behind the `sqlite` or
+//! `postgres` feature. The other crates stay published for custom development,
+//! such as a hand-written [`Store`](kuatia_storage::store::Store) or an
+//! embedding of the pure core on its own.
 
 pub mod error;
 pub mod inflight;
 pub mod ledger;
 pub mod workflow;
 
-// Re-export storage crate for convenience.
 pub use kuatia_storage::{error as store_error, mem_store, store, store_tests};
 
+pub use kuatia_core;
+pub use kuatia_storage;
+#[cfg(feature = "sql")]
+pub use kuatia_storage_sql as sql;
+pub use kuatia_types;
+
 pub mod prelude;

+ 5 - 2
crates/kuatia/src/prelude.rs

@@ -2,8 +2,9 @@
 //!
 //! `use kuatia::prelude::*;` brings the domain types and intent builders from
 //! [`kuatia_core`] into scope, along with the [`Ledger`] resource, the
-//! [`Store`] trait, and the [`InMemoryStore`]. Reach for the individual crates
-//! when you need types the prelude does not surface.
+//! [`Store`] trait, the [`InMemoryStore`] and, with the `sql` feature, the
+//! [`SqlStore`]. Reach for [`kuatia_core`] or [`crate::sql`] when you need a
+//! type the prelude does not surface.
 
 pub use kuatia_core::*;
 
@@ -14,3 +15,5 @@ pub use crate::inflight::{
 pub use crate::ledger::Ledger;
 pub use kuatia_storage::mem_store::InMemoryStore;
 pub use kuatia_storage::store::Store;
+#[cfg(feature = "sql")]
+pub use kuatia_storage_sql::SqlStore;

+ 18 - 0
crates/kuatia/tests/readme.rs

@@ -0,0 +1,18 @@
+//! The README's quick example is the `quickstart` program's source, so a README
+//! that drifts from the compiler fails here rather than in a reader's editor.
+
+const README: &str = include_str!("../../../README.md");
+const QUICKSTART: &str = include_str!("../examples/quickstart.rs");
+
+#[test]
+fn readme_quick_example_matches_the_compiled_example() {
+    let body: Vec<&str> = QUICKSTART
+        .lines()
+        .skip_while(|line| line.starts_with("//!") || line.is_empty())
+        .collect();
+    assert!(
+        README.contains(&body.join("\n")),
+        "README.md's quick example has drifted from crates/kuatia/examples/quickstart.rs; \
+         paste that file's code (without its //! header) into the fence"
+    );
+}

+ 30 - 4
doc/crates.md

@@ -88,8 +88,20 @@ Output is a `Plan` containing `transfer_id`, `postings_to_deactivate`, and
 
 ## kuatia
 
-Async resource layer. Depends on `kuatia-core`, `tokio`, `async-trait`,
-`serde`.
+Async resource layer, and the only crate an application depends on: it
+re-exports `kuatia-core`, `kuatia-types` and `kuatia-storage`, so the crates
+below it are reachable without being named in a manifest.
+
+### Features
+
+| Feature | Effect |
+|---------|--------|
+| `sqlite` | Re-exports the SQL backend as `kuatia::sql` with the SQLite driver, and enables `Ledger::connect` |
+| `postgres` | The same, with the PostgreSQL driver |
+| `i128` | Swaps the `Cent` backing to `i128` across the whole chain |
+
+Both backend features are off by default, so an application on `InMemoryStore`
+or a hand-written `Store` does not compile `sqlx`.
 
 ### Modules
 
@@ -99,8 +111,22 @@ Async resource layer. Depends on `kuatia-core`, `tokio`, `async-trait`,
 | `store` | `Store` composite trait + sub-traits (`AccountStore`, `PostingStore`, `TransferStore`, `CommitStore`, `EventStore`, `AssetStore`, `BookStore`, `BalanceProjectionStore`) |
 | `error` | `StoreError`, `LedgerError`: unified error hierarchy |
 | `mem_store` | `InMemoryStore`: in-memory `Store` implementation for tests |
+| `sql` | The SQL backend (`SqlStore`), under the `sqlite` or `postgres` feature |
+| `prelude` | The domain types, the builders, `Ledger`, and the stores in one import |
 | `workflow` | `run_transfers`: multi-transfer LIFO composition over `commit`/`reverse` |
 
+### Opening a ledger
+
+```rust
+let ledger = Ledger::new(InMemoryStore::new());
+let ledger = Ledger::connect("sqlite://ledger.db?mode=rwc").await?;
+let ledger = Ledger::connect("postgres://user:pass@host/db").await?;
+```
+
+`Ledger::connect` installs the driver, connects a one-connection pool and
+applies the schema. Pass a `SqlStore` built from your own pool to `Ledger::new`
+to size it yourself; `SqlStore::connect` documents the two traps that costs you.
+
 ### Ledger API
 
 #### Commit (atomic)
@@ -273,8 +299,8 @@ is a plain runner, not a saga VM.
 use kuatia::workflow::run_transfers;
 
 let receipts = run_transfers(&ledger, &[
-    TransferBuilder::new().deposit(alice, ("50.00", usd), bank).build()?,
-    TransferBuilder::new().pay(alice, bob, (amount, usd)).build()?,
+    TransferBuilder::new().deposit(alice, ("50.00", &usd), bank).build()?,
+    TransferBuilder::new().pay(alice, bob, ("20.00", &usd)).build()?,
 ])
 .await?;
 ```

+ 30 - 7
doc/examples/runnable.md

@@ -1,19 +1,32 @@
 # Runnable programs
 
-The programs in `crates/kuatia/examples/` drive a real ledger over SQLite in
-memory, so each one runs with no setup:
+The programs in `crates/kuatia/examples/` need no setup. `quickstart` runs on
+the in-memory store, so it needs no feature and no database; the rest open a
+real SQLite database in memory through `Ledger::connect`, which the `sqlite`
+feature re-exports:
 
 ```sh
-cargo run -p kuatia --example create_accounts
-cargo run -p kuatia --example fund_and_trade
-cargo run -p kuatia --example withdraw
-cargo run -p kuatia --example inflight_hold
-cargo run -p kuatia --example escrow
+cargo run -p kuatia --example quickstart
+cargo run -p kuatia --features sqlite --example create_accounts
+cargo run -p kuatia --features sqlite --example fund_and_trade
+cargo run -p kuatia --features sqlite --example withdraw
+cargo run -p kuatia --features sqlite --example overdraft
+cargo run -p kuatia --features sqlite --example inflight_hold
+cargo run -p kuatia --features sqlite --example escrow
 ```
 
 They are included below from source, so what the book shows is the code `cargo
 test` compiles.
 
+## Quickstart
+
+Register an asset, open two accounts, fund one and pay the other. This is the
+same source as the quick example in the top-level README, held there by a test.
+
+```rust
+{{#include ../../crates/kuatia/examples/quickstart.rs}}
+```
+
 ## Create accounts
 
 ```rust
@@ -35,6 +48,16 @@ each asset conserves independently, so a swap needs no special verb.
 {{#include ../../crates/kuatia/examples/withdraw.rs}}
 ```
 
+## Overdraft
+
+A shortfall becomes a negative posting on an account that permits it, and
+`InsufficientFunds` on an account that does not. Walked through in
+[overdraft](overdraft.md).
+
+```rust
+{{#include ../../crates/kuatia/examples/overdraft.rs}}
+```
+
 ## Inflight hold
 
 Authorize, confirm and void through a per-destination holding subaccount; see