sqlparser/
lib.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! # SQL Parser for Rust
19//!
20//! This crate provides an ANSI:SQL 2011 lexer and parser that can parse SQL
21//! into an Abstract Syntax Tree ([`AST`]). See the [sqlparser crates.io page]
22//! for more information.
23//!
24//! For more information:
25//! 1. [`Parser::parse_sql`] and [`Parser::new`] for the Parsing API
26//! 2. [`ast`] for the AST structure
27//! 3. [`Dialect`] for supported SQL dialects
28//! 4. [`Spanned`] for source text locations (see "Source Spans" below for details)
29//!
30//! [`Spanned`]: ast::Spanned
31//!
32//! # Example parsing SQL text
33//!
34//! ```
35//! use sqlparser::dialect::GenericDialect;
36//! use sqlparser::parser::Parser;
37//!
38//! let dialect = GenericDialect {}; // or AnsiDialect
39//!
40//! let sql = "SELECT a, b, 123, myfunc(b) \
41//!            FROM table_1 \
42//!            WHERE a > b AND b < 100 \
43//!            ORDER BY a DESC, b";
44//!
45//! let ast = Parser::parse_sql(&dialect, sql).unwrap();
46//!
47//! println!("AST: {:?}", ast);
48//! ```
49//!
50//! # Creating SQL text from AST
51//!
52//! This crate allows users to recover the original SQL text (with comments
53//! removed, normalized whitespace and identifier capitalization), which is
54//! useful for tools that analyze and manipulate SQL.
55//!
56//! ```
57//! # use sqlparser::dialect::GenericDialect;
58//! # use sqlparser::parser::Parser;
59//! let sql = "SELECT a FROM table_1";
60//!
61//! // parse to a Vec<Statement>
62//! let ast = Parser::parse_sql(&GenericDialect, sql).unwrap();
63//!
64//! // The original SQL text can be generated from the AST
65//! assert_eq!(ast[0].to_string(), sql);
66//! ```
67//!
68//! # Pretty Printing
69//!
70//! SQL statements can be pretty-printed with proper indentation and line breaks using the alternate flag (`{:#}`):
71//!
72//! ```
73//! # use sqlparser::dialect::GenericDialect;
74//! # use sqlparser::parser::Parser;
75//! let sql = "SELECT a, b FROM table_1";
76//! let ast = Parser::parse_sql(&GenericDialect, sql).unwrap();
77//!
78//! // Pretty print with indentation and line breaks
79//! let pretty_sql = format!("{:#}", ast[0]);
80//! assert_eq!(pretty_sql, r#"
81//! SELECT
82//!   a,
83//!   b
84//! FROM
85//!   table_1
86//! "#.trim());
87//! ```
88//! [sqlparser crates.io page]: https://crates.io/crates/sqlparser
89//! [`Parser::parse_sql`]: crate::parser::Parser::parse_sql
90//! [`Parser::new`]: crate::parser::Parser::new
91//! [`AST`]: crate::ast
92//! [`ast`]: crate::ast
93//! [`Dialect`]: crate::dialect::Dialect
94//!
95//! # Source Spans
96//!
97//! Starting with version  `0.53.0` sqlparser introduced source spans to the
98//! AST. This feature provides source information for syntax errors, enabling
99//! better error messages. See [issue #1548] for more information and the
100//! [`Spanned`] trait to access the spans.
101//!
102//! [issue #1548]: https://github.com/apache/datafusion-sqlparser-rs/issues/1548
103//! [`Spanned`]: ast::Spanned
104//!
105//! ## Migration Guide
106//!
107//! For the next few releases, we will be incrementally adding source spans to the
108//! AST nodes, trying to minimize the impact on existing users. Some breaking
109//! changes are inevitable, and the following is a summary of the changes:
110//!
111//! #### New fields for spans (must be added to any existing pattern matches)
112//!
113//! The primary change is that new fields will be added to AST nodes to store the source `Span` or `TokenWithLocation`.
114//!
115//! This will require
116//! 1. Adding new fields to existing pattern matches.
117//! 2. Filling in the proper span information when constructing AST nodes.
118//!
119//! For example, since `Ident` now stores a `Span`, to construct an `Ident` you
120//! must provide now provide one:
121//!
122//! Previously:
123//! ```text
124//! # use sqlparser::ast::Ident;
125//! Ident {
126//!     value: "name".into(),
127//!     quote_style: None,
128//! }
129//! ```
130//! Now
131//! ```rust
132//! # use sqlparser::ast::Ident;
133//! # use sqlparser::tokenizer::Span;
134//! Ident {
135//!     value: "name".into(),
136//!     quote_style: None,
137//!     span: Span::empty(),
138//! };
139//! ```
140//!
141//! Similarly, when pattern matching on `Ident`, you must now account for the
142//! `span` field.
143//!
144//! #### Misc.
145//! - [`TokenWithLocation`] stores a full `Span`, rather than just a source location.
146//!   Users relying on `token.location` should use `token.location.start` instead.
147//!
148//![`TokenWithLocation`]: tokenizer::TokenWithLocation
149
150#![cfg_attr(not(feature = "std"), no_std)]
151#![allow(clippy::upper_case_acronyms)]
152// Permit large enum variants to keep a unified, expressive AST.
153// Splitting complex nodes (expressions, statements, types) into separate types
154// would bloat the API and hide intent. Extra memory is a worthwhile tradeoff.
155#![allow(clippy::large_enum_variant)]
156
157// Allow proc-macros to find this crate
158extern crate self as sqlparser;
159
160#[cfg(not(feature = "std"))]
161extern crate alloc;
162
163#[macro_use]
164#[cfg(test)]
165extern crate pretty_assertions;
166
167pub mod ast;
168#[macro_use]
169pub mod dialect;
170mod display_utils;
171pub mod keywords;
172pub mod parser;
173pub mod tokenizer;
174
175#[doc(hidden)]
176// This is required to make utilities accessible by both the crate-internal
177// unit-tests and by the integration tests <https://stackoverflow.com/a/44541071/1026>
178// External users are not supposed to rely on this module.
179pub mod test_utils;