Skip to content

Add ODBC escape syntax support for time expressions #1953

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

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
58 changes: 48 additions & 10 deletions src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1014,12 +1014,7 @@ pub enum Expr {
/// A constant of form `<data_type> 'value'`.
/// This can represent ANSI SQL `DATE`, `TIME`, and `TIMESTAMP` literals (such as `DATE '2020-01-01'`),
/// as well as constants of other types (a non-standard PostgreSQL extension).
TypedString {
data_type: DataType,
/// The value of the constant.
/// Hint: you can unwrap the string value using `value.into_string()`.
value: ValueWithSpan,
},
TypedString(TypedString),
/// Scalar function call e.g. `LEFT(foo, 5)`
Function(Function),
/// `CASE [<operand>] WHEN <condition> THEN <result> ... [ELSE <result>] END`
Expand Down Expand Up @@ -1734,10 +1729,7 @@ impl fmt::Display for Expr {
Expr::Nested(ast) => write!(f, "({ast})"),
Expr::Value(v) => write!(f, "{v}"),
Expr::Prefixed { prefix, value } => write!(f, "{prefix} {value}"),
Expr::TypedString { data_type, value } => {
write!(f, "{data_type}")?;
write!(f, " {value}")
}
Expr::TypedString(ts) => ts.fmt(f),
Expr::Function(fun) => fun.fmt(f),
Expr::Case {
case_token: _,
Expand Down Expand Up @@ -7429,6 +7421,52 @@ pub struct DropDomain {
pub drop_behavior: Option<DropBehavior>,
}

/// A constant of form `<data_type> 'value'`.
/// This can represent ANSI SQL `DATE`, `TIME`, and `TIMESTAMP` literals (such as `DATE '2020-01-01'`),
/// as well as constants of other types (a non-standard PostgreSQL extension).
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct TypedString {
pub data_type: DataType,
/// The value of the constant.
/// Hint: you can unwrap the string value using `value.into_string()`.
pub value: ValueWithSpan,
/// Flags whether this TypedString uses the [ODBC syntax].
///
/// Example:
/// ```sql
/// -- An ODBC date literal:
/// SELECT {d '2025-07-16'}
/// -- This is equivalent to the standard ANSI SQL literal:
/// SELECT DATE '2025-07-16'
///
/// [ODBC syntax]: https://learn.microsoft.com/en-us/sql/odbc/reference/develop-app/date-time-and-timestamp-literals?view=sql-server-2017
pub uses_odbc_syntax: bool,
}

impl fmt::Display for TypedString {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let data_type = &self.data_type;
let value = &self.value;
match self.uses_odbc_syntax {
false => {
write!(f, "{data_type}")?;
write!(f, " {value}")
}
true => {
let prefix = match data_type {
DataType::Date => "d",
DataType::Time(..) => "t",
DataType::Timestamp(..) => "ts",
_ => "?",
};
write!(f, "{{{prefix} {value}}}")
}
}
}
}

/// A function call
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
Expand Down
4 changes: 2 additions & 2 deletions src/ast/spans.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
// specific language governing permissions and limitations
// under the License.

use crate::ast::{query::SelectItemQualifiedWildcardKind, ColumnOptions};
use crate::ast::{query::SelectItemQualifiedWildcardKind, ColumnOptions, TypedString};
use core::iter;

use crate::tokenizer::Span;
Expand Down Expand Up @@ -1514,7 +1514,7 @@ impl Spanned for Expr {
.union(&union_spans(collation.0.iter().map(|i| i.span()))),
Expr::Nested(expr) => expr.span(),
Expr::Value(value) => value.span(),
Expr::TypedString { value, .. } => value.span(),
Expr::TypedString(TypedString { value, .. }) => value.span(),
Expr::Function(function) => function.span(),
Expr::GroupingSets(vec) => {
union_spans(vec.iter().flat_map(|i| i.iter().map(|k| k.span())))
Expand Down
56 changes: 51 additions & 5 deletions src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1539,10 +1539,11 @@ impl<'a> Parser<'a> {
// an unary negation `NOT ('a' LIKE 'b')`. To solve this, we don't accept the
// `type 'string'` syntax for the custom data types at all.
DataType::Custom(..) => parser_err!("dummy", loc),
data_type => Ok(Expr::TypedString {
data_type => Ok(Expr::TypedString(TypedString {
data_type,
value: parser.parse_value()?,
}),
uses_odbc_syntax: false,
})),
}
})?;

Expand Down Expand Up @@ -1728,10 +1729,11 @@ impl<'a> Parser<'a> {
}

fn parse_geometric_type(&mut self, kind: GeometricTypeKind) -> Result<Expr, ParserError> {
Ok(Expr::TypedString {
Ok(Expr::TypedString(TypedString {
data_type: DataType::GeometricType(kind),
value: self.parse_value()?,
})
uses_odbc_syntax: false,
}))
}

/// Try to parse an [Expr::CompoundFieldAccess] like `a.b.c` or `a.b[1].c`.
Expand Down Expand Up @@ -2028,6 +2030,50 @@ impl<'a> Parser<'a> {
})
}

/// Tries to parse the body of an [ODBC escaping sequence]
/// i.e. without the enclosing braces
/// Currently implemented:
/// Scalar Function Calls
/// Date, Time, and Timestamp Literals
/// See <https://learn.microsoft.com/en-us/sql/odbc/reference/develop-app/escape-sequences-in-odbc?view=sql-server-2017>
fn maybe_parse_odbc_body(&mut self) -> Result<Option<Expr>, ParserError> {
// Attempt 1: Try to parse it as a function.
if let Some(expr) = self.maybe_parse_odbc_fn_body()? {
return Ok(Some(expr));
}
// Attempt 2: Try to parse it as a Date, Time or Timestamp Literal
self.maybe_parse_odbc_body_datetime()
}

/// Tries to parse the body of an [ODBC Date, Time, and Timestamp Literals] call.
///
/// ```sql
/// {d '2025-07-17'}
/// {t '14:12:01'}
/// {ts '2025-07-17 14:12:01'}
/// ```
///
/// [ODBC Date, Time, and Timestamp Literals]:
/// https://learn.microsoft.com/en-us/sql/odbc/reference/develop-app/date-time-and-timestamp-literals?view=sql-server-2017
fn maybe_parse_odbc_body_datetime(&mut self) -> Result<Option<Expr>, ParserError> {
self.maybe_parse(|p| {
let token = p.next_token().clone();
let word_string = token.token.to_string();
let data_type = match word_string.as_str() {
"t" => DataType::Time(None, TimezoneInfo::None),
"d" => DataType::Date,
"ts" => DataType::Timestamp(None, TimezoneInfo::None),
_ => return p.expected("ODBC datetime keyword (t, d, or ts)", token),
};
let value = p.parse_value()?;
Ok(Expr::TypedString(TypedString {
data_type,
value,
uses_odbc_syntax: true,
}))
})
}

/// Tries to parse the body of an [ODBC function] call.
/// i.e. without the enclosing braces
///
Expand Down Expand Up @@ -2782,7 +2828,7 @@ impl<'a> Parser<'a> {
fn parse_lbrace_expr(&mut self) -> Result<Expr, ParserError> {
let token = self.expect_token(&Token::LBrace)?;

if let Some(fn_expr) = self.maybe_parse_odbc_fn_body()? {
if let Some(fn_expr) = self.maybe_parse_odbc_body()? {
self.expect_token(&Token::RBrace)?;
return Ok(fn_expr);
}
Expand Down
Loading
Loading