Expand description
This crate implements an enhanced Visitor implementation suitable for semantic analysis of SQL.
The AST is provided by the sqlparser crate - which this crate re-exports.
§Key features
-
Full coverage of all AST node types from
sqlparser(including all field types and container types (Vec,Option&Box)) and terminal nodes. -
Support for annotating AST nodes with user-defined metadata during traversal (see: [
sqltk-analysis]) -
An API for composing
Visitorimplementations to facilitate complex SQL analysis scenarios made from small, unit testable pieces (see: [sqltk-analysis]).
§Installation
$ cargo install cargo-expand
$ cargo add sqltk
# optional:
$ cargo add sqltk-analysis§Example
Count the number of Expr nodes in an AST.
use std::cell::Cell;
use std::convert::Infallible;
use std::ops::ControlFlow;
use sqltk::{Visitor, Visitable, into_result, Break};
use sqlparser::{ast::Expr, dialect::GenericDialect, parser::Parser};
let dialect = GenericDialect {};
let sql = "SELECT a, b, 123, myfunc(b) \
FROM table_1 \
WHERE a > b AND b < 100 \
ORDER BY a DESC, b";
let ast = Parser::parse_sql(&dialect, sql).unwrap();
struct CountOfExprNodes{ count: Cell<usize> };
impl<'ast> Visitor<'ast> for CountOfExprNodes {
type Error = Infallible;
fn enter<N: Visitable>(&mut self, node: &'ast N) -> ControlFlow<Break<Self::Error>> {
if let Some(expr) = node.downcast_ref::<Expr>() {
self.count.set(self.count.get() + 1);
}
ControlFlow::Continue(())
}
}
// The expressions are:
// In the SELECT projection: a, b, 123, myfunc(b), b
// In the WHERE clause: a, b, a > b, b, 100, b < 100, a > b AND b < 100
// In the ORDER BY clause: a, b
// Total: 14
let mut visitor = CountOfExprNodes{ count: Cell::new(0) };
match into_result(ast.accept(&mut visitor)) {
Ok(()) => assert_eq!(14, visitor.count.get()),
err => panic!("{:#?}", err)
};Enums§
- Type used to signal abnormal control flow from a
Visitorduring AST traversal.
Traits§
- Marker trait for AST nodes that are semantically interesting. Every type that implements
Visitableis semantically interesting except forBox<T: Visitable>andOption<T: Visitable> - Trait for producing a new AST node from an existing one by applying edits.
- Trait for applying a
Transformto an AST to produce an edited version. - Trait for types that can be traversed by a
Visitor. - Trait for types that can visit any
sqlparserAST node.
Functions§
- Converts a
ControlFlow<Break<E1>, ()>into aControlFlow<Break<E2>, ()>. - Converts a
Result<(), E>into aControlFlow<Break<E>, ()>. - Converts a
ControlFlow<Break<E>, ()>into aResult<(), E>.