From 8a8bac66392a08bf7ea4f6f618b78f52b050637d Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 22 Nov 2026 17:15:36 +0000 Subject: [PATCH] feat(dialect): add session transaction control Add StartTransaction, Commit, Rollback and SetAutocommit statements to the KiteSQL AST. The generic parser lowers BEGIN or START TRANSACTION, COMMIT and ROLLBACK, rejecting transaction modes, savepoints and AND CHAIN, and lowers SET autocommit = 0 | 1 (or ON/OFF, TRUE/FALSE) only after SqlParser::with_set_autocommit(); otherwise SET autocommit is rejected like any other SET. The SQLite parser lowers BEGIN [DEFERRED], COMMIT/END and ROLLBACK. Add Database::session(), which returns a Session that runs these statements. Between BEGIN and COMMIT or ROLLBACK, statements run in one transaction, as with Transaction::run; outside one, each statement commits on its own, as with Database::run. COMMIT and ROLLBACK without an open transaction do nothing, and dropping the session rolls back an open transaction. With autocommit off, a statement outside a transaction opens one that stays open until COMMIT or ROLLBACK, and turning autocommit back on commits it. DDL and ANALYZE still go through Database::ddl and Database::analyze, and the other entry points reject transaction control statements. Add SqlDialect::begin_commits_active_transaction(), defaulting to false: when true, BEGIN inside an open transaction commits it and opens a new one; by default such a BEGIN is rejected and the open transaction is left as it was. DynDialect forwards it to its current dialect. Database::run and Transaction::run now delegate to run_statements, which the session reuses for statements it has already parsed. Their behaviour is unchanged. Unit tests in src/db/session.rs cover the default and a test-only dialect that parses SET autocommit and turns the hook on. Co-authored-by: Alex Skinner --- docs/features.md | 2 + src/ast/statement.rs | 6 + src/binder/parser.rs | 36 +++- src/db.rs | 2 + src/db/session.rs | 309 ++++++++++++++++++++++++++++++++ src/dialect/mod.rs | 13 ++ src/parser/generic/mod.rs | 15 +- src/parser/generic/statement.rs | 58 +++++- src/parser/sqlite/statement.rs | 10 +- 9 files changed, 439 insertions(+), 12 deletions(-) create mode 100644 src/db/session.rs diff --git a/docs/features.md b/docs/features.md index 4218a8a0..6d49f7e7 100644 --- a/docs/features.md +++ b/docs/features.md @@ -211,6 +211,7 @@ let kite_sql = DataBaseBuilder::path("./data") - Pessimistic (Default) - Optimistic - Isolation level: repeatable read; every statement in a transaction reads the snapshot taken when it began +- SQL transaction control through `Database::session()`: `BEGIN`/`START TRANSACTION`, `COMMIT` and `ROLLBACK` as statements; nested `BEGIN` follows the dialect, and `SET autocommit` is accepted by a dialect that parses it (`SqlParser::with_set_autocommit()`) ### Checkpoint KiteSQL exposes checkpoint as a storage capability rather than a full backup workflow. A checkpoint only creates a consistent local snapshot directory; compressing, uploading, retaining, and pruning backups should stay in application code. @@ -436,6 +437,7 @@ The `SqlDialect` trait methods: - `parse()` — Parses SQL text into KiteSQL statements; the dialect rejects syntax it does not support and may rewrite the statements - `comparison_type()` — Optional hook to pick the type both operands of a comparison (`=`, `<>`, `<`, `<=`, `>`, `>=`, `IN`, `BETWEEN`) are cast to - `boolean_text()` — Optional hook to choose the text of a boolean in `CAST(.. AS CHAR)` or `CAST(.. AS VARCHAR)` (default `'true'`/`'false'`) +- `begin_commits_active_transaction()` — Optional hook to make `BEGIN` in a `Session` commit the open transaction and start a new one (default: rejected) `DataTypeMapper::map_data_type()` maps types inside expressions (`CAST`, typed literals); `map_column_type()` maps the types of column definitions and defaults to `map_data_type()`. diff --git a/src/ast/statement.rs b/src/ast/statement.rs index e19b2567..20a331a5 100644 --- a/src/ast/statement.rs +++ b/src/ast/statement.rs @@ -46,6 +46,12 @@ pub enum Statement { }, ShowTables, ShowViews, + /// `BEGIN` or `START TRANSACTION`; run through [`Session`](crate::db::Session). + StartTransaction, + Commit, + Rollback, + /// `SET autocommit = ..` + SetAutocommit(bool), } #[derive(Debug, Clone, PartialEq)] diff --git a/src/binder/parser.rs b/src/binder/parser.rs index 3087016b..5896fe3f 100644 --- a/src/binder/parser.rs +++ b/src/binder/parser.rs @@ -80,9 +80,19 @@ pub fn command_type(stmt: &Statement) -> Result { | Statement::Insert(_) => CommandType::DML, Statement::Copy(copy) if copy.to => CommandType::DQL, Statement::Copy(_) => CommandType::DML, + Statement::StartTransaction + | Statement::Commit + | Statement::Rollback + | Statement::SetAutocommit(_) => return Err(transaction_control_unsupported()), }) } +fn transaction_control_unsupported() -> DatabaseError { + DatabaseError::UnsupportedStmt( + "transaction control statements require `Database::session`".to_string(), + ) +} + impl State { pub(crate) fn prepare_all>( &self, @@ -205,6 +215,14 @@ impl Database { .state .prepare_all(sql) .map_err(|err| err.with_sql_context(sql))?; + self.run_statements(sql, statements).await + } + + pub(crate) async fn run_statements( + &self, + sql: &str, + statements: Vec, + ) -> Result, DatabaseError> { let has_catalog_mutation = statements .iter() .try_fold(false, |has_mutation, stmt| { @@ -273,10 +291,18 @@ impl<'txn, S: Storage, D: SqlDialect> Transaction<'txn, S, D> { sql: T, ) -> Result>, DatabaseError> { let sql = sql.as_ref(); - let mut statements = self + let statements = self .state .prepare_all(sql) .map_err(|err| err.with_sql_context(sql))?; + self.run_statements(sql, statements).await + } + + pub(crate) async fn run_statements<'a>( + &'a mut self, + sql: &str, + mut statements: Vec, + ) -> Result>, DatabaseError> { for statement in &statements { if statement_mutates_catalog_or_statistics(statement)? { return Err(DatabaseError::UnsupportedStmt( @@ -385,6 +411,10 @@ where } Statement::CreateIndex(create) => self.create_index(create)?, Statement::CreateView(create) => self.create_view(create)?, + Statement::StartTransaction + | Statement::Commit + | Statement::Rollback + | Statement::SetAutocommit(_) => return Err(transaction_control_unsupported()), }; Ok(BindStatementComplete { plan }) @@ -2700,8 +2730,8 @@ mod tests { } assert_unsupported( - database.prepare_all("start transaction").unwrap_err(), - "START TRANSACTION", + command_type(&database.prepare_all("start transaction")?.pop().unwrap()).unwrap_err(), + "`Database::session`", ); Ok(()) diff --git a/src/db.rs b/src/db.rs index fd25dfd6..da7e93cd 100644 --- a/src/db.rs +++ b/src/db.rs @@ -13,6 +13,7 @@ // limitations under the License. mod program; +mod session; pub use crate::ast::Statement; use crate::binder::{Binder, BinderContext}; use crate::dialect::{DynDialect, GenericSqlDialect, SqlDialect}; @@ -62,6 +63,7 @@ use crate::types::value::DataValue; use crate::types::LogicalType; use ordered_float::OrderedFloat; pub use program::{Param, Program, ProgramIter}; +pub use session::{Session, SessionIter}; use std::borrow::Cow; use std::collections::{HashMap, HashSet}; use std::marker::PhantomData; diff --git a/src/db/session.rs b/src/db/session.rs new file mode 100644 index 00000000..a204a323 --- /dev/null +++ b/src/db/session.rs @@ -0,0 +1,309 @@ +// Copyright 2024 KipData/KiteSQL +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use super::*; + +/// Runs SQL with `BEGIN`/`START TRANSACTION`, `COMMIT` and `ROLLBACK` as statements. +/// +/// Outside a transaction each statement commits on its own, as with [`Database::run`]; inside +/// one, statements run as with [`Transaction::run`], and a failed statement leaves the +/// transaction open with whatever it wrote. DDL and `ANALYZE` still go through +/// [`Database::ddl`]/[`Database::analyze`]. `COMMIT`/`ROLLBACK` without a transaction do +/// nothing, and dropping the session rolls back. Nested `BEGIN` follows +/// [`SqlDialect::begin_commits_active_transaction`]. With `SET autocommit = 0`, which needs a +/// dialect that parses it, a statement outside a transaction opens one that stays open until +/// `COMMIT` or `ROLLBACK`, and `SET autocommit = 1` commits it. +/// +/// While a transaction is open, send every statement through the session: on single-writer +/// storage such as LMDB, writing through the [`Database`] on the same thread waits for it. +pub struct Session<'db, S: Storage, D: SqlDialect = GenericSqlDialect> { + database: &'db Database, + transaction: Option>, + autocommit: bool, +} + +impl Database { + /// Opens a [`Session`] with autocommit on. + pub fn session(&self) -> Session<'_, S, D> { + Session { + database: self, + transaction: None, + autocommit: true, + } + } +} + +#[maybe_async] +impl<'db, S: Storage, D: SqlDialect> Session<'db, S, D> { + /// Runs one statement; transaction control statements return no rows. + pub async fn run<'a>( + &'a mut self, + sql: &str, + ) -> Result, DatabaseError> { + let mut statements = self + .database + .prepare_all(sql) + .map_err(|err| err.with_sql_context(sql))?; + if statements.len() != 1 { + return Err(DatabaseError::UnsupportedStmt( + "a session runs one statement at a time".to_string(), + ) + .with_sql_context(sql)); + } + let statement = statements.pop().ok_or(DatabaseError::EmptyStatement)?; + self.run_statement(sql, statement) + .await + .map_err(|err| err.with_sql_context(sql)) + } + + async fn run_statement<'a>( + &'a mut self, + sql: &str, + statement: Statement, + ) -> Result, DatabaseError> { + match &statement { + Statement::StartTransaction => { + self.begin().await?; + return Ok(self.empty()); + } + Statement::Commit => { + self.finish(true).await?; + return Ok(self.empty()); + } + Statement::Rollback => { + self.finish(false).await?; + return Ok(self.empty()); + } + Statement::SetAutocommit(autocommit) => { + if *autocommit && !self.autocommit { + self.finish(true).await?; + } + self.autocommit = *autocommit; + return Ok(self.empty()); + } + _ => (), + } + + if self.transaction.is_none() && !self.autocommit { + self.begin().await?; + } + match self.transaction.as_mut() { + Some(transaction) => Ok(SessionIter { + inner: SessionIterInner::Transaction(Box::new( + transaction.run_statements(sql, vec![statement]).await?, + )), + }), + None => Ok(SessionIter { + inner: SessionIterInner::Database( + self.database.run_statements(sql, vec![statement]).await?, + ), + }), + } + } + + fn empty<'a>(&self) -> SessionIter<'a, 'db, S, D> { + SessionIter { + inner: SessionIterInner::Empty(&self.database.state), + } + } + + async fn begin(&mut self) -> Result<(), DatabaseError> { + if self.transaction.is_some() { + if !self + .database + .state + .dialect() + .begin_commits_active_transaction() + { + return Err(DatabaseError::UnsupportedStmt( + "BEGIN inside an active transaction".to_string(), + )); + } + self.finish(true).await?; + } + self.transaction = Some(self.database.new_transaction(false)?); + Ok(()) + } + + async fn finish(&mut self, commit: bool) -> Result<(), DatabaseError> { + match self.transaction.take() { + Some(transaction) if commit => transaction.commit().await, + // Dropping the transaction rolls it back. + _ => Ok(()), + } + } + + pub fn autocommit(&self) -> bool { + self.autocommit + } + + pub fn in_transaction(&self) -> bool { + self.transaction.is_some() + } +} + +/// Result iterator returned by [`Session::run`]. +pub struct SessionIter<'a, 'db, S: Storage + 'db, D: SqlDialect = GenericSqlDialect> { + inner: SessionIterInner<'a, 'db, S, D>, +} + +enum SessionIterInner<'a, 'db, S: Storage + 'db, D: SqlDialect> { + Empty(&'db State), + Transaction(Box>>), + Database(DatabaseIter<'db, S>), +} + +#[maybe_async] +impl<'a, 'db, S: Storage + 'db, D: SqlDialect> SessionIter<'a, 'db, S, D> { + /// Empty for a transaction control statement. + pub fn schema(&self, f: impl FnOnce(&SchemaView<'_, '_>) -> R) -> R { + match &self.inner { + SessionIterInner::Empty(state) => f(&SchemaView::new( + &Schema::new(), + state.table_arena().borrow(), + )), + SessionIterInner::Transaction(iter) => iter.schema(f), + SessionIterInner::Database(iter) => iter.schema(f), + } + } + + pub async fn next_tuple( + &mut self, + f: impl FnOnce(&SchemaView<'_, '_>, &mut ResultRow<'_, '_>) -> R + MaybeSend, + ) -> Result, DatabaseError> { + match &mut self.inner { + SessionIterInner::Empty(_) => Ok(None), + SessionIterInner::Transaction(iter) => iter.next_tuple(f).await, + SessionIterInner::Database(iter) => iter.next_tuple(f).await, + } + } + + /// A statement outside a transaction commits here. + pub async fn done(self) -> Result<(), DatabaseError> { + match self.inner { + SessionIterInner::Empty(_) => Ok(()), + SessionIterInner::Transaction(iter) => iter.done().await, + SessionIterInner::Database(iter) => iter.done().await, + } + } +} + +#[maybe_async] +impl<'db, S: Storage + 'db, D: SqlDialect> ResultIter for SessionIter<'_, 'db, S, D> { + fn schema(&self, f: impl FnOnce(&SchemaView<'_, '_>) -> R) -> R { + SessionIter::schema(self, f) + } + + async fn next_tuple( + &mut self, + f: impl FnOnce(&SchemaView<'_, '_>, &mut ResultRow<'_, '_>) -> R + MaybeSend, + ) -> Result, DatabaseError> { + SessionIter::next_tuple(self, f).await + } + + async fn done(self) -> Result<(), DatabaseError> { + SessionIter::done(self).await + } +} + +#[cfg(all(test, feature = "parser", not(target_arch = "wasm32")))] +#[maybe_async] +mod tests { + use crate::db::{DataBaseBuilder, Database, DatabaseError, Session, Statement}; + use crate::dialect::SqlDialect; + use crate::parser::generic::SqlParser; + use crate::storage::Storage; + use sqlparser::dialect::GenericDialect; + + #[derive(Debug)] + struct SessionDialect; + + impl SqlDialect for SessionDialect { + fn name(&self) -> &str { + "test_session" + } + + fn parse(&self, sql: &str) -> Result, DatabaseError> { + SqlParser::new(&GenericDialect {}) + .with_set_autocommit() + .parse(sql) + } + + fn begin_commits_active_transaction(&self) -> bool { + true + } + } + + async fn exec( + session: &mut Session<'_, S, D>, + sql: &str, + ) -> Result<(), DatabaseError> { + session.run(sql).await?.done().await + } + + async fn count(db: &Database) -> Result { + let mut iter = db.run("select id from t1").await?; + let mut rows = 0; + while iter.next_tuple(|_, _| ()).await?.is_some() { + rows += 1; + } + iter.done().await?; + Ok(rows) + } + + #[test] + async fn generic_session_rejects_nested_begin_and_autocommit() -> Result<(), DatabaseError> { + let mut db = DataBaseBuilder::path(".").build_in_memory().await?; + db.ddl("create table t1 (id int primary key)").await?; + let mut session = db.session(); + + assert!(exec(&mut session, "set autocommit = 0").await.is_err()); + exec(&mut session, "begin").await?; + exec(&mut session, "insert into t1 values (1)").await?; + assert!(exec(&mut session, "begin").await.is_err()); + assert!(session.in_transaction()); + exec(&mut session, "commit").await?; + drop(session); + assert_eq!(count(&db).await?, 1); + + Ok(()) + } + + #[test] + async fn dialect_session_hooks() -> Result<(), DatabaseError> { + let mut db = DataBaseBuilder::path(".") + .dialect(SessionDialect) + .build_in_memory() + .await?; + db.ddl("create table t1 (id int primary key)").await?; + let mut session = db.session(); + + exec(&mut session, "begin").await?; + exec(&mut session, "insert into t1 values (1)").await?; + exec(&mut session, "begin").await?; + assert!(session.in_transaction()); + exec(&mut session, "commit").await?; + + exec(&mut session, "set autocommit = 0").await?; + assert!(!session.autocommit()); + exec(&mut session, "insert into t1 values (2)").await?; + assert!(session.in_transaction()); + exec(&mut session, "set autocommit = 1").await?; + assert!(!session.in_transaction()); + drop(session); + assert_eq!(count(&db).await?, 2); + + Ok(()) + } +} diff --git a/src/dialect/mod.rs b/src/dialect/mod.rs index d8c48241..575e47d3 100644 --- a/src/dialect/mod.rs +++ b/src/dialect/mod.rs @@ -60,6 +60,15 @@ pub trait SqlDialect: Debug + Send + Sync + 'static { fn boolean_text(&self, _value: bool) -> Option<&'static str> { None } + + /// Whether `BEGIN` in a [`Session`](crate::db::Session) that already has a transaction + /// open commits that transaction and opens a new one. + /// + /// The default implementation returns `false`, which rejects such a `BEGIN` and leaves the + /// open transaction as it was. + fn begin_commits_active_transaction(&self) -> bool { + false + } } /// Standard SQL behavior with no customizations; the default dialect. @@ -206,6 +215,10 @@ impl SqlDialect for DynDialect { fn boolean_text(&self, value: bool) -> Option<&'static str> { self.current().boolean_text(value) } + + fn begin_commits_active_transaction(&self) -> bool { + self.current().begin_commits_active_transaction() + } } #[cfg(all(test, feature = "parser", not(target_arch = "wasm32")))] diff --git a/src/parser/generic/mod.rs b/src/parser/generic/mod.rs index 254b4490..52feb67a 100644 --- a/src/parser/generic/mod.rs +++ b/src/parser/generic/mod.rs @@ -37,6 +37,7 @@ pub struct SqlParser<'a> { dialect: &'a dyn SqlParserDialect, recursion_limit: Option, types: &'a dyn DataTypeMapper, + set_autocommit: bool, } impl<'a> SqlParser<'a> { @@ -46,6 +47,7 @@ impl<'a> SqlParser<'a> { dialect, recursion_limit: None, types: &(), + set_autocommit: false, } } @@ -61,12 +63,22 @@ impl<'a> SqlParser<'a> { self } + /// Accepts `SET autocommit = 0 | 1` (or `ON`/`OFF`, `TRUE`/`FALSE`), which is rejected by + /// default like any other `SET`. + pub fn with_set_autocommit(mut self) -> Self { + self.set_autocommit = true; + self + } + pub fn parse(&self, sql: &str) -> Result, DatabaseError> { let mut parser = Parser::new(self.dialect); if let Some(limit) = self.recursion_limit { parser = parser.with_recursion_limit(limit); } - let lower = Lower { types: self.types }; + let lower = Lower { + types: self.types, + set_autocommit: self.set_autocommit, + }; parser .try_with_sql(sql)? .parse_statements()? @@ -95,6 +107,7 @@ pub fn parse_sql>(sql: S) -> Result, DatabaseError> /// Converts sqlparser statements into KiteSQL statements. struct Lower<'a> { types: &'a dyn DataTypeMapper, + set_autocommit: bool, } impl Lower<'_> { diff --git a/src/parser/generic/statement.rs b/src/parser/generic/statement.rs index 924e6099..5050bd90 100644 --- a/src/parser/generic/statement.rs +++ b/src/parser/generic/statement.rs @@ -17,10 +17,10 @@ use crate::ast; use crate::errors::DatabaseError; use sqlparser::ast::{ AlterColumnOperation, AlterTableOperation, Assignment, AssignmentTarget, ColumnDef, - ColumnOption, CopyOption, CopySource, CopyTarget, CreateIndex, CreateTable, DescribeAlias, - Expr, FromTable, FunctionArg, FunctionArgExpr, FunctionArguments, Ident, IndexColumn, - IndexOption, IndexType, Insert, NullsDistinctOption, ObjectNamePart, ObjectType, OnInsert, - Spanned, SqliteOnConflict, Statement, TableConstraint, TableFactor, TableObject, + ColumnOption, ContextModifier, CopyOption, CopySource, CopyTarget, CreateIndex, CreateTable, + DescribeAlias, Expr, FromTable, FunctionArg, FunctionArgExpr, FunctionArguments, Ident, + IndexColumn, IndexOption, IndexType, Insert, NullsDistinctOption, ObjectNamePart, ObjectType, + OnInsert, Set, Spanned, SqliteOnConflict, Statement, TableConstraint, TableFactor, TableObject, TableWithJoins, Value, }; @@ -167,6 +167,32 @@ impl Lower<'_> { }, Statement::ShowTables { .. } => ast::Statement::ShowTables, Statement::ShowViews { .. } => ast::Statement::ShowViews, + Statement::StartTransaction { + modes, + modifier: None, + statements, + exception: None, + .. + } if modes.is_empty() && statements.is_empty() => ast::Statement::StartTransaction, + Statement::Commit { + chain: false, + end: false, + modifier: None, + } => ast::Statement::Commit, + Statement::Rollback { + chain: false, + savepoint: None, + } => ast::Statement::Rollback, + Statement::Set(Set::SingleAssignment { + scope: None | Some(ContextModifier::Session), + hivevar: false, + variable, + values, + }) if self.set_autocommit + && variable.to_string().eq_ignore_ascii_case("autocommit") => + { + ast::Statement::SetAutocommit(autocommit_value(&values)?) + } statement => return Err(unsupported(statement.to_string())), }) } @@ -556,6 +582,21 @@ fn copy_format(options: Vec) -> Result Result { + match values { + [Expr::Value(value)] => match &value.value { + Value::Number(n, _) if n == "0" => Some(false), + Value::Number(n, _) if n == "1" => Some(true), + Value::Boolean(value) => Some(*value), + _ => None, + }, + [Expr::Identifier(ident)] if ident.value.eq_ignore_ascii_case("on") => Some(true), + [Expr::Identifier(ident)] if ident.value.eq_ignore_ascii_case("off") => Some(false), + _ => None, + } + .ok_or_else(|| unsupported("autocommit must be 0, 1, ON or OFF")) +} + // GRCOV_EXCL_START #[cfg(test)] mod tests { @@ -607,9 +648,12 @@ mod tests { drop_behavior: None, }; assert_unsupported( - Lower { types: &() } - .alter_table_operation(operation) - .unwrap_err(), + Lower { + types: &(), + set_autocommit: false, + } + .alter_table_operation(operation) + .unwrap_err(), "only dropping a single column", ); } diff --git a/src/parser/sqlite/statement.rs b/src/parser/sqlite/statement.rs index f58787a4..f04bb42f 100644 --- a/src/parser/sqlite/statement.rs +++ b/src/parser/sqlite/statement.rs @@ -19,7 +19,7 @@ use crate::ast; use crate::errors::DatabaseError; use sqlite3_parser::ast::{ AlterTableBody, Cmd, ColumnConstraint, ColumnDefinition, CreateTableBody, Expr, InsertBody, - QualifiedName, ResolveType, SortOrder, SortedColumn, Stmt, TableConstraint, + QualifiedName, ResolveType, SortOrder, SortedColumn, Stmt, TableConstraint, TransactionType, }; pub(super) fn cmd(cmd: &Cmd<'_>) -> Result { @@ -239,6 +239,14 @@ fn statement(stmt: &Stmt<'_>, cmd: &Cmd<'_>) -> Result return Err(unsupported("ANALYZE without table is not supported")), + Stmt::Begin(None | Some(TransactionType::Deferred), None) => { + ast::Statement::StartTransaction + } + Stmt::Commit(None) => ast::Statement::Commit, + Stmt::Rollback { + tx_name: None, + savepoint_name: None, + } => ast::Statement::Rollback, _ => return Err(unsupported(cmd.to_string())), }) }