Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Spanned to retrieve source locations on AST nodes #1435

Merged
merged 38 commits into from
Nov 26, 2024
Merged
Show file tree
Hide file tree
Changes from 19 commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
1a77bac
feat(tokenizer): add source location spans to tokens
Nyrox Sep 16, 2024
d818012
feat: begin work on trait Spanned
Nyrox Sep 16, 2024
079a4e2
implement a bunch more stuff
Nyrox Sep 17, 2024
b97a781
Merge branch 'feat/ast-source-locations'
Nyrox Sep 17, 2024
df9ab1e
fix: restore old behaviour of location display
Nyrox Sep 17, 2024
b718c76
implement spans for eveeeeen more ast nodes
Nyrox Sep 17, 2024
8986a1e
feat: more ast nodes
Nyrox Sep 19, 2024
aeb4f3a
start working on better tests
Nyrox Sep 20, 2024
4de3209
feat: implement spans for Wildcard projections
Nyrox Sep 25, 2024
a04888a
make union_spans public
Nyrox Sep 26, 2024
1b2b03d
enable serde feat for spans and locations
Nyrox Sep 30, 2024
5f60bdc
feat: implement remaining ast nodes
Nyrox Oct 7, 2024
ea8a6b1
fix unused variable warnings
Nyrox Oct 8, 2024
6a9250a
undo parse_keyword signature change
Nyrox Oct 8, 2024
0804e99
fix: diverging hash and partialeq implementations
Nyrox Oct 8, 2024
eb9ff9a
Update src/ast/spans.rs
Nyrox Oct 9, 2024
a93cebc
improve docs & un-pub union_spans
Nyrox Oct 9, 2024
734264a
move union_spans to top of file
Nyrox Oct 9, 2024
441ceb1
replace old tests
Nyrox Oct 9, 2024
e6a4340
pr feedback
Nyrox Oct 11, 2024
16a3f2a
add small comment
Nyrox Oct 11, 2024
98b051d
refactor: rewrite all span implementations to pattern match exhaustiv…
Nyrox Oct 16, 2024
d76d1e0
for_clause is mssql, not mysql
Nyrox Oct 18, 2024
bf75fe4
Merge branch 'main' into main
Nyrox Oct 25, 2024
71c27ea
cargo fmt
Nyrox Oct 25, 2024
1353bf2
Merge remote-tracking branch 'apache/main'
Nyrox Nov 11, 2024
a31c6a6
lint & no-std
Nyrox Nov 12, 2024
ce8b35c
add IgnoreField helper
Nyrox Nov 12, 2024
2bb72a4
docs and fixes
Nyrox Nov 12, 2024
4dda1fe
fix: test failing
Nyrox Nov 12, 2024
3fa3766
pr feedback
Nyrox Nov 18, 2024
6bfe13f
rename ignore_field.rs -> attached_token.rs
Nyrox Nov 18, 2024
903f24a
pr feedback
Nyrox Nov 19, 2024
3989efe
add AttachedToken::empty
Nyrox Nov 19, 2024
b2b8795
Merge branch 'main' of https://github.com/apache/datafusion-sqlparser-rs
Nyrox Nov 19, 2024
1f3d514
Merge remote-tracking branch 'apache/main' into Nyrox/main
alamb Nov 24, 2024
23c4922
update test to avoid overflow
alamb Nov 24, 2024
b24c9fe
Merge branch 'main' of https://github.com/apache/datafusion-sqlparser-rs
Nyrox Nov 26, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 55 additions & 7 deletions src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ use serde::{Deserialize, Serialize};
#[cfg(feature = "visitor")]
use sqlparser_derive::{Visit, VisitMut};

use crate::tokenizer::{Span, TokenWithLocation};

pub use self::data_type::{
ArrayElemTypeDef, CharLengthUnits, CharacterLength, DataType, ExactNumberInfo,
StructBracketKind, TimezoneInfo,
Expand Down Expand Up @@ -79,6 +81,9 @@ mod dml;
pub mod helpers;
mod operator;
mod query;
mod spans;
pub use spans::Spanned;

mod trigger;
mod value;

Expand Down Expand Up @@ -123,7 +128,7 @@ where
}

/// An identifier, decomposed into its value or character data and the quote style.
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[derive(Debug, Clone, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct Ident {
Expand All @@ -132,8 +137,25 @@ pub struct Ident {
/// The starting quote if any. Valid quote characters are the single quote,
/// double quote, backtick, and opening square bracket.
pub quote_style: Option<char>,
/// The span of the identifier in the original SQL string.
pub span: Span,
}

impl PartialEq for Ident {
fn eq(&self, other: &Self) -> bool {
self.value == other.value && self.quote_style == other.quote_style
}
}

impl core::hash::Hash for Ident {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.value.hash(state);
self.quote_style.hash(state);
}
Nyrox marked this conversation as resolved.
Show resolved Hide resolved
}

impl Eq for Ident {}

impl Ident {
/// Create a new identifier with the given value and no quotes.
pub fn new<S>(value: S) -> Self
Expand All @@ -143,6 +165,7 @@ impl Ident {
Ident {
value: value.into(),
quote_style: None,
span: Span::empty(),
}
}

Expand All @@ -156,6 +179,30 @@ impl Ident {
Ident {
value: value.into(),
quote_style: Some(quote),
span: Span::empty(),
}
}

pub fn with_span<S>(span: Span, value: S) -> Self
where
S: Into<String>,
{
Ident {
value: value.into(),
quote_style: None,
span,
}
}

pub fn with_quote_and_span<S>(quote: char, span: Span, value: S) -> Self
where
S: Into<String>,
{
assert!(quote == '\'' || quote == '"' || quote == '`' || quote == '[');
iffyio marked this conversation as resolved.
Show resolved Hide resolved
Ident {
value: value.into(),
quote_style: Some(quote),
span,
}
}
}
Expand All @@ -165,6 +212,7 @@ impl From<&str> for Ident {
Ident {
value: value.to_string(),
quote_style: None,
span: Span::empty(),
}
}
}
Expand Down Expand Up @@ -881,10 +929,10 @@ pub enum Expr {
/// `<search modifier>`
opt_search_modifier: Option<SearchModifier>,
},
Wildcard,
Wildcard(TokenWithLocation),
Nyrox marked this conversation as resolved.
Show resolved Hide resolved
/// Qualified wildcard, e.g. `alias.*` or `schema.table.*`.
/// (Same caveats apply to `QualifiedWildcard` as to `Wildcard`.)
QualifiedWildcard(ObjectName),
QualifiedWildcard(ObjectName, TokenWithLocation),
Nyrox marked this conversation as resolved.
Show resolved Hide resolved
/// Some dialects support an older syntax for outer joins where columns are
/// marked with the `(+)` operator in the WHERE clause, for example:
///
Expand Down Expand Up @@ -1173,8 +1221,8 @@ impl fmt::Display for Expr {
Expr::MapAccess { column, keys } => {
write!(f, "{column}{}", display_separated(keys, ""))
}
Expr::Wildcard => f.write_str("*"),
Expr::QualifiedWildcard(prefix) => write!(f, "{}.*", prefix),
Expr::Wildcard(_) => f.write_str("*"),
Expr::QualifiedWildcard(prefix, _) => write!(f, "{}.*", prefix),
Expr::CompoundIdentifier(s) => write!(f, "{}", display_separated(s, ".")),
Expr::IsTrue(ast) => write!(f, "{ast} IS TRUE"),
Expr::IsNotTrue(ast) => write!(f, "{ast} IS NOT TRUE"),
Expand Down Expand Up @@ -5169,8 +5217,8 @@ pub enum FunctionArgExpr {
impl From<Expr> for FunctionArgExpr {
fn from(wildcard_expr: Expr) -> Self {
match wildcard_expr {
Expr::QualifiedWildcard(prefix) => Self::QualifiedWildcard(prefix),
Expr::Wildcard => Self::Wildcard,
Expr::QualifiedWildcard(prefix, _) => Self::QualifiedWildcard(prefix),
Expr::Wildcard(_) => Self::Wildcard,
expr => Self::Expr(expr),
}
}
Expand Down
26 changes: 24 additions & 2 deletions src/ast/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ use serde::{Deserialize, Serialize};
#[cfg(feature = "visitor")]
use sqlparser_derive::{Visit, VisitMut};

use crate::ast::*;
use crate::{
ast::*,
tokenizer::{Token, TokenWithLocation},
};

/// The most complete variant of a `SELECT` query expression, optionally
/// including `WITH`, `UNION` / other set operations, and `ORDER BY`.
Expand Down Expand Up @@ -271,6 +274,8 @@ impl fmt::Display for Table {
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct Select {
/// SELECT
pub select_token: TokenWithLocation,
pub distinct: Option<Distinct>,
/// MSSQL syntax: `TOP (<N>) [ PERCENT ] [ WITH TIES ]`
pub top: Option<Top>,
Expand Down Expand Up @@ -490,6 +495,7 @@ impl fmt::Display for NamedWindowDefinition {
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct With {
pub with_token: TokenWithLocation,
pub recursive: bool,
pub cte_tables: Vec<Cte>,
}
Expand Down Expand Up @@ -541,6 +547,8 @@ pub struct Cte {
pub query: Box<Query>,
pub from: Option<Ident>,
pub materialized: Option<CteAsMaterialized>,
// needed for accurate span reporting
Nyrox marked this conversation as resolved.
Show resolved Hide resolved
pub closing_paren_token: TokenWithLocation,
}

impl fmt::Display for Cte {
Expand Down Expand Up @@ -592,10 +600,11 @@ impl fmt::Display for IdentWithAlias {
}

/// Additional options for wildcards, e.g. Snowflake `EXCLUDE`/`RENAME` and Bigquery `EXCEPT`.
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Default)]
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct WildcardAdditionalOptions {
pub wildcard_token: TokenWithLocation,
/// `[ILIKE...]`.
/// Snowflake syntax: <https://docs.snowflake.com/en/sql-reference/sql/select#parameters>
pub opt_ilike: Option<IlikeSelectItem>,
Expand All @@ -613,6 +622,19 @@ pub struct WildcardAdditionalOptions {
pub opt_rename: Option<RenameSelectItem>,
}

impl Default for WildcardAdditionalOptions {
fn default() -> Self {
Self {
wildcard_token: TokenWithLocation::wrap(Token::Mul),
opt_ilike: None,
opt_exclude: None,
opt_except: None,
opt_replace: None,
opt_rename: None,
}
}
}

impl fmt::Display for WildcardAdditionalOptions {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(ilike) = &self.opt_ilike {
Expand Down
Loading