| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325 |
- //! [`PostingStore`]: the immutable posting record plus one `live_postings` hot
- //! table whose membership is each posting's state.
- //!
- //! A posting is in `live_postings` while it is spendable. Once consumed the row
- //! is deleted, leaving the posting only in the immutable `postings` table, so
- //! the two tables never disagree about what is spent. See ADR-0022 (merged hot
- //! index) and ADR-0016.
- use std::collections::HashMap;
- use async_trait::async_trait;
- use sqlx::Row;
- use sqlx::any::AnyRow;
- use kuatia_storage::error::StoreError;
- use kuatia_storage::store::*;
- use kuatia_types::*;
- use crate::SqlStore;
- use crate::dialect::Dialect;
- use crate::row::{row_to_cent, row_to_posting, transfer_id_to_hex};
- /// The live-balance aggregate, shared by [`PostingStore::live_balance`] and the
- /// in-transaction overdraft floor in `commit`, so both read the balance the same
- /// way. The sum happens in the database and is exact on both backends
- /// (ADR-0024).
- pub(crate) fn live_balance_sql(dialect: Dialect) -> String {
- format!(
- "SELECT {} AS total FROM live_postings \
- WHERE owner = $1 AND subaccount = $2 AND asset = $3",
- dialect.money_sum("value")
- )
- }
- /// The source table a posting read of the given filter targets. No UNION and no
- /// predicate: the live set is exactly one table's rows.
- fn filter_source(filter: PostingFilter) -> &'static str {
- match filter {
- PostingFilter::Live => "live_postings",
- PostingFilter::All => "postings",
- }
- }
- /// Maximum posting ids matched by a single statement. `id_predicate` expands to
- /// an `OR` of `n` equality pairs, so the binding constraint is SQLite's
- /// expression-tree depth limit (`SQLITE_MAX_EXPR_DEPTH`, default 1000), which a
- /// chain of `n` `OR`s reaches at roughly `n` deep. It caps well before the
- /// bind-parameter limits (SQLite 32766, PostgreSQL 65535) that `2 * n (+1)`
- /// parameters would hit. `500` stays comfortably under the expression-depth
- /// limit; callers that pass more ids are chunked, so the id-batch primitives
- /// have no practical ceiling on batch size.
- pub(crate) const MAX_IDS_PER_QUERY: usize = 500;
- /// Build a portable predicate matching a set of posting ids:
- /// `(transfer_id = $s AND idx = $s+1) OR (transfer_id = $s+2 AND idx = $s+3) ...`
- /// starting at placeholder `$start`. Row-value `IN ((a, b), ...)` is not
- /// portable across SQLite and PostgreSQL; an `OR` of equality pairs is. The
- /// caller binds each id as `(hex(transfer), idx as i16)` in order, matching the
- /// placeholder sequence. `ids` must be non-empty and no longer than
- /// [`MAX_IDS_PER_QUERY`]; larger sets are split into chunks by the caller.
- pub(crate) fn id_predicate(count: usize, start: u32) -> String {
- (0..count)
- .map(|i| {
- let p = start + (i as u32) * 2;
- format!("(transfer_id = ${} AND idx = ${})", p, p + 1)
- })
- .collect::<Vec<_>>()
- .join(" OR ")
- }
- #[async_trait]
- impl PostingStore for SqlStore {
- async fn get_postings(&self, ids: &[PostingId]) -> Result<Vec<Posting>, StoreError> {
- if ids.is_empty() {
- return Ok(Vec::new());
- }
- // Set-based query per chunk instead of one probe per id, reusing the
- // portable `id_predicate` and binding each id in order as
- // `(hex(transfer), idx as i16)`. Chunked so a large batch never exceeds
- // the backend's bind-parameter limit (see `MAX_IDS_PER_QUERY`).
- let mut found: HashMap<(String, i16), Posting> = HashMap::with_capacity(ids.len());
- for chunk in ids.chunks(MAX_IDS_PER_QUERY) {
- let sql = format!(
- "SELECT {} FROM postings WHERE {}",
- self.dialect.posting_columns(),
- id_predicate(chunk.len(), 1)
- );
- let mut q = sqlx::query(&sql);
- for id in chunk {
- q = q
- .bind(transfer_id_to_hex(&id.transfer))
- .bind(id.index as i16);
- }
- let rows = q
- .fetch_all(&self.pool)
- .await
- .map_err(|e| StoreError::Internal(e.to_string()))?;
- // Index the fetched postings by the same `(hex, idx)` key that was bound.
- for row in &rows {
- let posting = row_to_posting(self.dialect, row)?;
- let key = (
- transfer_id_to_hex(&posting.id.transfer),
- posting.id.index as i16,
- );
- found.insert(key, posting);
- }
- }
- // Return in input order, erroring on the first id absent from the batch
- // (matching the per-id lookup's `NotFound` semantics).
- let mut result = Vec::with_capacity(ids.len());
- for id in ids {
- let key = (transfer_id_to_hex(&id.transfer), id.index as i16);
- let posting = found
- .get(&key)
- .ok_or_else(|| StoreError::NotFound(format!("posting {id:?}")))?;
- result.push(posting.clone());
- }
- Ok(result)
- }
- async fn get_postings_by_account(
- &self,
- id: i64,
- sub: Option<i64>,
- asset: Option<&AssetId>,
- filter: PostingFilter,
- ) -> Result<Vec<Posting>, StoreError> {
- // Build the predicate dynamically: `sub == None` spans every subaccount
- // of `id`, `Some(s)` restricts to one. The subaccount is compared only
- // for equality, never as a magnitude.
- let source = filter_source(filter);
- let mut sql = format!(
- "SELECT {} FROM {source} WHERE owner = $1",
- self.dialect.posting_columns()
- );
- let mut placeholder = 2u32;
- if sub.is_some() {
- sql.push_str(&format!(" AND subaccount = ${placeholder}"));
- placeholder += 1;
- }
- if asset.is_some() {
- sql.push_str(&format!(" AND asset = ${placeholder}"));
- }
- // Deterministic order by the posting primary key, matching
- // `query_postings`, so callers (and pagination built on top) see a
- // stable sequence.
- sql.push_str(" ORDER BY transfer_id, idx");
- let mut q = sqlx::query(&sql).bind(id);
- if let Some(s) = sub {
- q = q.bind(s);
- }
- if let Some(a) = asset {
- q = q.bind(a.0 as i32);
- }
- let rows = q
- .fetch_all(&self.pool)
- .await
- .map_err(|e| StoreError::Internal(e.to_string()))?;
- rows.iter()
- .map(|row| row_to_posting(self.dialect, row))
- .collect()
- }
- async fn live_balance(&self, account: &AccountId, asset: &AssetId) -> Result<Cent, StoreError> {
- let row = sqlx::query(&live_balance_sql(self.dialect))
- .bind(account.id)
- .bind(account.sub)
- .bind(asset.0 as i32)
- .fetch_one(&self.pool)
- .await
- .map_err(|e| StoreError::Internal(e.to_string()))?;
- row_to_cent(self.dialect, &row, "total")
- }
- async fn get_posting_states(&self, ids: &[PostingId]) -> Result<Vec<PostingState>, StoreError> {
- if ids.is_empty() {
- return Ok(Vec::new());
- }
- // Two set-based queries per chunk: membership of the live table decides
- // Live, and `postings` decides Spent vs Missing for ids absent from it.
- // Reuses the portable `id_predicate` (an OR of equality pairs; row-value
- // `IN` is not portable across SQLite and PostgreSQL), binding each id as
- // `(hex, idx)`.
- // Key membership by the same `(hex, idx)` values that were bound, so the
- // per-id lookup below matches without decoding transfer ids back.
- let row_key = |row: &AnyRow| -> Result<(String, i16), StoreError> {
- let transfer_id: String = row
- .try_get("transfer_id")
- .map_err(|e| StoreError::Internal(e.to_string()))?;
- let idx: i16 = row
- .try_get("idx")
- .map_err(|e| StoreError::Internal(e.to_string()))?;
- Ok((transfer_id, idx))
- };
- // `present` is every id in the immutable record, which is what tells
- // Spent (present, not live) from Missing (absent).
- let mut live: std::collections::HashSet<(String, i16)> = std::collections::HashSet::new();
- let mut present: std::collections::HashSet<(String, i16)> =
- std::collections::HashSet::new();
- for chunk in ids.chunks(MAX_IDS_PER_QUERY) {
- let predicate = id_predicate(chunk.len(), 1);
- let live_sql = format!("SELECT transfer_id, idx FROM live_postings WHERE {predicate}");
- let mut live_q = sqlx::query(&live_sql);
- for id in chunk {
- live_q = live_q
- .bind(transfer_id_to_hex(&id.transfer))
- .bind(id.index as i16);
- }
- let live_rows = live_q
- .fetch_all(&self.pool)
- .await
- .map_err(|e| StoreError::Internal(e.to_string()))?;
- for row in &live_rows {
- live.insert(row_key(row)?);
- }
- let present_sql = format!("SELECT transfer_id, idx FROM postings WHERE {predicate}");
- let mut present_q = sqlx::query(&present_sql);
- for id in chunk {
- present_q = present_q
- .bind(transfer_id_to_hex(&id.transfer))
- .bind(id.index as i16);
- }
- let present_rows = present_q
- .fetch_all(&self.pool)
- .await
- .map_err(|e| StoreError::Internal(e.to_string()))?;
- for row in &present_rows {
- present.insert(row_key(row)?);
- }
- }
- // Reconstruct each id's state in input order, live before spent before
- // missing, so a duplicated id resolves to the same state both times.
- let mut out = Vec::with_capacity(ids.len());
- for id in ids {
- let key = (transfer_id_to_hex(&id.transfer), id.index as i16);
- out.push(if live.contains(&key) {
- PostingState::Live
- } else if present.contains(&key) {
- PostingState::Spent
- } else {
- PostingState::Missing
- });
- }
- Ok(out)
- }
- async fn query_postings(&self, query: &PostingQuery) -> Result<Page<Posting>, StoreError> {
- let (where_clause, count_clause) = {
- let source = filter_source(query.filter);
- let mut w = String::from("WHERE owner = $1");
- let mut idx = 2u32;
- if query.sub.is_some() {
- w.push_str(&format!(" AND subaccount = ${idx}"));
- idx += 1;
- }
- if query.asset.is_some() {
- w.push_str(&format!(" AND asset = ${idx}"));
- }
- let c = format!("SELECT COUNT(*) as cnt FROM {source} {w}");
- let (offset, limit) = kuatia_storage::query::window(query.offset, query.limit);
- // Order by the posting primary key so pagination is deterministic:
- // without it LIMIT/OFFSET could skip or repeat rows across pages.
- w.push_str(&format!(
- " ORDER BY transfer_id, idx LIMIT {limit} OFFSET {offset}"
- ));
- (
- format!(
- "SELECT {} FROM {source} {w}",
- self.dialect.posting_columns()
- ),
- c,
- )
- };
- // Build count query
- let mut count_q = sqlx::query(&count_clause).bind(query.account);
- if let Some(s) = query.sub {
- count_q = count_q.bind(s);
- }
- if let Some(ref a) = query.asset {
- count_q = count_q.bind(a.0 as i32);
- }
- let count_row = count_q
- .fetch_one(&self.pool)
- .await
- .map_err(|e| StoreError::Internal(e.to_string()))?;
- let total: i64 = count_row
- .try_get("cnt")
- .map_err(|e| StoreError::Internal(e.to_string()))?;
- // Build data query
- let mut data_q = sqlx::query(&where_clause).bind(query.account);
- if let Some(s) = query.sub {
- data_q = data_q.bind(s);
- }
- if let Some(ref a) = query.asset {
- data_q = data_q.bind(a.0 as i32);
- }
- let rows = data_q
- .fetch_all(&self.pool)
- .await
- .map_err(|e| StoreError::Internal(e.to_string()))?;
- let items: Vec<Posting> = rows
- .iter()
- .map(|row| row_to_posting(self.dialect, row))
- .collect::<Result<_, _>>()?;
- Ok(Page {
- items,
- total: total as u64,
- })
- }
- }
|