diff --git a/Cargo.lock b/Cargo.lock index 369e66317..10e90ff6e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1066,6 +1066,12 @@ dependencies = [ "tokio", ] +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + [[package]] name = "fastant" version = "0.1.11" @@ -2011,6 +2017,7 @@ dependencies = [ "serde_json", "slatedb", "sqlite", + "sqlite3-parser", "sqlparser", "tempfile", "tokio", @@ -2337,7 +2344,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -2885,7 +2892,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -3287,7 +3294,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -3657,7 +3664,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -3679,6 +3686,21 @@ dependencies = [ "sqlite3-sys", ] +[[package]] +name = "sqlite3-parser" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbb44bfd84bfd1bde5ee215dd0b27d10c3c601a1b7cf03a91c7d6f607f2a10f7" +dependencies = [ + "bitflags 2.13.2", + "bumpalo", + "cc", + "fallible-iterator", + "indexmap", + "log", + "memchr", +] + [[package]] name = "sqlite3-src" version = "0.6.1" diff --git a/Cargo.toml b/Cargo.toml index f1487712a..d4cee76a6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,6 +31,7 @@ decimal = ["dep:rust_decimal"] macros = [] orm = ["macros"] parser = ["dep:sqlparser"] +sqlite-parser = ["dep:sqlite3-parser"] rocksdb = ["dep:rocksdb"] unsafe_txdb_checkpoint = ["rocksdb"] lmdb = ["dep:lmdb", "dep:lmdb-sys"] @@ -86,6 +87,7 @@ csv = { version = "1", optional = true } pyo3 = { version = "0.23", features = ["auto-initialize"], optional = true } rust_decimal = { version = "1", default-features = false, features = ["std"], optional = true } sqlparser = { version = "0.61", default-features = false, features = ["std"], optional = true } +sqlite3-parser = { version = "0.17", optional = true } [target.'cfg(unix)'.dev-dependencies] pprof = { version = "0.15", features = ["flamegraph", "criterion"] } diff --git a/Makefile b/Makefile index abc2f1b32..2d77a2a90 100644 --- a/Makefile +++ b/Makefile @@ -5,9 +5,9 @@ WASM_PACK ?= wasm-pack SQLLOGIC_PATH ?= tests/slt/**/*.slt SQLITE_LOGIC_PATH ?= tests/kitesql-testing/data/sqlite/**/*.slt # Every feature except `async`, which excludes the sync storages and bindings. -SYNC_FEATURES ?= time,copy,decimal,macros,orm,parser,rocksdb,unsafe_txdb_checkpoint,lmdb,pprof,python,shell,spill,wasm +SYNC_FEATURES ?= time,copy,decimal,macros,orm,parser,sqlite-parser,rocksdb,unsafe_txdb_checkpoint,lmdb,pprof,python,shell,spill,wasm # The async path with every feature it supports. -ASYNC_FEATURES ?= async,time,copy,decimal,macros,orm,parser,spill +ASYNC_FEATURES ?= async,time,copy,decimal,macros,orm,parser,sqlite-parser,spill SQLITE_LOGIC_ARGS ?= PYO3_PYTHON ?= /usr/bin/python3.12 TPCC_MEASURE_TIME ?= 15 @@ -48,7 +48,7 @@ COVERAGE_REPORT_ARGS ?= --llvm --ignore-not-existing --keep-only 'src/**' --igno ## Run default Rust tests in the current environment (non-WASM). test: - $(CARGO) test --all --features spill + $(CARGO) test --all --features spill,sqlite-parser ## Run the same unit tests through the async path (`async` feature, SlateDB on an in-memory object store). test-async: diff --git a/docs/features.md b/docs/features.md index 93f437c9b..4218a8a00 100644 --- a/docs/features.md +++ b/docs/features.md @@ -354,10 +354,12 @@ If `unsafe_txdb_checkpoint` is not enabled, `build_rocksdb()` returns an explici ### Custom SQL Dialects -KiteSQL supports pluggable SQL dialects through the `SqlDialect` trait. This allows you to customize parsing, data type mapping, and SQL rewriting. A `Database` parses and binds statements with its current dialect. The default is `GenericSqlDialect`, the standard behaviour. +KiteSQL supports pluggable SQL dialects through the `SqlDialect` trait. A dialect parses SQL text into KiteSQL's own syntax tree (`kite_sql::ast`), so it may use any parser, and customizes how statements are typed. A `Database` parses and binds statements with its current dialect. The default is `GenericSqlDialect`, the standard behaviour, which parses with sqlparser and needs the `parser` feature. #### Using a Custom Dialect +With the `sqlite-parser` feature, `SqliteDialect` parses SQLite syntax with SQLite's own grammar (`sqlite3-parser`); statements still run with KiteSQL's semantics, and SQLite syntax KiteSQL does not support is rejected. + Pass a dialect type to the builder when it is fixed at compile time: ```rust @@ -387,34 +389,23 @@ After opening a database with `DynDialect`, use `db.switch_dialect(name)` with m #### Implementing a Custom Dialect -Implement the `SqlDialect` trait to customize behavior: +Implement the `SqlDialect` trait to customize behavior. A dialect built on sqlparser can parse with `kite_sql::parser::generic::SqlParser`, map its own data types through `DataTypeMapper`, and rewrite the returned statements: ```rust +use kite_sql::ast::Statement; use kite_sql::dialect::SqlDialect; use kite_sql::errors::DatabaseError; +use kite_sql::parser::generic::{DataTypeMapper, SqlParser}; use kite_sql::types::LogicalType; -use sqlparser::ast::{DataType, Statement}; -use sqlparser::dialect::{Dialect as SqlParserDialect, GenericDialect}; +use sqlparser::ast::DataType; +use sqlparser::dialect::GenericDialect; #[derive(Debug)] -struct MyDialect { - parser: GenericDialect, -} - -impl SqlDialect for MyDialect { - fn name(&self) -> &str { - "my_dialect" - } - - fn parser_dialect(&self) -> &dyn SqlParserDialect { - &self.parser - } +struct MyDialect; - // Optional: map custom data types - fn map_data_type( - &self, - data_type: &DataType, - ) -> Option> { +// Optional: map custom data types +impl DataTypeMapper for MyDialect { + fn map_data_type(&self, data_type: &DataType) -> Option> { match data_type { DataType::Custom(name, _) if name.to_string() == "MY_TYPE" => { Some(Ok(LogicalType::Integer)) @@ -422,11 +413,19 @@ impl SqlDialect for MyDialect { _ => None, } } +} + +impl SqlDialect for MyDialect { + fn name(&self) -> &str { + "my_dialect" + } - // Optional: rewrite SQL statements before execution - fn rewrite(&self, stmt: &mut Statement) -> Result<(), DatabaseError> { - // Modify the statement if needed - Ok(()) + fn parse(&self, sql: &str) -> Result, DatabaseError> { + let statements = SqlParser::new(&GenericDialect {}) + .with_type_mapper(self) + .parse(sql)?; + // Optional: rewrite the statements before they are bound + Ok(statements) } } ``` @@ -434,11 +433,10 @@ impl SqlDialect for MyDialect { The `SqlDialect` trait methods: - `name()` — Returns the dialect's unique identifier -- `parser_dialect()` — Returns the sqlparser dialect for parsing SQL -- `map_data_type()` — Optional hook to map SQL data types in expressions (`CAST`, typed literals) to KiteSQL's `LogicalType` -- `map_column_type()` — Optional hook to map the data types of column definitions; defaults to `map_data_type()` -- `rewrite()` — Optional hook to transform each parsed statement before it is bound +- `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'`) +`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()`. + By default, the `GenericSqlDialect` is used, which provides standard SQL behavior with no custom transformations. diff --git a/fuzz/fuzz_targets/sql_exec.rs b/fuzz/fuzz_targets/sql_exec.rs index 50ec7e317..a64f4492a 100644 --- a/fuzz/fuzz_targets/sql_exec.rs +++ b/fuzz/fuzz_targets/sql_exec.rs @@ -152,10 +152,8 @@ fn run_one(db: &mut Database, sql: &str) { let _ = db.ddl(sql); } CommandType::Analyze => { - if let Statement::Analyze(analyze) = statement { - if let Some(table_name) = analyze.table_name.as_ref() { - let _ = db.analyze(table_name.to_string()); - } + if let Statement::Analyze { table_name } = statement { + let _ = db.analyze(table_name.to_string()); } } _ => { diff --git a/src/ast/expr.rs b/src/ast/expr.rs new file mode 100644 index 000000000..edea4f2ec --- /dev/null +++ b/src/ast/expr.rs @@ -0,0 +1,208 @@ +// 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::{Ident, ObjectName, Query, Span}; +use crate::expression::{BinaryOperator, TrimWhereField, UnaryOperator}; +use crate::types::LogicalType; + +/// A literal as written. +#[derive(Debug, Clone, PartialEq)] +pub enum Value { + /// Digits as written, so the binder picks the narrowest type that holds them. + Number(String), + String(String), + /// The digits of `X'..'`. + HexString(String), + Boolean(bool), + Null, + /// A parameter such as `$1`. + Placeholder(String), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct ValueWithSpan { + pub value: Value, + pub span: Span, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum Expr { + Identifier(Ident), + /// `a.b` + CompoundIdentifier(Vec), + Value(ValueWithSpan), + /// `type 'text'`, such as `DATE '2024-01-01'`. + TypedString { + data_type: LogicalType, + value: String, + span: Span, + }, + BinaryOp { + left: Box, + op: BinaryOperator, + right: Box, + }, + UnaryOp { + op: UnaryOperator, + expr: Box, + }, + Nested(Box), + Like { + negated: bool, + expr: Box, + pattern: Box, + escape_char: Option, + }, + IsNull(Box), + IsNotNull(Box), + InList { + expr: Box, + list: Vec, + negated: bool, + }, + Between { + expr: Box, + negated: bool, + low: Box, + high: Box, + }, + Cast { + expr: Box, + data_type: LogicalType, + }, + Substring { + expr: Box, + from: Option>, + r#for: Option>, + }, + Position { + expr: Box, + r#in: Box, + }, + Trim { + expr: Box, + trim_what: Option>, + trim_where: Option, + }, + Function(Function), + Case { + operand: Option>, + /// `WHEN condition THEN result` pairs. + conditions: Vec<(Expr, Expr)>, + else_result: Option>, + }, + Tuple(Vec), + Exists { + subquery: Box, + negated: bool, + }, + Subquery(Box), + InSubquery { + expr: Box, + subquery: Box, + negated: bool, + }, + /// `left op ANY (subquery)` + AnyOp { + left: Box, + compare_op: BinaryOperator, + subquery: Box, + }, + /// `left op ALL (subquery)` + AllOp { + left: Box, + compare_op: BinaryOperator, + subquery: Box, + }, +} + +/// A function call; a call with `over` is a window function. +#[derive(Debug, Clone, PartialEq)] +pub struct Function { + pub name: ObjectName, + pub args: Vec, + pub distinct: bool, + pub over: Option, + pub span: Span, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum FunctionArg { + Expr(Expr), + /// `*`, as in `count(*)`. + Wildcard, +} + +/// An inline window, `OVER (PARTITION BY .. ORDER BY ..)`. +#[derive(Debug, Clone, PartialEq)] +pub struct WindowSpec { + pub partition_by: Vec, + pub order_by: Vec, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct OrderByExpr { + pub expr: Expr, + /// `None` when neither `ASC` nor `DESC` is written. + pub asc: Option, + pub nulls_first: Option, +} + +impl Expr { + /// The source range of this expression, from the spans of the names and literals in it. + pub fn span(&self) -> Span { + let union = |exprs: &mut dyn Iterator| { + exprs.fold(Span::empty(), |span, expr| span.union(expr.span())) + }; + match self { + Expr::Identifier(ident) => ident.span, + Expr::CompoundIdentifier(idents) => idents + .iter() + .fold(Span::empty(), |span, ident| span.union(ident.span)), + Expr::Value(value) => value.span, + Expr::TypedString { span, .. } => *span, + Expr::Function(function) => function.span, + Expr::BinaryOp { left, right, .. } => left.span().union(right.span()), + Expr::Like { expr, pattern, .. } => expr.span().union(pattern.span()), + Expr::Between { + expr, low, high, .. + } => union(&mut [expr, low, high].into_iter().map(AsRef::as_ref)), + Expr::InList { expr, list, .. } => expr.span().union(union(&mut list.iter())), + Expr::Tuple(exprs) => union(&mut exprs.iter()), + Expr::Case { + operand, + conditions, + else_result, + } => union( + &mut operand + .iter() + .map(AsRef::as_ref) + .chain(conditions.iter().flat_map(|(when, then)| [when, then])) + .chain(else_result.iter().map(AsRef::as_ref)), + ), + Expr::UnaryOp { expr, .. } + | Expr::Nested(expr) + | Expr::IsNull(expr) + | Expr::IsNotNull(expr) + | Expr::Cast { expr, .. } + | Expr::Substring { expr, .. } + | Expr::Position { expr, .. } + | Expr::Trim { expr, .. } + | Expr::InSubquery { expr, .. } + | Expr::AnyOp { left: expr, .. } + | Expr::AllOp { left: expr, .. } => expr.span(), + Expr::Exists { .. } | Expr::Subquery(_) => Span::empty(), + } + } +} diff --git a/src/ast/mod.rs b/src/ast/mod.rs new file mode 100644 index 000000000..5ea2e4742 --- /dev/null +++ b/src/ast/mod.rs @@ -0,0 +1,200 @@ +// 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. + +//! KiteSQL's SQL syntax tree. +//! +//! A [`SqlDialect`](crate::dialect::SqlDialect) parses SQL text into these statements, and +//! the binder turns them into logical plans. The tree holds only the syntax KiteSQL +//! supports: a dialect rejects anything else while building it. Type names are already +//! resolved to [`LogicalType`](crate::types::LogicalType)s. + +mod expr; +mod query; +mod statement; + +pub use expr::*; +pub use query::*; +pub use statement::*; + +use crate::errors::{DatabaseError, SqlErrorSpan}; +use std::fmt; + +/// A position in the SQL text; lines and columns start at 1, and `0` means unknown. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)] +pub struct Location { + pub line: u64, + pub column: u64, +} + +/// The source range of a syntax node, used to point errors at the SQL text. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)] +pub struct Span { + pub start: Location, + pub end: Location, +} + +impl Span { + pub const fn new(start: Location, end: Location) -> Self { + Self { start, end } + } + + /// A span that points nowhere. + pub const fn empty() -> Self { + Self { + start: Location { line: 0, column: 0 }, + end: Location { line: 0, column: 0 }, + } + } + + pub fn is_empty(&self) -> bool { + *self == Self::empty() + } + + /// The smallest span covering both spans; an empty span covers nothing. + pub fn union(self, other: Self) -> Self { + let key = |location: Location| (location.line, location.column); + match (self.is_empty(), other.is_empty()) { + (true, _) => other, + (_, true) => self, + _ => Self { + start: std::cmp::min_by_key(self.start, other.start, |l| key(*l)), + end: std::cmp::max_by_key(self.end, other.end, |l| key(*l)), + }, + } + } + + fn sql_error_span(self) -> Option { + if self.is_empty() { + return None; + } + let start = self.start.column as usize; + let mut end = self.end.column as usize; + if end <= start { + end = start.saturating_add(1); + } + Some(SqlErrorSpan { + start, + end, + line: self.start.line as usize, + highlight: None, + }) + } +} + +/// Points `err` at `span` unless it already points somewhere. +pub(crate) fn attach_span_if_absent(err: DatabaseError, span: Span) -> DatabaseError { + if err.sql_error_span().is_some() { + return err; + } + match span.sql_error_span() { + Some(span) => err.with_span(span), + None => err, + } +} + +/// An identifier as written; the binder decides how its case folds. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct Ident { + pub value: String, + /// The opening quote, if the identifier was quoted. + pub quote_style: Option, + pub span: Span, +} + +impl Ident { + pub fn new(value: impl Into) -> Self { + Self { + value: value.into(), + quote_style: None, + span: Span::empty(), + } + } +} + +impl fmt::Display for Ident { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.quote_style { + Some(quote) => { + let close = if quote == '[' { ']' } else { quote }; + write!(f, "{quote}{}{close}", self.value) + } + None => f.write_str(&self.value), + } + } +} + +/// A possibly qualified name, such as `table` or `schema.table`. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct ObjectName(pub Vec); + +impl ObjectName { + pub fn span(&self) -> Span { + self.0 + .iter() + .fold(Span::empty(), |span, ident| span.union(ident.span)) + } +} + +impl fmt::Display for ObjectName { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + for (i, ident) in self.0.iter().enumerate() { + if i > 0 { + f.write_str(".")?; + } + write!(f, "{ident}")?; + } + Ok(()) + } +} + +// GRCOV_EXCL_START +#[cfg(test)] +mod tests { + use super::{attach_span_if_absent, Location, Span}; + use crate::errors::{DatabaseError, SqlErrorSpan}; + + #[test] + fn attach_span_if_absent_keeps_an_existing_span() { + let at = |line, column| Location { line, column }; + let err = attach_span_if_absent( + DatabaseError::invalid_column("bad"), + Span::new(at(3, 5), at(3, 5)), + ); + assert_eq!( + err.sql_error_span(), + Some(&SqlErrorSpan { + start: 5, + end: 6, + line: 3, + highlight: None, + }) + ); + + let existing = SqlErrorSpan { + start: 1, + end: 2, + line: 1, + highlight: None, + }; + let err = attach_span_if_absent( + DatabaseError::invalid_column("bad").with_span(existing.clone()), + Span::new(at(4, 8), at(4, 9)), + ); + assert_eq!(err.sql_error_span(), Some(&existing)); + + let err = attach_span_if_absent(DatabaseError::invalid_column("bad"), Span::empty()); + assert_eq!(err.sql_error_span(), None); + } +} +// GRCOV_EXCL_STOP diff --git a/src/ast/query.rs b/src/ast/query.rs new file mode 100644 index 000000000..90c9ae2b0 --- /dev/null +++ b/src/ast/query.rs @@ -0,0 +1,146 @@ +// 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::{Expr, Ident, ObjectName, OrderByExpr}; + +#[derive(Debug, Clone, PartialEq)] +pub struct Query { + pub with: Option, + pub body: Box, + pub order_by: Option>, + pub limit: Option, + /// A locking read, such as `FOR UPDATE`, which needs a write transaction. + pub for_update: bool, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct With { + pub recursive: bool, + pub cte_tables: Vec, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Cte { + pub alias: TableAlias, + pub query: Box, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Limit { + pub limit: Option, + pub offset: Option, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum SetExpr { + Select(Box