Expand description
This crate implements an enhanced Visitor implementation suitable for semantic analysis of SQL.
The AST is provided by the sqltk-parser
crate - which this crate re-exports.
§Key features
-
Full coverage of all AST node types from
sqltk-parser
(including all field types and container types (Vec
,Option
&Box
)) and terminal nodes. -
Transform
trait methods do not receive a mutable node argument which means that non-mutable references AST nodes can be retained in your own data structures from previous analysis passes.
§Installation
$ cargo add sqltk
§Example
Count the number of Expr nodes in an AST.
use std::convert::Infallible;
use std::ops::ControlFlow;
use sqltk::{Visitor, Visitable, into_result, Break};
use sqltk_parser::{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: 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 += 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: 0 };
match into_result(ast.accept(&mut visitor)) {
Ok(()) => assert_eq!(14, visitor.count),
err => panic!("{:#?}", err)
};
Modules§
Structs§
Enums§
Traits§
- AsNode
Key - Transform
- Trait for producing a new AST node from an existing one by applying edits.
- Transformable
- Trait for applying a
Transform
to an AST to produce an edited version. - Visitable
- Trait for types that can be traversed by a
Visitor
. - Visitor
- Trait for types that can visit any
sqltk-parser
AST node.
Functions§
- convert_
control_ flow - Converts a
ControlFlow<Break<E1>, ()>
into aControlFlow<Break<E2>, ()>
. - into_
control_ flow - Converts a
Result<(), E>
into aControlFlow<Break<E>, ()>
. - into_
result - Converts a
ControlFlow<Break<E>, ()>
into aResult<(), E>
. - visit_
expressions - visit_
relations - visit_
statements