Skip to main content

khive_storage/
sql.rs

1//! SQL access capability traits.
2
3use async_trait::async_trait;
4
5use crate::types::{SqlRow, SqlStatement, SqlTxOptions, SqlValue, StorageResult};
6
7/// Read-capable SQL connection.
8#[async_trait]
9pub trait SqlReader: Send + 'static {
10    /// Execute `statement` and return the first row, or `None` if the result set is empty.
11    async fn query_row(&mut self, statement: SqlStatement) -> StorageResult<Option<SqlRow>>;
12    /// Execute `statement` and return all rows.
13    async fn query_all(&mut self, statement: SqlStatement) -> StorageResult<Vec<SqlRow>>;
14    /// Execute `statement` and return the first column of the first row as a scalar.
15    async fn query_scalar(&mut self, statement: SqlStatement) -> StorageResult<Option<SqlValue>>;
16    /// Run `EXPLAIN QUERY PLAN` for `statement` and return the plan rows.
17    async fn explain(&mut self, statement: SqlStatement) -> StorageResult<Vec<SqlRow>>;
18}
19
20/// Write-capable SQL connection (extends `SqlReader`).
21#[async_trait]
22pub trait SqlWriter: SqlReader + Send + 'static {
23    /// Execute a single DML statement and return the number of rows affected.
24    async fn execute(&mut self, statement: SqlStatement) -> StorageResult<u64>;
25    /// Execute multiple DML statements and return the total rows affected.
26    async fn execute_batch(&mut self, statements: Vec<SqlStatement>) -> StorageResult<u64>;
27    /// Execute a raw SQL script (no parameters; used for migrations).
28    async fn execute_script(&mut self, script: String) -> StorageResult<()>;
29}
30
31/// A SQL transaction (extends `SqlWriter`).
32#[async_trait]
33pub trait SqlTransaction: SqlWriter + Send + 'static {
34    /// Commit the transaction, persisting all changes.
35    async fn commit(self: Box<Self>) -> StorageResult<()>;
36    /// Roll back the transaction, discarding all changes.
37    async fn rollback(self: Box<Self>) -> StorageResult<()>;
38}
39
40/// Base SQL access capability.
41#[async_trait]
42pub trait SqlAccess: Send + Sync + 'static {
43    /// Acquire a read-only connection from the pool.
44    async fn reader(&self) -> StorageResult<Box<dyn SqlReader>>;
45    /// Acquire a read-write connection from the pool.
46    async fn writer(&self) -> StorageResult<Box<dyn SqlWriter>>;
47    /// Begin a transaction with the given isolation options.
48    async fn begin_tx(&self, options: SqlTxOptions) -> StorageResult<Box<dyn SqlTransaction>>;
49}