Skip to content

Commit 610096c

Browse files
authored
MSSQL: Add support for functionality MERGE output clause (#1790)
1 parent 3ed4ad9 commit 610096c

File tree

7 files changed

+109
-16
lines changed

7 files changed

+109
-16
lines changed

src/ast/mod.rs

+38-1
Original file line numberDiff line numberDiff line change
@@ -3817,6 +3817,7 @@ pub enum Statement {
38173817
/// ```
38183818
/// [Snowflake](https://docs.snowflake.com/en/sql-reference/sql/merge)
38193819
/// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/dml-syntax#merge_statement)
3820+
/// [MSSQL](https://learn.microsoft.com/en-us/sql/t-sql/statements/merge-transact-sql?view=sql-server-ver16)
38203821
Merge {
38213822
/// optional INTO keyword
38223823
into: bool,
@@ -3828,6 +3829,8 @@ pub enum Statement {
38283829
on: Box<Expr>,
38293830
/// Specifies the actions to perform when values match or do not match.
38303831
clauses: Vec<MergeClause>,
3832+
// Specifies the output to save changes in MSSQL
3833+
output: Option<OutputClause>,
38313834
},
38323835
/// ```sql
38333836
/// CACHE [ FLAG ] TABLE <table_name> [ OPTIONS('K1' = 'V1', 'K2' = V2) ] [ AS ] [ <query> ]
@@ -5407,14 +5410,19 @@ impl fmt::Display for Statement {
54075410
source,
54085411
on,
54095412
clauses,
5413+
output,
54105414
} => {
54115415
write!(
54125416
f,
54135417
"MERGE{int} {table} USING {source} ",
54145418
int = if *into { " INTO" } else { "" }
54155419
)?;
54165420
write!(f, "ON {on} ")?;
5417-
write!(f, "{}", display_separated(clauses, " "))
5421+
write!(f, "{}", display_separated(clauses, " "))?;
5422+
if let Some(output) = output {
5423+
write!(f, " {output}")?;
5424+
}
5425+
Ok(())
54185426
}
54195427
Statement::Cache {
54205428
table_name,
@@ -7945,6 +7953,35 @@ impl Display for MergeClause {
79457953
}
79467954
}
79477955

7956+
/// A Output Clause in the end of a 'MERGE' Statement
7957+
///
7958+
/// Example:
7959+
/// OUTPUT $action, deleted.* INTO dbo.temp_products;
7960+
/// [mssql](https://learn.microsoft.com/en-us/sql/t-sql/queries/output-clause-transact-sql)
7961+
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7962+
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7963+
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7964+
pub struct OutputClause {
7965+
pub select_items: Vec<SelectItem>,
7966+
pub into_table: SelectInto,
7967+
}
7968+
7969+
impl fmt::Display for OutputClause {
7970+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7971+
let OutputClause {
7972+
select_items,
7973+
into_table,
7974+
} = self;
7975+
7976+
write!(
7977+
f,
7978+
"OUTPUT {} {}",
7979+
display_comma_separated(select_items),
7980+
into_table
7981+
)
7982+
}
7983+
}
7984+
79487985
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
79497986
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
79507987
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]

src/keywords.rs

+1
Original file line numberDiff line numberDiff line change
@@ -632,6 +632,7 @@ define_keywords!(
632632
ORGANIZATION,
633633
OUT,
634634
OUTER,
635+
OUTPUT,
635636
OUTPUTFORMAT,
636637
OVER,
637638
OVERFLOW,

src/parser/mod.rs

+36-14
Original file line numberDiff line numberDiff line change
@@ -10910,18 +10910,7 @@ impl<'a> Parser<'a> {
1091010910
};
1091110911

1091210912
let into = if self.parse_keyword(Keyword::INTO) {
10913-
let temporary = self
10914-
.parse_one_of_keywords(&[Keyword::TEMP, Keyword::TEMPORARY])
10915-
.is_some();
10916-
let unlogged = self.parse_keyword(Keyword::UNLOGGED);
10917-
let table = self.parse_keyword(Keyword::TABLE);
10918-
let name = self.parse_object_name(false)?;
10919-
Some(SelectInto {
10920-
temporary,
10921-
unlogged,
10922-
table,
10923-
name,
10924-
})
10913+
Some(self.parse_select_into()?)
1092510914
} else {
1092610915
None
1092710916
};
@@ -14513,10 +14502,9 @@ impl<'a> Parser<'a> {
1451314502
pub fn parse_merge_clauses(&mut self) -> Result<Vec<MergeClause>, ParserError> {
1451414503
let mut clauses = vec![];
1451514504
loop {
14516-
if self.peek_token() == Token::EOF || self.peek_token() == Token::SemiColon {
14505+
if !(self.parse_keyword(Keyword::WHEN)) {
1451714506
break;
1451814507
}
14519-
self.expect_keyword_is(Keyword::WHEN)?;
1452014508

1452114509
let mut clause_kind = MergeClauseKind::Matched;
1452214510
if self.parse_keyword(Keyword::NOT) {
@@ -14610,6 +14598,34 @@ impl<'a> Parser<'a> {
1461014598
Ok(clauses)
1461114599
}
1461214600

14601+
fn parse_output(&mut self) -> Result<OutputClause, ParserError> {
14602+
self.expect_keyword_is(Keyword::OUTPUT)?;
14603+
let select_items = self.parse_projection()?;
14604+
self.expect_keyword_is(Keyword::INTO)?;
14605+
let into_table = self.parse_select_into()?;
14606+
14607+
Ok(OutputClause {
14608+
select_items,
14609+
into_table,
14610+
})
14611+
}
14612+
14613+
fn parse_select_into(&mut self) -> Result<SelectInto, ParserError> {
14614+
let temporary = self
14615+
.parse_one_of_keywords(&[Keyword::TEMP, Keyword::TEMPORARY])
14616+
.is_some();
14617+
let unlogged = self.parse_keyword(Keyword::UNLOGGED);
14618+
let table = self.parse_keyword(Keyword::TABLE);
14619+
let name = self.parse_object_name(false)?;
14620+
14621+
Ok(SelectInto {
14622+
temporary,
14623+
unlogged,
14624+
table,
14625+
name,
14626+
})
14627+
}
14628+
1461314629
pub fn parse_merge(&mut self) -> Result<Statement, ParserError> {
1461414630
let into = self.parse_keyword(Keyword::INTO);
1461514631

@@ -14620,13 +14636,19 @@ impl<'a> Parser<'a> {
1462014636
self.expect_keyword_is(Keyword::ON)?;
1462114637
let on = self.parse_expr()?;
1462214638
let clauses = self.parse_merge_clauses()?;
14639+
let output = if self.peek_keyword(Keyword::OUTPUT) {
14640+
Some(self.parse_output()?)
14641+
} else {
14642+
None
14643+
};
1462314644

1462414645
Ok(Statement::Merge {
1462514646
into,
1462614647
table,
1462714648
source,
1462814649
on: Box::new(on),
1462914650
clauses,
14651+
output,
1463014652
})
1463114653
}
1463214654

tests/sqlparser_bigquery.rs

+2
Original file line numberDiff line numberDiff line change
@@ -1735,13 +1735,15 @@ fn parse_merge() {
17351735
},
17361736
],
17371737
};
1738+
17381739
match bigquery_and_generic().verified_stmt(sql) {
17391740
Statement::Merge {
17401741
into,
17411742
table,
17421743
source,
17431744
on,
17441745
clauses,
1746+
..
17451747
} => {
17461748
assert!(!into);
17471749
assert_eq!(

tests/sqlparser_common.rs

+15
Original file line numberDiff line numberDiff line change
@@ -9359,13 +9359,15 @@ fn parse_merge() {
93599359
source,
93609360
on,
93619361
clauses,
9362+
..
93629363
},
93639364
Statement::Merge {
93649365
into: no_into,
93659366
table: table_no_into,
93669367
source: source_no_into,
93679368
on: on_no_into,
93689369
clauses: clauses_no_into,
9370+
..
93699371
},
93709372
) => {
93719373
assert!(into);
@@ -9558,6 +9560,19 @@ fn parse_merge() {
95589560
verified_stmt(sql);
95599561
}
95609562

9563+
#[test]
9564+
fn test_merge_with_output() {
9565+
let sql = "MERGE INTO target_table USING source_table \
9566+
ON target_table.id = source_table.oooid \
9567+
WHEN MATCHED THEN \
9568+
UPDATE SET target_table.description = source_table.description \
9569+
WHEN NOT MATCHED THEN \
9570+
INSERT (ID, description) VALUES (source_table.id, source_table.description) \
9571+
OUTPUT inserted.* INTO log_target";
9572+
9573+
verified_stmt(sql);
9574+
}
9575+
95619576
#[test]
95629577
fn test_merge_into_using_table() {
95639578
let sql = "MERGE INTO target_table USING source_table \

tests/sqlparser_mssql.rs

+16
Original file line numberDiff line numberDiff line change
@@ -1921,3 +1921,19 @@ fn ms() -> TestedDialects {
19211921
fn ms_and_generic() -> TestedDialects {
19221922
TestedDialects::new(vec![Box::new(MsSqlDialect {}), Box::new(GenericDialect {})])
19231923
}
1924+
1925+
#[test]
1926+
fn parse_mssql_merge_with_output() {
1927+
let stmt = "MERGE dso.products AS t \
1928+
USING dsi.products AS \
1929+
s ON s.ProductID = t.ProductID \
1930+
WHEN MATCHED AND \
1931+
NOT (t.ProductName = s.ProductName OR (ISNULL(t.ProductName, s.ProductName) IS NULL)) \
1932+
THEN UPDATE SET t.ProductName = s.ProductName \
1933+
WHEN NOT MATCHED BY TARGET \
1934+
THEN INSERT (ProductID, ProductName) \
1935+
VALUES (s.ProductID, s.ProductName) \
1936+
WHEN NOT MATCHED BY SOURCE THEN DELETE \
1937+
OUTPUT $action, deleted.ProductID INTO dsi.temp_products";
1938+
ms_and_generic().verified_stmt(stmt);
1939+
}

tests/sqlparser_redshift.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -395,5 +395,5 @@ fn test_parse_nested_quoted_identifier() {
395395
#[test]
396396
fn parse_extract_single_quotes() {
397397
let sql = "SELECT EXTRACT('month' FROM my_timestamp) FROM my_table";
398-
redshift().verified_stmt(&sql);
398+
redshift().verified_stmt(sql);
399399
}

0 commit comments

Comments
 (0)