Skip to content

Store spans for Value expressions #1738

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

Merged
merged 18 commits into from
Feb 25, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
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
14 changes: 8 additions & 6 deletions src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ pub use self::trigger::{

pub use self::value::{
escape_double_quote_string, escape_quoted_string, DateTimeField, DollarQuotedString,
NormalizationForm, TrimWhereField, Value,
NormalizationForm, TrimWhereField, Value, ValueWrapper,
};

use crate::ast::helpers::key_value_options::KeyValueOptions;
Expand Down Expand Up @@ -892,7 +892,7 @@ pub enum Expr {
/// Nested expression e.g. `(foo > bar)` or `(1)`
Nested(Box<Expr>),
/// A literal value, such as string, number, date or NULL
Value(Value),
Value(ValueWrapper),
/// <https://dev.mysql.com/doc/refman/8.0/en/charset-introducer.html>
IntroducedString {
introducer: String,
Expand Down Expand Up @@ -8733,9 +8733,9 @@ mod tests {
#[test]
fn test_interval_display() {
let interval = Expr::Interval(Interval {
value: Box::new(Expr::Value(Value::SingleQuotedString(String::from(
"123:45.67",
)))),
value: Box::new(Expr::Value(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

minor stuff we could use the Expr::value here too

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes! But I don't have the strength to fight ast-grep again 🙂‍↔️

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I saw it in my editor and couldn't exist:

Value::SingleQuotedString(String::from("123:45.67")).with_empty_span(),
)),
leading_field: Some(DateTimeField::Minute),
leading_precision: Some(10),
last_field: Some(DateTimeField::Second),
Expand All @@ -8747,7 +8747,9 @@ mod tests {
);

let interval = Expr::Interval(Interval {
value: Box::new(Expr::Value(Value::SingleQuotedString(String::from("5")))),
value: Box::new(Expr::Value(
Value::SingleQuotedString(String::from("5")).with_empty_span(),
)),
leading_field: Some(DateTimeField::Second),
leading_precision: Some(1),
last_field: None,
Expand Down
28 changes: 9 additions & 19 deletions src/ast/spans.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,21 +21,7 @@ use core::iter;
use crate::tokenizer::Span;

use super::{
dcl::SecondaryRoles, AccessExpr, AlterColumnOperation, AlterIndexOperation,
AlterTableOperation, Array, Assignment, AssignmentTarget, CloseCursor, ClusteredIndex,
ColumnDef, ColumnOption, ColumnOptionDef, ConflictTarget, ConnectBy, ConstraintCharacteristics,
CopySource, CreateIndex, CreateTable, CreateTableOptions, Cte, Delete, DoUpdate,
ExceptSelectItem, ExcludeSelectItem, Expr, ExprWithAlias, Fetch, FromTable, Function,
FunctionArg, FunctionArgExpr, FunctionArgumentClause, FunctionArgumentList, FunctionArguments,
GroupByExpr, HavingBound, IlikeSelectItem, Insert, Interpolate, InterpolateExpr, Join,
JoinConstraint, JoinOperator, JsonPath, JsonPathElem, LateralView, MatchRecognizePattern,
Measure, NamedWindowDefinition, ObjectName, ObjectNamePart, Offset, OnConflict,
OnConflictAction, OnInsert, OrderBy, OrderByExpr, Partition, PivotValueSource,
ProjectionSelect, Query, ReferentialAction, RenameSelectItem, ReplaceSelectElement,
ReplaceSelectItem, Select, SelectInto, SelectItem, SetExpr, SqlOption, Statement, Subscript,
SymbolDefinition, TableAlias, TableAliasColumnDef, TableConstraint, TableFactor, TableObject,
TableOptionsClustered, TableWithJoins, UpdateTableFromKind, Use, Value, Values, ViewColumnDef,
WildcardAdditionalOptions, With, WithFill,
dcl::SecondaryRoles, value::ValueWrapper, AccessExpr, AlterColumnOperation, AlterIndexOperation, AlterTableOperation, Array, Assignment, AssignmentTarget, CloseCursor, ClusteredIndex, ColumnDef, ColumnOption, ColumnOptionDef, ConflictTarget, ConnectBy, ConstraintCharacteristics, CopySource, CreateIndex, CreateTable, CreateTableOptions, Cte, Delete, DoUpdate, ExceptSelectItem, ExcludeSelectItem, Expr, ExprWithAlias, Fetch, FromTable, Function, FunctionArg, FunctionArgExpr, FunctionArgumentClause, FunctionArgumentList, FunctionArguments, GroupByExpr, HavingBound, IlikeSelectItem, Insert, Interpolate, InterpolateExpr, Join, JoinConstraint, JoinOperator, JsonPath, JsonPathElem, LateralView, MatchRecognizePattern, Measure, NamedWindowDefinition, ObjectName, ObjectNamePart, Offset, OnConflict, OnConflictAction, OnInsert, OrderBy, OrderByExpr, Partition, PivotValueSource, ProjectionSelect, Query, ReferentialAction, RenameSelectItem, ReplaceSelectElement, ReplaceSelectItem, Select, SelectInto, SelectItem, SetExpr, SqlOption, Statement, Subscript, SymbolDefinition, TableAlias, TableAliasColumnDef, TableConstraint, TableFactor, TableObject, TableOptionsClustered, TableWithJoins, UpdateTableFromKind, Use, Value, Values, ViewColumnDef, WildcardAdditionalOptions, With, WithFill
};

/// Given an iterator of spans, return the [Span::union] of all spans.
Expand Down Expand Up @@ -1974,10 +1960,14 @@ impl Spanned for TableAliasColumnDef {
}
}

/// # missing span
///
/// The span of a `Value` is currently not implemented, as doing so
/// requires a breaking changes, which may be done in a future release.

impl Spanned for ValueWrapper {
fn span(&self) -> Span {
self.span
}
}

/// The span is stored in the `ValueWrapper` struct
impl Spanned for Value {
fn span(&self) -> Span {
Span::empty() // # todo: Value needs to store spans before this is possible
Expand Down
38 changes: 37 additions & 1 deletion src/ast/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,25 @@ use bigdecimal::BigDecimal;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

use crate::ast::Ident;
use crate::{ast::Ident, tokenizer::Span};
#[cfg(feature = "visitor")]
use sqlparser_derive::{Visit, VisitMut};

/// Primitive SQL values such as number and string
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct ValueWrapper {
pub value: Value,
pub span: Span,
}

impl From<ValueWrapper> for Value {
fn from(value: ValueWrapper) -> Self {
value.value
}
}

/// Primitive SQL values such as number and string
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
Expand Down Expand Up @@ -97,6 +112,13 @@ pub enum Value {
Placeholder(String),
}

impl ValueWrapper {
/// If the underlying literal is a string, regardless of quote style, returns the associated string value
pub fn into_string(self) -> Option<String> {
self.value.into_string()
}
}

impl Value {
/// If the underlying literal is a string, regardless of quote style, returns the associated string value
pub fn into_string(self) -> Option<String> {
Expand All @@ -121,6 +143,20 @@ impl Value {
_ => None,
}
}

pub fn with_span(self, span: Span) -> ValueWrapper {
ValueWrapper { value: self, span }
}

pub fn with_empty_span(self) -> ValueWrapper {
self.with_span(Span::empty())
}
}

impl fmt::Display for ValueWrapper {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.value)
}
}

impl fmt::Display for Value {
Expand Down
Loading
Loading