Crate sqltk

Source
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

  1. Full coverage of all AST node types from sqltk-parser (including all field types and container types (Vec, Option & Box)) and terminal nodes.

  2. 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§

parser

Structs§

NodeKey
Acts as a type-erased proxy for any type bound by 'static.
NodePath

Enums§

Break
Type used to signal abnormal control flow from a Visitor during AST traversal.

Traits§

AsNodeKey
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 a ControlFlow<Break<E2>, ()>.
into_control_flow
Converts a Result<(), E> into a ControlFlow<Break<E>, ()>.
into_result
Converts a ControlFlow<Break<E>, ()> into a Result<(), E>.
visit_expressions
visit_relations
visit_statements