Skip to main content

khive_db/
sql_bridge.rs

1//! SqlAccess bridge: connects `ConnectionPool` to `khive_storage::SqlAccess`.
2//!
3//! Two modes:
4//! - **File-backed**: ordinary reads check out pooled readers per operation.
5//!   The only standalone-reader exception is an explicitly admitted multi-call
6//!   deferred read transaction; standalone writer handles remain capped at one.
7//!   Cross-statement write atomicity goes through `atomic_unit`, which drives a
8//!   single registered raw transaction span rather than a caller-held per-tx
9//!   connection.
10//! - **Memory**: Uses pool-backed approach (acquire pool connection per-query inside `spawn_blocking`).
11
12#[path = "sql_bridge/write_errors.rs"]
13mod write_errors;
14
15#[path = "sql_bridge/manual_atomic.rs"]
16mod manual_atomic;
17use manual_atomic::run_manual_atomic_unit;
18#[path = "sql_bridge/standalone_admission.rs"]
19mod standalone_admission;
20use standalone_admission::{
21    acquire_standalone_lease, admit_standalone_operation, StandaloneWriteError,
22};
23mod standalone_batch;
24#[cfg(test)]
25use standalone_batch::BatchPoisonReason;
26use standalone_batch::{
27    run_standalone_batch, run_standalone_script, run_standalone_statement,
28    run_standalone_top_level, BatchFailure, PoisonedBatchError,
29};
30
31mod standalone_call;
32use standalone_call::{
33    execute_standalone_writer_query, writer_query_requires_admission, StandaloneCallOwner,
34};
35
36use std::any::Any;
37use std::sync::atomic::{AtomicU64, Ordering};
38use std::sync::Arc;
39
40use async_trait::async_trait;
41
42use khive_storage::error::StorageError;
43use khive_storage::types::{PageRequest, SqlColumn, SqlRow, SqlStatement, SqlValue};
44use khive_storage::{AtomicUnitOp, StorageCapability, TopLevelMaintenance};
45use tokio::sync::{OwnedSemaphorePermit, Semaphore};
46
47use crate::error::SqliteError;
48use crate::pool::{ConnectionPool, SharedReaderTransactionGuard, StandaloneReaderPurpose};
49
50// =============================================================================
51// Shared helpers
52// =============================================================================
53
54mod batch_exec;
55use batch_exec::{
56    cached_read_transaction_control, execute_prepared_batch, next_sqlite_token,
57    reject_transaction_control_statements, skip_sqlite_empty_prefix, transaction_control_head,
58    CachedReadTransactionControl,
59};
60
61mod rows;
62
63pub(crate) use rows::bind_params;
64use rows::{
65    prepare_batch_statements, prepare_cached_sql_statement, prepare_sql_statement, row_to_sql_row,
66    AtomicEventRows,
67};
68#[cfg(test)]
69use rows::{COUNTED_EVENT_INSERT_LABELS, ROW_CONVERSIONS};
70
71#[cfg(test)]
72#[path = "atomic_event_usage_tests.rs"]
73mod atomic_event_usage_tests;
74
75mod query_execution;
76use query_execution::{
77    execute_prepared_query, execute_prepared_query_page, execute_prepared_query_row, execute_query,
78    execute_query_page, execute_query_row, map_rusqlite_err, map_write_boundary_err, map_write_err,
79    prepare_bound_statement, settle_pooled_call,
80};
81
82#[cfg(test)]
83#[path = "sql_bridge/sync_executor_tests.rs"]
84mod sync_executor_tests;
85
86/// Execute trusted statements inside a caller-owned active transaction.
87///
88/// The caller owns writer admission, commit, rollback, and connection settlement.
89/// This function starts no transaction or savepoint, installs no hooks, retries
90/// nothing, and does not account committed events. The returned affected-row sum
91/// is execution evidence, not a commit receipt; zero affected rows is successful.
92///
93/// Explicit transaction-control heads are rejected across the list before
94/// preparation. Each element must contain only one SQL statement. Other prepare
95/// failures may be deferred until execution to allow earlier schema changes, so
96/// an error can follow earlier successful writes. Missing raw parameters bind as
97/// NULL; excess parameters fail binding before that element steps.
98///
99/// This is not a SQL sandbox: PRAGMAs, UDFs, triggers, and virtual tables may have
100/// connection or external effects, and SQLite errors can end the transaction.
101/// The owner must handle rollback and verify settlement on error.
102///
103/// # Errors
104/// Returns [`SqliteError::InvalidData`] for autocommit connections (even with an
105/// empty list) or explicit transaction control. Native prepare, bind, and step
106/// failures are preserved as [`SqliteError::Rusqlite`].
107pub fn execute_statements(
108    conn: &rusqlite::Connection,
109    statements: &[SqlStatement],
110) -> Result<u64, SqliteError> {
111    if conn.is_autocommit() {
112        return Err(SqliteError::InvalidData(
113            "execute_statements requires a caller-owned active transaction".into(),
114        ));
115    }
116    for (index, statement) in statements.iter().enumerate() {
117        if let Some(keyword) = transaction_control_head(&statement.sql) {
118            return Err(SqliteError::InvalidData(format!(
119                "statement at index {index} is transaction control ({keyword}); \
120                 the caller owns the transaction boundary"
121            )));
122        }
123    }
124    let prepared = prepare_batch_statements(conn, statements)?;
125    Ok(execute_prepared_batch(conn, prepared, statements, None)?)
126}
127
128mod reader_capability;
129use reader_capability::{
130    admit_reader_capability_sql, execute_query_interruptibly, execute_query_page_interruptibly,
131    execute_query_row_interruptibly,
132};
133pub(crate) use reader_capability::{reader_capability_admits, statement_guard_select_admits};
134
135mod handles;
136pub(crate) use handles::acquire_in_memory_write_unit;
137pub(crate) use handles::build_standalone_writer;
138use handles::{
139    acquire_handle_slot, acquire_reader_handle_slot, open_standalone_reader_on_blocking,
140    open_standalone_writer_on_blocking, SlotTimeoutClass,
141};
142#[cfg(test)]
143use handles::{open_external_writer_fixture, open_standalone_on_blocking, open_standalone_reader};
144
145mod sqlite_reader;
146#[cfg(test)]
147use sqlite_reader::CACHED_READ_TRANSACTION_LABEL;
148use sqlite_reader::{
149    execute_standalone_read, open_explicit_read_transaction_handle, SqliteReader, StandaloneHandle,
150};
151
152mod sqlite_writer;
153use sqlite_writer::{execute_top_level_maintenance, SqliteWriter};
154
155mod pool_backed;
156use pool_backed::{run_pool_reader_query, PoolBackedReader, PoolBackedWriter};
157
158mod inline_bridge;
159pub use inline_bridge::SqlBridge;
160#[cfg(test)]
161use inline_bridge::{block_on_sync, InlineWriter};
162
163#[cfg(test)]
164#[path = "sql_bridge_tests.rs"]
165mod tests;
166
167#[cfg(test)]
168#[path = "sql_bridge/direct_busy_tests.rs"]
169mod direct_busy_tests;
170
171#[cfg(test)]
172mod manual_atomic_owner_tests;
173
174#[cfg(test)]
175#[path = "sql_bridge/settlement_hazard_tests.rs"]
176mod settlement_hazard_tests;
177
178#[cfg(test)]
179mod cancel_after_classification_tests;
180#[cfg(test)]
181mod writer_query_admission_tests;