Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
131 changes: 131 additions & 0 deletions src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -931,6 +931,54 @@ pub enum Expr {
///
/// See <https://docs.databricks.com/en/sql/language-manual/sql-ref-lambda-functions.html>.
Lambda(LambdaFunction),
/// MSSQL's `JSON_ARRAY` function for construct JSON-ARRAY object
///
/// Syntax:
///
/// ```plaintext
/// JSON_ARRAY ( [ <json_array_value> [,...n] ] [ <json_null_clause> ] )
///
/// <json_array_value> ::= value_expression
///
/// <json_null_clause> ::=
/// NULL ON NULL
/// | ABSENT ON NULL
/// ```
///
/// Example:
///
/// ```sql
/// SELECT JSON_ARRAY('a', 1, 'b', 2) --["a",1,"b",2]
/// SELECT JSON_ARRAY('a', 1, NULL, 2 NULL ON NULL) --["a",1,null,2]
/// SELECT JSON_ARRAY('a', JSON_OBJECT('name':'value', 'type':1), JSON_ARRAY(1, null, 2 NULL ON NULL)) --["a",{"name":"value","type":1},[1,null,2]]
/// ```
///
/// Reference: <https://learn.microsoft.com/en-us/sql/t-sql/functions/json-array-transact-sql?view=sql-server-ver16>
JsonArray(JsonArray),
/// MSSQL's `JSON_OBJECT` function for construct JSON-OBJECT object
///
/// Syntax:
///
/// ```plaintext
/// JSON_OBJECT ( [ <json_key_value> [,...n] ] [ json_null_clause ] )
///
/// <json_key_value> ::= json_key_name : value_expression
///
/// <json_null_clause> ::=
/// NULL ON NULL
/// | ABSENT ON NULL
/// ```
///
/// Example:
///
/// ```sql
/// SELECT JSON_OBJECT('name':'value', 'type':1) --{"name":"value","type":1}
/// SELECT JSON_OBJECT('name':'value', 'type':NULL ABSENT ON NULL) --{"name":"value"}
/// SELECT JSON_OBJECT('name':'value', 'type':JSON_ARRAY(1, 2)) --{"name":"value","type":[1,2]}
/// ```
///
/// Reference: <https://learn.microsoft.com/en-us/sql/t-sql/functions/json-object-transact-sql?view=sql-server-ver16>
JsonObject(JsonObject),
}

/// The contents inside the `[` and `]` in a subscript expression.
Expand Down Expand Up @@ -1658,6 +1706,8 @@ impl fmt::Display for Expr {
}
Expr::Prior(expr) => write!(f, "PRIOR {expr}"),
Expr::Lambda(lambda) => write!(f, "{lambda}"),
Expr::JsonArray(json_array) => write!(f, "{json_array}"),
Expr::JsonObject(json_object) => write!(f, "{json_object}"),
}
}
}
Expand Down Expand Up @@ -7317,6 +7367,87 @@ impl Display for UtilityOption {
}
}

/// MSSQL's `JSON_ARRAY` constructor function
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct JsonArray {
pub args: Vec<Expr>,
pub null_clause: Option<JsonNullClause>,
}

impl Display for JsonArray {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "JSON_ARRAY({}", display_comma_separated(&self.args))?;
if let Some(null_clause) = &self.null_clause {
if !self.args.is_empty() {
write!(f, " ")?;
}
write!(f, "{null_clause}")?;
}
write!(f, ")")
}
}

/// MSSQL's `JSON_OBJECT` constructor function
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct JsonObject {
pub key_values: Vec<JsonKeyValue>,
pub null_clause: Option<JsonNullClause>,
}

impl Display for JsonObject {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"JSON_OBJECT({}",
display_comma_separated(&self.key_values)
)?;
if let Some(null_clause) = &self.null_clause {
if !self.key_values.is_empty() {
write!(f, " ")?;
}
write!(f, "{null_clause}")?;
}
write!(f, ")")
}
}

/// A key-value pair of MSSQL's `JSON_OBJECT`
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct JsonKeyValue {
pub key: Expr,
pub value: Expr,
}

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

/// MSSQL's json null clause
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum JsonNullClause {
NullOnNull,
AbsentOnNull,
}

impl Display for JsonNullClause {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
JsonNullClause::NullOnNull => write!(f, "NULL ON NULL"),
JsonNullClause::AbsentOnNull => write!(f, "ABSENT ON NULL"),
}
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
3 changes: 3 additions & 0 deletions src/keywords.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ macro_rules! define_keywords {
define_keywords!(
ABORT,
ABS,
ABSENT,
ABSOLUTE,
ACCESS,
ACTION,
Expand Down Expand Up @@ -419,6 +420,8 @@ define_keywords!(
JSON,
JSONB,
JSONFILE,
JSON_ARRAY,
JSON_OBJECT,
JSON_TABLE,
JULIAN,
KEY,
Expand Down
71 changes: 70 additions & 1 deletion src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -991,7 +991,7 @@ impl<'a> Parser<'a> {
if let Some(expr) = opt_expr {
return Ok(expr);
}

let next_token = self.next_token();
let expr = match next_token.token {
Token::Word(w) => match w.keyword {
Expand Down Expand Up @@ -1028,6 +1028,11 @@ impl<'a> Parser<'a> {
Keyword::CAST => self.parse_cast_expr(CastKind::Cast),
Keyword::TRY_CAST => self.parse_cast_expr(CastKind::TryCast),
Keyword::SAFE_CAST => self.parse_cast_expr(CastKind::SafeCast),
Keyword::JSON_ARRAY
if self.peek_token() == Token::LParen
&& dialect_of!(self is MsSqlDialect) => self.parse_json_array(),
Keyword::JSON_OBJECT if self.peek_token() == Token::LParen
&& dialect_of!(self is MsSqlDialect) => self.parse_json_object(),
Keyword::EXISTS
// Support parsing Databricks has a function named `exists`.
if !dialect_of!(self is DatabricksDialect)
Expand Down Expand Up @@ -3013,6 +3018,70 @@ impl<'a> Parser<'a> {
})
}

/// Parses MSSQL's `JSON_ARRAY` constructor function
pub fn parse_json_array(&mut self) -> Result<Expr, ParserError> {
self.expect_token(&Token::LParen)?;
let mut args = Vec::new();
let mut null_clause = None;
loop {
// JSON_ARRAY()
if self.consume_token(&Token::RParen) {
self.prev_token();
break;
}
// JSON_ARRAY(NULL ON NULL)
else if self.parse_keywords(&[Keyword::NULL, Keyword::ON, Keyword::NULL]) {
null_clause = Some(JsonNullClause::NullOnNull);
break;
}
// JSON_ARRAY(ABSENT ON NULL)
else if self.parse_keywords(&[Keyword::ABSENT, Keyword::ON, Keyword::NULL]) {
null_clause = Some(JsonNullClause::AbsentOnNull);
break;
} else if !args.is_empty() && !self.consume_token(&Token::Comma) {
break;
}
args.push(self.parse_expr()?);
}
self.expect_token(&Token::RParen)?;
Ok(Expr::JsonArray(JsonArray { args, null_clause }))
}

/// Parses MSSQL's `JSON_OBJECT` constructor function
pub fn parse_json_object(&mut self) -> Result<Expr, ParserError> {
self.expect_token(&Token::LParen)?;
let mut key_values = Vec::new();
let mut null_clause = None;
loop {
// JSON_OBJECT()
if self.consume_token(&Token::RParen) {
self.prev_token();
break;
}
// JSON_OBJECT(NULL ON NULL)
else if self.parse_keywords(&[Keyword::NULL, Keyword::ON, Keyword::NULL]) {
null_clause = Some(JsonNullClause::NullOnNull);
break;
}
// JSON_OBJECT(ABSENT ON NULL)
else if self.parse_keywords(&[Keyword::ABSENT, Keyword::ON, Keyword::NULL]) {
null_clause = Some(JsonNullClause::AbsentOnNull);
break;
} else if !key_values.is_empty() && !self.consume_token(&Token::Comma) {
break;
}
let key = self.parse_expr()?;
self.expect_token(&Token::Colon)?;
let value = self.parse_expr()?;
key_values.push(JsonKeyValue {
key,
value
});
}
self.expect_token(&Token::RParen)?;
Ok(Expr::JsonObject(JsonObject { key_values, null_clause }))
}

/// Parses the parens following the `[ NOT ] IN` operator.
pub fn parse_in(&mut self, expr: Expr, negated: bool) -> Result<Expr, ParserError> {
// BigQuery allows `IN UNNEST(array_expression)`
Expand Down
Loading