Skip to main content

sqlparser/dialect/
mssql.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
18use crate::ast::helpers::attached_token::AttachedToken;
19use crate::ast::{
20    BeginEndStatements, ConditionalStatementBlock, ConditionalStatements, CreateTrigger,
21    GranteesType, IfStatement, Statement,
22};
23use crate::dialect::Dialect;
24use crate::keywords::{Keyword, RESERVED_FOR_TABLE_FACTOR};
25use crate::parser::{Parser, ParserError};
26use crate::tokenizer::Token;
27#[cfg(not(feature = "std"))]
28use alloc::{vec, vec::Vec};
29
30/// A [`Dialect`] for [Microsoft SQL Server](https://www.microsoft.com/en-us/sql-server/)
31#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
32#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
33pub struct MsSqlDialect {}
34
35impl Dialect for MsSqlDialect {
36    fn is_delimited_identifier_start(&self, ch: char) -> bool {
37        ch == '"' || ch == '['
38    }
39
40    fn is_identifier_start(&self, ch: char) -> bool {
41        // See https://docs.microsoft.com/en-us/sql/relational-databases/databases/database-identifiers?view=sql-server-2017#rules-for-regular-identifiers
42        ch.is_alphabetic() || ch == '_' || ch == '#' || ch == '@'
43    }
44
45    fn is_identifier_part(&self, ch: char) -> bool {
46        ch.is_alphabetic()
47            || ch.is_ascii_digit()
48            || ch == '@'
49            || ch == '$'
50            || ch == '#'
51            || ch == '_'
52    }
53
54    fn identifier_quote_style(&self, _identifier: &str) -> Option<char> {
55        Some('[')
56    }
57
58    /// SQL Server has `CONVERT(type, value)` instead of `CONVERT(value, type)`
59    /// <https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16>
60    fn convert_type_before_value(&self) -> bool {
61        true
62    }
63
64    fn supports_outer_join_operator(&self) -> bool {
65        true
66    }
67
68    /// SQL Server supports `$` as a prefix for money literals
69    /// <https://learn.microsoft.com/en-us/sql/t-sql/data-types/constants-transact-sql?view=sql-server-ver17#money-constants>
70    fn supports_dollar_as_money_prefix(&self) -> bool {
71        true
72    }
73
74    fn supports_create_proc_syntax(&self) -> bool {
75        true
76    }
77
78    fn supports_connect_by(&self) -> bool {
79        true
80    }
81
82    fn supports_eq_alias_assignment(&self) -> bool {
83        true
84    }
85
86    fn supports_try_convert(&self) -> bool {
87        true
88    }
89
90    /// In MSSQL, there is no boolean type, and `true` and `false` are valid column names
91    fn supports_boolean_literals(&self) -> bool {
92        false
93    }
94
95    fn supports_named_fn_args_with_colon_operator(&self) -> bool {
96        true
97    }
98
99    fn supports_named_fn_args_with_expr_name(&self) -> bool {
100        true
101    }
102
103    fn supports_named_fn_args_with_rarrow_operator(&self) -> bool {
104        false
105    }
106
107    fn supports_start_transaction_modifier(&self) -> bool {
108        true
109    }
110
111    fn supports_end_transaction_modifier(&self) -> bool {
112        true
113    }
114
115    /// See: <https://learn.microsoft.com/en-us/sql/t-sql/statements/set-statements-transact-sql>
116    fn supports_set_stmt_without_operator(&self) -> bool {
117        true
118    }
119
120    /// See: <https://learn.microsoft.com/en-us/sql/relational-databases/tables/querying-data-in-a-system-versioned-temporal-table>
121    fn supports_table_versioning(&self) -> bool {
122        true
123    }
124
125    /// See <https://learn.microsoft.com/en-us/sql/t-sql/language-elements/slash-star-comment-transact-sql?view=sql-server-ver16>
126    fn supports_nested_comments(&self) -> bool {
127        true
128    }
129
130    /// See <https://learn.microsoft.com/en-us/sql/t-sql/queries/from-transact-sql>
131    fn supports_object_name_double_dot_notation(&self) -> bool {
132        true
133    }
134
135    /// See <https://learn.microsoft.com/en-us/sql/relational-databases/security/authentication-access/server-level-roles>
136    fn get_reserved_grantees_types(&self) -> &[GranteesType] {
137        &[GranteesType::Public]
138    }
139
140    fn is_select_item_alias(&self, explicit: bool, kw: &Keyword, parser: &mut Parser) -> bool {
141        !Self::is_reserved_for_alias(kw) && (explicit || self.is_column_alias(kw, parser))
142    }
143
144    /// LIMIT is not a reserved word in Transact-SQL.
145    /// See <https://learn.microsoft.com/en-us/sql/t-sql/language-elements/reserved-keywords-transact-sql>
146    fn is_table_factor(&self, kw: &Keyword, _parser: &mut Parser) -> bool {
147        kw == &Keyword::LIMIT || !RESERVED_FOR_TABLE_FACTOR.contains(kw)
148    }
149
150    fn is_table_factor_alias(&self, explicit: bool, kw: &Keyword, parser: &mut Parser) -> bool {
151        !Self::is_reserved_for_alias(kw) && (explicit || self.is_table_alias(kw, parser))
152    }
153
154    fn parse_statement(&self, parser: &mut Parser) -> Option<Result<Statement, ParserError>> {
155        if parser.parse_keyword(Keyword::BEGIN) {
156            // Check if this is a BEGIN...END block rather than BEGIN TRANSACTION
157            let is_block = parser
158                .maybe_parse(|p| {
159                    if p.parse_transaction_modifier().is_some()
160                        || p.parse_one_of_keywords(&[
161                            Keyword::TRANSACTION,
162                            Keyword::WORK,
163                            Keyword::TRAN,
164                        ])
165                        .is_some()
166                        || matches!(p.peek_token_ref().token, Token::SemiColon | Token::EOF)
167                    {
168                        p.expected_ref("statement", p.peek_token_ref())
169                    } else {
170                        Ok(())
171                    }
172                })
173                .unwrap_or(None)
174                .is_some();
175            if is_block {
176                Some(parser.parse_begin_exception_end())
177            } else {
178                parser.prev_token();
179                None
180            }
181        } else if parser.peek_keyword(Keyword::IF) {
182            Some(self.parse_if_stmt(parser))
183        } else if parser.parse_keywords(&[Keyword::CREATE, Keyword::TRIGGER]) {
184            Some(self.parse_create_trigger(parser, false))
185        } else if parser.parse_keywords(&[
186            Keyword::CREATE,
187            Keyword::OR,
188            Keyword::ALTER,
189            Keyword::TRIGGER,
190        ]) {
191            Some(self.parse_create_trigger(parser, true))
192        } else {
193            None
194        }
195    }
196
197    fn get_next_precedence(&self, parser: &Parser) -> Option<Result<u8, ParserError>> {
198        let token = parser.peek_token_ref();
199        match &token.token {
200            // lowest prec to prevent it from turning into a binary op
201            Token::Colon => Some(Ok(self.prec_unknown())),
202            _ => None,
203        }
204    }
205}
206
207impl MsSqlDialect {
208    /// Keywords excluded from explicit and implicit aliases.
209    fn is_reserved_for_alias(kw: &Keyword) -> bool {
210        matches!(
211            kw,
212            Keyword::IF
213                | Keyword::ELSE
214                | Keyword::DECLARE
215                | Keyword::EXEC
216                | Keyword::EXECUTE
217                | Keyword::INSERT
218                | Keyword::UPDATE
219                | Keyword::DELETE
220                | Keyword::DROP
221                | Keyword::CREATE
222                | Keyword::ALTER
223                | Keyword::TRUNCATE
224                | Keyword::PRINT
225                | Keyword::WHILE
226                | Keyword::RETURN
227                | Keyword::THROW
228                | Keyword::RAISERROR
229                | Keyword::MERGE
230        )
231    }
232
233    /// ```sql
234    /// IF boolean_expression
235    ///     { sql_statement | statement_block }
236    /// [ ELSE
237    ///     { sql_statement | statement_block } ]
238    /// ```
239    fn parse_if_stmt(&self, parser: &mut Parser) -> Result<Statement, ParserError> {
240        let if_token = parser.expect_keyword(Keyword::IF)?;
241
242        let condition = parser.parse_expr()?;
243
244        let if_block = if parser.peek_keyword(Keyword::BEGIN) {
245            let begin_token = parser.expect_keyword(Keyword::BEGIN)?;
246            let statements = self.parse_statement_list(parser, Some(Keyword::END))?;
247            let end_token = parser.expect_keyword(Keyword::END)?;
248            ConditionalStatementBlock {
249                start_token: AttachedToken(if_token),
250                condition: Some(condition),
251                then_token: None,
252                conditional_statements: ConditionalStatements::BeginEnd(BeginEndStatements {
253                    begin_token: AttachedToken(begin_token),
254                    statements,
255                    end_token: AttachedToken(end_token),
256                }),
257            }
258        } else {
259            let stmt = parser.parse_statement()?;
260            ConditionalStatementBlock {
261                start_token: AttachedToken(if_token),
262                condition: Some(condition),
263                then_token: None,
264                conditional_statements: ConditionalStatements::Sequence {
265                    statements: vec![stmt],
266                },
267            }
268        };
269
270        let mut prior_statement_ended_with_semi_colon = false;
271        while let Token::SemiColon = parser.peek_token_ref().token {
272            parser.advance_token();
273            prior_statement_ended_with_semi_colon = true;
274        }
275
276        let mut else_block = None;
277        if parser.peek_keyword(Keyword::ELSE) {
278            let else_token = parser.expect_keyword(Keyword::ELSE)?;
279            if parser.peek_keyword(Keyword::BEGIN) {
280                let begin_token = parser.expect_keyword(Keyword::BEGIN)?;
281                let statements = self.parse_statement_list(parser, Some(Keyword::END))?;
282                let end_token = parser.expect_keyword(Keyword::END)?;
283                else_block = Some(ConditionalStatementBlock {
284                    start_token: AttachedToken(else_token),
285                    condition: None,
286                    then_token: None,
287                    conditional_statements: ConditionalStatements::BeginEnd(BeginEndStatements {
288                        begin_token: AttachedToken(begin_token),
289                        statements,
290                        end_token: AttachedToken(end_token),
291                    }),
292                });
293            } else {
294                let stmt = parser.parse_statement()?;
295                else_block = Some(ConditionalStatementBlock {
296                    start_token: AttachedToken(else_token),
297                    condition: None,
298                    then_token: None,
299                    conditional_statements: ConditionalStatements::Sequence {
300                        statements: vec![stmt],
301                    },
302                });
303            }
304        } else if prior_statement_ended_with_semi_colon {
305            parser.prev_token();
306        }
307
308        Ok(IfStatement {
309            if_block,
310            else_block,
311            elseif_blocks: Vec::new(),
312            end_token: None,
313        }
314        .into())
315    }
316
317    /// Parse `CREATE TRIGGER` for [MsSql]
318    ///
319    /// [MsSql]: https://learn.microsoft.com/en-us/sql/t-sql/statements/create-trigger-transact-sql
320    fn parse_create_trigger(
321        &self,
322        parser: &mut Parser,
323        or_alter: bool,
324    ) -> Result<Statement, ParserError> {
325        let name = parser.parse_object_name(false)?;
326        parser.expect_keyword_is(Keyword::ON)?;
327        let table_name = parser.parse_object_name(false)?;
328        let period = parser.parse_trigger_period()?;
329        let events = parser.parse_comma_separated(Parser::parse_trigger_event)?;
330
331        parser.expect_keyword_is(Keyword::AS)?;
332        let statements = Some(parser.parse_conditional_statements(&[Keyword::END])?);
333
334        Ok(CreateTrigger {
335            or_alter,
336            temporary: false,
337            or_replace: false,
338            is_constraint: false,
339            name,
340            period: Some(period),
341            period_before_table: false,
342            events,
343            table_name,
344            referenced_table_name: None,
345            referencing: Vec::new(),
346            trigger_object: None,
347            condition: None,
348            exec_body: None,
349            statements_as: true,
350            statements,
351            characteristics: None,
352        }
353        .into())
354    }
355
356    /// Parse a sequence of statements, optionally separated by semicolon.
357    ///
358    /// Stops parsing when reaching EOF or the given keyword.
359    fn parse_statement_list(
360        &self,
361        parser: &mut Parser,
362        terminal_keyword: Option<Keyword>,
363    ) -> Result<Vec<Statement>, ParserError> {
364        let mut stmts = Vec::new();
365        loop {
366            if let Token::EOF = parser.peek_token_ref().token {
367                break;
368            }
369            if let Some(term) = terminal_keyword {
370                if parser.peek_keyword(term) {
371                    break;
372                }
373            }
374            stmts.push(parser.parse_statement()?);
375            while let Token::SemiColon = parser.peek_token_ref().token {
376                parser.advance_token();
377            }
378        }
379        Ok(stmts)
380    }
381}