Skip to main content

sqlparser/ast/
dml.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18#[cfg(not(feature = "std"))]
19use alloc::{boxed::Box, format, string::ToString, vec::Vec};
20
21use core::fmt::{self, Display};
22#[cfg(feature = "serde")]
23use serde::{Deserialize, Serialize};
24#[cfg(feature = "visitor")]
25use sqlparser_derive::{Visit, VisitMut};
26
27use crate::{
28    ast::display_separated,
29    display_utils::{indented_list, Indent, SpaceOrNewline},
30};
31
32use super::{
33    display_comma_separated, helpers::attached_token::AttachedToken, query::InputFormatClause,
34    Assignment, Expr, FromTable, Ident, InsertAliases, MysqlInsertPriority, ObjectName, OnInsert,
35    OptimizerHint, OrderByExpr, Query, SelectInto, SelectItem, Setting, SqliteOnConflict,
36    TableAliasWithoutColumns, TableFactor, TableObject, TableWithJoins, UpdateTableFromKind,
37    Values,
38};
39
40/// The `OVERRIDING` clause of a PostgreSQL `INSERT`: whether values supplied for an identity
41/// column are used instead of the values its sequence would generate.
42///
43/// See <https://www.postgresql.org/docs/current/sql-insert.html>
44#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
45#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
46#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
47pub enum InsertOverriding {
48    /// `OVERRIDING SYSTEM VALUE`
49    System,
50    /// `OVERRIDING USER VALUE`
51    User,
52}
53
54impl Display for InsertOverriding {
55    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
56        match self {
57            InsertOverriding::System => write!(f, "OVERRIDING SYSTEM VALUE"),
58            InsertOverriding::User => write!(f, "OVERRIDING USER VALUE"),
59        }
60    }
61}
62
63/// INSERT statement.
64#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
65#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
66#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
67pub struct Insert {
68    /// Token for the `INSERT` keyword (or its substitutes)
69    pub insert_token: AttachedToken,
70    /// Query optimizer hints
71    ///
72    /// [MySQL](https://dev.mysql.com/doc/refman/8.4/en/optimizer-hints.html)
73    /// [Oracle](https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/Comments.html#GUID-D316D545-89E2-4D54-977F-FC97815CD62E)
74    pub optimizer_hints: Vec<OptimizerHint>,
75    /// Only for Sqlite
76    pub or: Option<SqliteOnConflict>,
77    /// Only for mysql
78    pub ignore: bool,
79    /// INTO - optional keyword
80    pub into: bool,
81    /// TABLE
82    pub table: TableObject,
83    /// `table_name as foo` (for PostgreSQL)
84    /// `table_name foo` (for Oracle)
85    pub table_alias: Option<TableAliasWithoutColumns>,
86    /// COLUMNS
87    pub columns: Vec<ObjectName>,
88    /// `BY NAME` clause used by Databricks SQL.
89    ///
90    /// When present, columns from the source query are matched to columns in
91    /// the target table by name instead of by position. The syntax is:
92    ///
93    /// ```sql
94    /// INSERT INTO [TABLE] table_name
95    ///     [PARTITION (...)]
96    ///     [(column_name [, ...]) | BY NAME]
97    ///     query
98    /// ```
99    ///
100    /// See <https://docs.databricks.com/gcp/en/sql/language-manual/sql-ref-syntax-dml-insert-into>.
101    pub by_name: bool,
102    /// Overwrite (Hive)
103    pub overwrite: bool,
104    /// A SQL query that specifies what to insert
105    pub source: Option<Box<Query>>,
106    /// MySQL `INSERT INTO ... SET`
107    /// See: <https://dev.mysql.com/doc/refman/8.4/en/insert.html>
108    pub assignments: Vec<Assignment>,
109    /// partitioned insert (Hive)
110    pub partitioned: Option<Vec<Expr>>,
111    /// Columns defined after PARTITION
112    pub after_columns: Vec<Ident>,
113    /// PostgreSQL `OVERRIDING { SYSTEM | USER } VALUE`, between the column list and the source.
114    ///
115    /// See <https://www.postgresql.org/docs/current/sql-insert.html>
116    pub overriding: Option<InsertOverriding>,
117    /// whether the insert has the table keyword (Hive)
118    pub has_table_keyword: bool,
119    /// ON INSERT
120    pub on: Option<OnInsert>,
121    /// RETURNING
122    pub returning: Option<Vec<SelectItem>>,
123    /// OUTPUT (MSSQL)
124    /// See <https://learn.microsoft.com/en-us/sql/t-sql/queries/output-clause-transact-sql>
125    pub output: Option<OutputClause>,
126    /// Only for mysql
127    pub replace_into: bool,
128    /// Only for mysql
129    pub priority: Option<MysqlInsertPriority>,
130    /// Only for mysql
131    pub insert_alias: Option<InsertAliases>,
132    /// Settings used for ClickHouse.
133    ///
134    /// ClickHouse syntax: `INSERT INTO tbl SETTINGS format_template_resultset = '/some/path/resultset.format'`
135    ///
136    /// [ClickHouse `INSERT INTO`](https://clickhouse.com/docs/en/sql-reference/statements/insert-into)
137    pub settings: Option<Vec<Setting>>,
138    /// Format for `INSERT` statement when not using standard SQL format. Can be e.g. `CSV`,
139    /// `JSON`, `JSONAsString`, `LineAsString` and more.
140    ///
141    /// ClickHouse syntax: `INSERT INTO tbl FORMAT JSONEachRow {"foo": 1, "bar": 2}, {"foo": 3}`
142    ///
143    /// [ClickHouse formats JSON insert](https://clickhouse.com/docs/en/interfaces/formats#json-inserting-data)
144    pub format_clause: Option<InputFormatClause>,
145    /// For Snowflake multi-table insert: specifies the type (`ALL` or `FIRST`)
146    ///
147    /// - `None` means this is a regular single-table INSERT
148    /// - `Some(All)` means `INSERT ALL` (all matching WHEN clauses are executed)
149    /// - `Some(First)` means `INSERT FIRST` (only the first matching WHEN clause is executed)
150    ///
151    /// See: <https://docs.snowflake.com/en/sql-reference/sql/insert-multi-table>
152    pub multi_table_insert_type: Option<MultiTableInsertType>,
153    /// For multi-table insert: additional INTO clauses (unconditional)
154    ///
155    /// Used for `INSERT ALL INTO t1 INTO t2 ... SELECT ...`
156    ///
157    /// See: <https://docs.snowflake.com/en/sql-reference/sql/insert-multi-table>
158    pub multi_table_into_clauses: Vec<MultiTableInsertIntoClause>,
159    /// For conditional multi-table insert: WHEN clauses
160    ///
161    /// Used for `INSERT ALL/FIRST WHEN cond THEN INTO t1 ... SELECT ...`
162    ///
163    /// See: <https://docs.snowflake.com/en/sql-reference/sql/insert-multi-table>
164    pub multi_table_when_clauses: Vec<MultiTableInsertWhenClause>,
165    /// For conditional multi-table insert: ELSE clause
166    ///
167    /// See: <https://docs.snowflake.com/en/sql-reference/sql/insert-multi-table>
168    pub multi_table_else_clause: Option<Vec<MultiTableInsertIntoClause>>,
169}
170
171impl Display for Insert {
172    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
173        // SQLite OR conflict has a special format: INSERT OR ... INTO table_name
174        let table_name = if let Some(table_alias) = &self.table_alias {
175            format!(
176                "{table} {as_keyword}{alias}",
177                table = self.table,
178                as_keyword = if table_alias.explicit { "AS " } else { "" },
179                alias = table_alias.alias
180            )
181        } else {
182            self.table.to_string()
183        };
184
185        if let Some(on_conflict) = self.or {
186            f.write_str("INSERT")?;
187            for hint in &self.optimizer_hints {
188                write!(f, " {hint}")?;
189            }
190            write!(f, " {on_conflict} INTO {table_name} ")?;
191        } else {
192            write!(
193                f,
194                "{start}",
195                start = if self.replace_into {
196                    "REPLACE"
197                } else {
198                    "INSERT"
199                }
200            )?;
201            for hint in &self.optimizer_hints {
202                write!(f, " {hint}")?;
203            }
204            if let Some(priority) = self.priority {
205                write!(f, " {priority}")?;
206            }
207
208            if self.ignore {
209                write!(f, " IGNORE")?;
210            }
211
212            if self.overwrite {
213                write!(f, " OVERWRITE")?;
214            }
215
216            if let Some(insert_type) = &self.multi_table_insert_type {
217                write!(f, " {}", insert_type)?;
218            }
219
220            if self.into {
221                write!(f, " INTO")?;
222            }
223
224            if self.has_table_keyword {
225                write!(f, " TABLE")?;
226            }
227
228            if !table_name.is_empty() {
229                write!(f, " {table_name} ")?;
230            }
231        }
232
233        if !self.columns.is_empty() {
234            write!(f, "({})", display_comma_separated(&self.columns))?;
235            SpaceOrNewline.fmt(f)?;
236        }
237
238        if let Some(ref parts) = self.partitioned {
239            if !parts.is_empty() {
240                write!(f, "PARTITION ({})", display_comma_separated(parts))?;
241                SpaceOrNewline.fmt(f)?;
242            }
243        }
244
245        if self.by_name {
246            write!(f, "BY NAME")?;
247            SpaceOrNewline.fmt(f)?;
248        }
249
250        if !self.after_columns.is_empty() {
251            write!(f, "({})", display_comma_separated(&self.after_columns))?;
252            SpaceOrNewline.fmt(f)?;
253        }
254
255        if let Some(overriding) = &self.overriding {
256            write!(f, "{overriding}")?;
257            SpaceOrNewline.fmt(f)?;
258        }
259
260        if let Some(output) = &self.output {
261            write!(f, "{output}")?;
262            SpaceOrNewline.fmt(f)?;
263        }
264
265        if let Some(settings) = &self.settings {
266            write!(f, "SETTINGS {}", display_comma_separated(settings))?;
267            SpaceOrNewline.fmt(f)?;
268        }
269
270        for into_clause in &self.multi_table_into_clauses {
271            SpaceOrNewline.fmt(f)?;
272            write!(f, "{}", into_clause)?;
273        }
274
275        for when_clause in &self.multi_table_when_clauses {
276            SpaceOrNewline.fmt(f)?;
277            write!(f, "{}", when_clause)?;
278        }
279
280        if let Some(else_clauses) = &self.multi_table_else_clause {
281            SpaceOrNewline.fmt(f)?;
282            write!(f, "ELSE")?;
283            for into_clause in else_clauses {
284                SpaceOrNewline.fmt(f)?;
285                write!(f, "{}", into_clause)?;
286            }
287        }
288
289        if let Some(source) = &self.source {
290            if !self.multi_table_into_clauses.is_empty()
291                || !self.multi_table_when_clauses.is_empty()
292            {
293                SpaceOrNewline.fmt(f)?;
294            }
295            source.fmt(f)?;
296        } else if !self.assignments.is_empty() {
297            write!(f, "SET")?;
298            indented_list(f, &self.assignments)?;
299        } else if let Some(format_clause) = &self.format_clause {
300            format_clause.fmt(f)?;
301        } else if self.columns.is_empty() {
302            write!(f, "DEFAULT VALUES")?;
303        }
304
305        if let Some(insert_alias) = &self.insert_alias {
306            write!(f, " AS {0}", insert_alias.row_alias)?;
307
308            if let Some(col_aliases) = &insert_alias.col_aliases {
309                if !col_aliases.is_empty() {
310                    write!(f, " ({})", display_comma_separated(col_aliases))?;
311                }
312            }
313        }
314
315        if let Some(on) = &self.on {
316            write!(f, "{on}")?;
317        }
318
319        if let Some(returning) = &self.returning {
320            SpaceOrNewline.fmt(f)?;
321            f.write_str("RETURNING")?;
322            indented_list(f, returning)?;
323        }
324
325        Ok(())
326    }
327}
328
329/// DELETE statement.
330#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
331#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
332#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
333pub struct Delete {
334    /// Token for the `DELETE` keyword
335    pub delete_token: AttachedToken,
336    /// Query optimizer hints
337    ///
338    /// [MySQL](https://dev.mysql.com/doc/refman/8.4/en/optimizer-hints.html)
339    /// [Oracle](https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/Comments.html#GUID-D316D545-89E2-4D54-977F-FC97815CD62E)
340    pub optimizer_hints: Vec<OptimizerHint>,
341    /// Multi tables delete are supported in mysql
342    pub tables: Vec<ObjectName>,
343    /// FROM
344    pub from: FromTable,
345    /// ClickHouse `ON CLUSTER`
346    pub on_cluster: Option<Ident>,
347    /// USING (Snowflake, Postgres, MySQL)
348    pub using: Option<Vec<TableWithJoins>>,
349    /// WHERE
350    pub selection: Option<Expr>,
351    /// RETURNING
352    pub returning: Option<Vec<SelectItem>>,
353    /// OUTPUT (MSSQL)
354    /// See <https://learn.microsoft.com/en-us/sql/t-sql/queries/output-clause-transact-sql>
355    pub output: Option<OutputClause>,
356    /// ORDER BY (MySQL)
357    pub order_by: Vec<OrderByExpr>,
358    /// LIMIT (MySQL)
359    pub limit: Option<Expr>,
360    /// ClickHouse `SETTINGS`
361    pub settings: Option<Vec<Setting>>,
362}
363
364impl Display for Delete {
365    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
366        f.write_str("DELETE")?;
367        for hint in &self.optimizer_hints {
368            f.write_str(" ")?;
369            hint.fmt(f)?;
370        }
371        if !self.tables.is_empty() {
372            indented_list(f, &self.tables)?;
373        }
374        match &self.from {
375            FromTable::WithFromKeyword(from) => {
376                f.write_str(" FROM")?;
377                indented_list(f, from)?;
378            }
379            FromTable::WithoutKeyword(from) => {
380                indented_list(f, from)?;
381            }
382        }
383        if let Some(on_cluster) = &self.on_cluster {
384            write!(f, " ON CLUSTER {on_cluster}")?;
385        }
386        if let Some(output) = &self.output {
387            SpaceOrNewline.fmt(f)?;
388            write!(f, "{output}")?;
389        }
390        if let Some(using) = &self.using {
391            SpaceOrNewline.fmt(f)?;
392            f.write_str("USING")?;
393            indented_list(f, using)?;
394        }
395        if let Some(selection) = &self.selection {
396            SpaceOrNewline.fmt(f)?;
397            f.write_str("WHERE")?;
398            SpaceOrNewline.fmt(f)?;
399            Indent(selection).fmt(f)?;
400        }
401        if let Some(returning) = &self.returning {
402            SpaceOrNewline.fmt(f)?;
403            f.write_str("RETURNING")?;
404            indented_list(f, returning)?;
405        }
406        if !self.order_by.is_empty() {
407            SpaceOrNewline.fmt(f)?;
408            f.write_str("ORDER BY")?;
409            indented_list(f, &self.order_by)?;
410        }
411        if let Some(limit) = &self.limit {
412            SpaceOrNewline.fmt(f)?;
413            f.write_str("LIMIT")?;
414            SpaceOrNewline.fmt(f)?;
415            Indent(limit).fmt(f)?;
416        }
417        if let Some(settings) = &self.settings {
418            SpaceOrNewline.fmt(f)?;
419            f.write_str("SETTINGS")?;
420            indented_list(f, settings)?;
421        }
422        Ok(())
423    }
424}
425
426/// UPDATE statement.
427#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
428#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
429#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
430pub struct Update {
431    /// Token for the `UPDATE` keyword
432    pub update_token: AttachedToken,
433    /// Query optimizer hints
434    ///
435    /// [MySQL](https://dev.mysql.com/doc/refman/8.4/en/optimizer-hints.html)
436    /// [Oracle](https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/Comments.html#GUID-D316D545-89E2-4D54-977F-FC97815CD62E)
437    pub optimizer_hints: Vec<OptimizerHint>,
438    /// TABLE
439    pub table: TableWithJoins,
440    /// ClickHouse `ON CLUSTER`
441    pub on_cluster: Option<Ident>,
442    /// Column assignments
443    pub assignments: Vec<Assignment>,
444    /// Table which provide value to be set
445    pub from: Option<UpdateTableFromKind>,
446    /// WHERE
447    pub selection: Option<Expr>,
448    /// RETURNING
449    pub returning: Option<Vec<SelectItem>>,
450    /// OUTPUT (MSSQL)
451    /// See <https://learn.microsoft.com/en-us/sql/t-sql/queries/output-clause-transact-sql>
452    pub output: Option<OutputClause>,
453    /// SQLite-specific conflict resolution clause
454    pub or: Option<SqliteOnConflict>,
455    /// ORDER BY (MySQL extension for single-table UPDATE)
456    /// See <https://dev.mysql.com/doc/refman/8.4/en/update.html>
457    pub order_by: Vec<OrderByExpr>,
458    /// LIMIT
459    pub limit: Option<Expr>,
460    /// ClickHouse `SETTINGS`
461    pub settings: Option<Vec<Setting>>,
462}
463
464impl Display for Update {
465    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
466        f.write_str("UPDATE")?;
467        for hint in &self.optimizer_hints {
468            f.write_str(" ")?;
469            hint.fmt(f)?;
470        }
471        f.write_str(" ")?;
472        if let Some(or) = &self.or {
473            or.fmt(f)?;
474            f.write_str(" ")?;
475        }
476        self.table.fmt(f)?;
477        if let Some(on_cluster) = &self.on_cluster {
478            write!(f, " ON CLUSTER {on_cluster}")?;
479        }
480        if let Some(UpdateTableFromKind::BeforeSet(from)) = &self.from {
481            SpaceOrNewline.fmt(f)?;
482            f.write_str("FROM")?;
483            indented_list(f, from)?;
484        }
485        if !self.assignments.is_empty() {
486            SpaceOrNewline.fmt(f)?;
487            f.write_str("SET")?;
488            indented_list(f, &self.assignments)?;
489        }
490        if let Some(output) = &self.output {
491            SpaceOrNewline.fmt(f)?;
492            write!(f, "{output}")?;
493        }
494        if let Some(UpdateTableFromKind::AfterSet(from)) = &self.from {
495            SpaceOrNewline.fmt(f)?;
496            f.write_str("FROM")?;
497            indented_list(f, from)?;
498        }
499        if let Some(selection) = &self.selection {
500            SpaceOrNewline.fmt(f)?;
501            f.write_str("WHERE")?;
502            SpaceOrNewline.fmt(f)?;
503            Indent(selection).fmt(f)?;
504        }
505        if let Some(returning) = &self.returning {
506            SpaceOrNewline.fmt(f)?;
507            f.write_str("RETURNING")?;
508            indented_list(f, returning)?;
509        }
510        if !self.order_by.is_empty() {
511            SpaceOrNewline.fmt(f)?;
512            f.write_str("ORDER BY")?;
513            indented_list(f, &self.order_by)?;
514        }
515        if let Some(limit) = &self.limit {
516            SpaceOrNewline.fmt(f)?;
517            write!(f, "LIMIT {limit}")?;
518        }
519        if let Some(settings) = &self.settings {
520            SpaceOrNewline.fmt(f)?;
521            f.write_str("SETTINGS")?;
522            indented_list(f, settings)?;
523        }
524        Ok(())
525    }
526}
527
528/// A `MERGE` statement.
529#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
530#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
531#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
532pub struct Merge {
533    /// The `MERGE` token that starts the statement.
534    pub merge_token: AttachedToken,
535    /// Query optimizer hints
536    ///
537    /// [Oracle](https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/Comments.html#GUID-D316D545-89E2-4D54-977F-FC97815CD62E)
538    pub optimizer_hints: Vec<OptimizerHint>,
539    /// optional INTO keyword
540    pub into: bool,
541    /// Specifies the table to merge
542    pub table: TableFactor,
543    /// Specifies the table or subquery to join with the target table
544    pub source: TableFactor,
545    /// Specifies the expression on which to join the target table and source
546    pub on: Box<Expr>,
547    /// Specifies the actions to perform when values match or do not match.
548    pub clauses: Vec<MergeClause>,
549    /// Specifies the output to save changes in MSSQL
550    pub output: Option<OutputClause>,
551}
552
553impl Display for Merge {
554    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
555        f.write_str("MERGE")?;
556        for hint in &self.optimizer_hints {
557            write!(f, " {hint}")?;
558        }
559        if self.into {
560            write!(f, " INTO")?;
561        }
562        write!(
563            f,
564            " {table} USING {source} ",
565            table = self.table,
566            source = self.source
567        )?;
568        write!(f, "ON {on} ", on = self.on)?;
569        write!(f, "{}", display_separated(&self.clauses, " "))?;
570        if let Some(ref output) = self.output {
571            write!(f, " {output}")?;
572        }
573        Ok(())
574    }
575}
576
577/// A `WHEN` clause within a `MERGE` Statement
578///
579/// Example:
580/// ```sql
581/// WHEN NOT MATCHED BY SOURCE AND product LIKE '%washer%' THEN DELETE
582/// ```
583/// [Snowflake](https://docs.snowflake.com/en/sql-reference/sql/merge)
584/// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/dml-syntax#merge_statement)
585#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
586#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
587#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
588pub struct MergeClause {
589    /// The `WHEN` token that starts the sub-expression.
590    pub when_token: AttachedToken,
591    /// The type of `WHEN` clause.
592    pub clause_kind: MergeClauseKind,
593    /// An optional predicate to further restrict the clause.
594    pub predicate: Option<Expr>,
595    /// The action to perform when the clause is matched.
596    pub action: MergeAction,
597}
598
599impl Display for MergeClause {
600    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
601        let MergeClause {
602            when_token: _,
603            clause_kind,
604            predicate,
605            action,
606        } = self;
607
608        write!(f, "WHEN {clause_kind}")?;
609        if let Some(pred) = predicate {
610            write!(f, " AND {pred}")?;
611        }
612        write!(f, " THEN {action}")
613    }
614}
615
616/// Variant of `WHEN` clause used within a `MERGE` Statement.
617///
618/// Example:
619/// ```sql
620/// MERGE INTO T USING U ON FALSE WHEN MATCHED THEN DELETE
621/// ```
622/// [Snowflake](https://docs.snowflake.com/en/sql-reference/sql/merge)
623/// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/dml-syntax#merge_statement)
624#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
625#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
626#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
627pub enum MergeClauseKind {
628    /// `WHEN MATCHED`
629    Matched,
630    /// `WHEN NOT MATCHED`
631    NotMatched,
632    /// `WHEN MATCHED BY TARGET`
633    ///
634    /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/dml-syntax#merge_statement)
635    NotMatchedByTarget,
636    /// `WHEN MATCHED BY SOURCE`
637    ///
638    /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/dml-syntax#merge_statement)
639    NotMatchedBySource,
640}
641
642impl Display for MergeClauseKind {
643    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
644        match self {
645            MergeClauseKind::Matched => write!(f, "MATCHED"),
646            MergeClauseKind::NotMatched => write!(f, "NOT MATCHED"),
647            MergeClauseKind::NotMatchedByTarget => write!(f, "NOT MATCHED BY TARGET"),
648            MergeClauseKind::NotMatchedBySource => write!(f, "NOT MATCHED BY SOURCE"),
649        }
650    }
651}
652
653/// Underlying statement of a `WHEN` clause within a `MERGE` Statement
654///
655/// Example
656/// ```sql
657/// INSERT (product, quantity) VALUES(product, quantity)
658/// ```
659///
660/// [Snowflake](https://docs.snowflake.com/en/sql-reference/sql/merge)
661/// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/dml-syntax#merge_statement)
662/// [Oracle](https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/MERGE.html)
663#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
664#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
665#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
666pub enum MergeAction {
667    /// An `INSERT` clause
668    ///
669    /// Example:
670    /// ```sql
671    /// INSERT (product, quantity) VALUES(product, quantity)
672    /// ```
673    Insert(MergeInsertExpr),
674    /// An `UPDATE` clause
675    ///
676    /// Example:
677    /// ```sql
678    /// UPDATE SET quantity = T.quantity + S.quantity
679    /// ```
680    Update(MergeUpdateExpr),
681    /// A plain `DELETE` clause
682    Delete {
683        /// The `DELETE` token that starts the sub-expression.
684        delete_token: AttachedToken,
685    },
686    /// A `DO NOTHING` clause.
687    DoNothing {
688        /// The `DO` token that starts the sub-expression.
689        do_token: AttachedToken,
690        /// The `NOTHING` token that ends the sub-expression.
691        nothing_token: AttachedToken,
692    },
693}
694
695impl Display for MergeAction {
696    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
697        match self {
698            MergeAction::Insert(insert) => {
699                write!(f, "INSERT {insert}")
700            }
701            MergeAction::Update(update) => {
702                write!(f, "UPDATE {update}")
703            }
704            MergeAction::Delete { .. } => {
705                write!(f, "DELETE")
706            }
707            MergeAction::DoNothing { .. } => {
708                write!(f, "DO NOTHING")
709            }
710        }
711    }
712}
713
714/// The type of expression used to insert rows within a `MERGE` statement.
715///
716/// [Snowflake](https://docs.snowflake.com/en/sql-reference/sql/merge)
717/// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/dml-syntax#merge_statement)
718#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
719#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
720#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
721pub enum MergeInsertKind {
722    /// The insert expression is defined from an explicit `VALUES` clause
723    ///
724    /// Example:
725    /// ```sql
726    /// INSERT VALUES(product, quantity)
727    /// ```
728    Values(Values),
729    /// The insert expression is defined using only the `ROW` keyword.
730    ///
731    /// Example:
732    /// ```sql
733    /// INSERT ROW
734    /// ```
735    /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/dml-syntax#merge_statement)
736    Row,
737    /// The insert expression uses the `*` wildcard to insert all columns.
738    ///
739    /// Example:
740    /// ```sql
741    /// INSERT *
742    /// ```
743    /// [Databricks](https://docs.databricks.com/en/sql/language-manual/delta-merge-into.html)
744    Wildcard,
745}
746
747impl Display for MergeInsertKind {
748    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
749        match self {
750            MergeInsertKind::Values(values) => {
751                write!(f, "{values}")
752            }
753            MergeInsertKind::Row => {
754                write!(f, "ROW")
755            }
756            MergeInsertKind::Wildcard => {
757                write!(f, "*")
758            }
759        }
760    }
761}
762
763/// The expression used to insert rows within a `MERGE` statement.
764///
765/// Examples
766/// ```sql
767/// INSERT (product, quantity) VALUES(product, quantity)
768/// INSERT ROW
769/// ```
770///
771/// [Snowflake](https://docs.snowflake.com/en/sql-reference/sql/merge)
772/// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/dml-syntax#merge_statement)
773/// [Oracle](https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/MERGE.html)
774#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
775#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
776#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
777pub struct MergeInsertExpr {
778    /// The `INSERT` token that starts the sub-expression.
779    pub insert_token: AttachedToken,
780    /// Columns (if any) specified by the insert.
781    ///
782    /// Example:
783    /// ```sql
784    /// INSERT (product, quantity) VALUES(product, quantity)
785    /// INSERT (product, quantity) ROW
786    /// ```
787    pub columns: Vec<ObjectName>,
788    /// The token, `[VALUES | ROW]` starting `kind`.
789    pub kind_token: AttachedToken,
790    /// The insert type used by the statement.
791    pub kind: MergeInsertKind,
792    /// An optional condition to restrict the insertion (Oracle specific)
793    pub insert_predicate: Option<Expr>,
794}
795
796impl Display for MergeInsertExpr {
797    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
798        if !self.columns.is_empty() {
799            write!(f, "({}) ", display_comma_separated(self.columns.as_slice()))?;
800        }
801        write!(f, "{}", self.kind)?;
802        if let Some(predicate) = self.insert_predicate.as_ref() {
803            write!(f, " WHERE {}", predicate)?;
804        }
805        Ok(())
806    }
807}
808
809/// The kind of update used within a `MERGE` statement.
810#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
811#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
812#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
813pub enum MergeUpdateKind {
814    /// Standard update with explicit assignments.
815    ///
816    /// Example:
817    /// ```sql
818    /// UPDATE SET quantity = source.quantity, name = source.name
819    /// ```
820    Set(Vec<Assignment>),
821    /// The `*` wildcard to update all columns from the source.
822    ///
823    /// Example:
824    /// ```sql
825    /// UPDATE SET *
826    /// ```
827    /// [Databricks](https://docs.databricks.com/en/sql/language-manual/delta-merge-into.html)
828    Wildcard,
829}
830
831impl Display for MergeUpdateKind {
832    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
833        match self {
834            MergeUpdateKind::Set(assignments) => {
835                write!(f, "SET {}", display_comma_separated(assignments))
836            }
837            MergeUpdateKind::Wildcard => {
838                write!(f, "SET *")
839            }
840        }
841    }
842}
843
844/// The expression used to update rows within a `MERGE` statement.
845///
846/// Examples
847/// ```sql
848/// UPDATE SET quantity = T.quantity + S.quantity
849/// UPDATE SET *
850/// ```
851///
852/// [Snowflake](https://docs.snowflake.com/en/sql-reference/sql/merge)
853/// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/dml-syntax#merge_statement)
854/// [Oracle](https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/MERGE.html)
855/// [Databricks](https://docs.databricks.com/en/sql/language-manual/delta-merge-into.html)
856#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
857#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
858#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
859pub struct MergeUpdateExpr {
860    /// The `UPDATE` token that starts the sub-expression.
861    pub update_token: AttachedToken,
862    /// The kind of update: explicit assignments or `*` shorthand.
863    pub kind: MergeUpdateKind,
864    /// `where_clause` for the update (Oracle specific)
865    pub update_predicate: Option<Expr>,
866    /// `delete_clause` for the update "delete where" (Oracle specific)
867    pub delete_predicate: Option<Expr>,
868}
869
870impl Display for MergeUpdateExpr {
871    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
872        write!(f, "{}", self.kind)?;
873        if let Some(predicate) = self.update_predicate.as_ref() {
874            write!(f, " WHERE {predicate}")?;
875        }
876        if let Some(predicate) = self.delete_predicate.as_ref() {
877            write!(f, " DELETE WHERE {predicate}")?;
878        }
879        Ok(())
880    }
881}
882
883/// An `OUTPUT` clause on `MERGE`, `INSERT`, `UPDATE`, or `DELETE` (MSSQL).
884///
885/// Example:
886/// OUTPUT $action, deleted.* INTO dbo.temp_products;
887/// <https://learn.microsoft.com/en-us/sql/t-sql/queries/output-clause-transact-sql>
888#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
889#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
890#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
891pub enum OutputClause {
892    /// `OUTPUT` clause
893    Output {
894        /// The `OUTPUT` token that starts the sub-expression.
895        output_token: AttachedToken,
896        /// The select items to output
897        select_items: Vec<SelectItem>,
898        /// Optional `INTO` table to direct the output
899        into_table: Option<SelectInto>,
900    },
901    /// `RETURNING` clause
902    Returning {
903        /// The `RETURNING` token that starts the sub-expression.
904        returning_token: AttachedToken,
905        /// The select items to return
906        select_items: Vec<SelectItem>,
907    },
908}
909
910impl fmt::Display for OutputClause {
911    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
912        match self {
913            OutputClause::Output {
914                output_token: _,
915                select_items,
916                into_table,
917            } => {
918                f.write_str("OUTPUT ")?;
919                display_comma_separated(select_items).fmt(f)?;
920                if let Some(into_table) = into_table {
921                    f.write_str(" ")?;
922                    into_table.fmt(f)?;
923                }
924                Ok(())
925            }
926            OutputClause::Returning {
927                returning_token: _,
928                select_items,
929            } => {
930                f.write_str("RETURNING ")?;
931                display_comma_separated(select_items).fmt(f)
932            }
933        }
934    }
935}
936
937/// A WHEN clause in a conditional multi-table INSERT.
938///
939/// Syntax:
940/// ```sql
941/// WHEN n1 > 100 THEN
942///   INTO t1
943///   INTO t2 (c1, c2) VALUES (n1, n2)
944/// ```
945#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
946#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
947#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
948pub struct MultiTableInsertWhenClause {
949    /// The condition for this WHEN clause
950    pub condition: Expr,
951    /// The INTO clauses to execute when the condition is true
952    pub into_clauses: Vec<MultiTableInsertIntoClause>,
953}
954
955impl Display for MultiTableInsertWhenClause {
956    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
957        write!(f, "WHEN {} THEN", self.condition)?;
958        for into_clause in &self.into_clauses {
959            SpaceOrNewline.fmt(f)?;
960            write!(f, "{}", into_clause)?;
961        }
962        Ok(())
963    }
964}
965
966/// An INTO clause in a multi-table INSERT.
967///
968/// Syntax:
969/// ```sql
970/// INTO <target_table> [ ( <target_col_name> [ , ... ] ) ] [ VALUES ( { <source_col_name> | DEFAULT | NULL } [ , ... ] ) ]
971/// ```
972#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
973#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
974#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
975pub struct MultiTableInsertIntoClause {
976    /// The target table
977    pub table_name: ObjectName,
978    /// The target columns (optional)
979    pub columns: Vec<Ident>,
980    /// The VALUES clause (optional)
981    pub values: Option<MultiTableInsertValues>,
982}
983
984impl Display for MultiTableInsertIntoClause {
985    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
986        write!(f, "INTO {}", self.table_name)?;
987        if !self.columns.is_empty() {
988            write!(f, " ({})", display_comma_separated(&self.columns))?;
989        }
990        if let Some(values) = &self.values {
991            write!(f, " VALUES ({})", display_comma_separated(&values.values))?;
992        }
993        Ok(())
994    }
995}
996
997/// The VALUES clause in a multi-table INSERT INTO clause.
998#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
999#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1000#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1001pub struct MultiTableInsertValues {
1002    /// The values to insert (can be column references, DEFAULT, or NULL)
1003    pub values: Vec<MultiTableInsertValue>,
1004}
1005
1006/// A value in a multi-table INSERT VALUES clause.
1007#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1008#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1009#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1010pub enum MultiTableInsertValue {
1011    /// A column reference or expression from the source
1012    Expr(Expr),
1013    /// The DEFAULT keyword
1014    Default,
1015}
1016
1017impl Display for MultiTableInsertValue {
1018    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1019        match self {
1020            MultiTableInsertValue::Expr(expr) => write!(f, "{}", expr),
1021            MultiTableInsertValue::Default => write!(f, "DEFAULT"),
1022        }
1023    }
1024}
1025
1026/// The type of multi-table INSERT statement(Snowflake).
1027///
1028/// See: <https://docs.snowflake.com/en/sql-reference/sql/insert-multi-table>
1029#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1030#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1031#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1032pub enum MultiTableInsertType {
1033    /// `INSERT ALL` - all matching WHEN clauses are executed
1034    All,
1035    /// `INSERT FIRST` - only the first matching WHEN clause is executed
1036    First,
1037}
1038
1039impl Display for MultiTableInsertType {
1040    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1041        match self {
1042            MultiTableInsertType::All => write!(f, "ALL"),
1043            MultiTableInsertType::First => write!(f, "FIRST"),
1044        }
1045    }
1046}