From 22ecf592a1a827ddf67317c92cc23999da1c640d Mon Sep 17 00:00:00 2001 From: osipovartem Date: Fri, 11 Jul 2025 19:27:14 +0300 Subject: [PATCH 1/7] Snowflake create database --- src/ast/ddl.rs | 120 +++++++++- src/ast/helpers/mod.rs | 1 + src/ast/helpers/stmt_create_database.rs | 306 ++++++++++++++++++++++++ src/ast/mod.rs | 61 ++++- src/ast/spans.rs | 43 ++-- src/dialect/snowflake.rs | 122 +++++++++- src/keywords.rs | 6 + src/parser/mod.rs | 9 + tests/sqlparser_snowflake.rs | 60 +++++ 9 files changed, 694 insertions(+), 34 deletions(-) create mode 100644 src/ast/helpers/stmt_create_database.rs diff --git a/src/ast/ddl.rs b/src/ast/ddl.rs index 51e057840..25fbf1a5d 100644 --- a/src/ast/ddl.rs +++ b/src/ast/ddl.rs @@ -30,11 +30,11 @@ use sqlparser_derive::{Visit, VisitMut}; use crate::ast::value::escape_single_quote_string; use crate::ast::{ - display_comma_separated, display_separated, ArgMode, CommentDef, CreateFunctionBody, - CreateFunctionUsing, DataType, Expr, FunctionBehavior, FunctionCalledOnNull, - FunctionDeterminismSpecifier, FunctionParallel, Ident, IndexColumn, MySQLColumnPosition, - ObjectName, OperateFunctionArg, OrderByExpr, ProjectionSelect, SequenceOptions, SqlOption, Tag, - Value, ValueWithSpan, + display_comma_separated, display_separated, ArgMode, CatalogSyncNamespaceMode, CommentDef, + CreateFunctionBody, CreateFunctionUsing, DataType, Expr, FunctionBehavior, + FunctionCalledOnNull, FunctionDeterminismSpecifier, FunctionParallel, Ident, IndexColumn, + MySQLColumnPosition, ObjectName, OperateFunctionArg, OrderByExpr, ProjectionSelect, + SequenceOptions, SqlOption, StorageSerializationPolicy, Tag, Value, ValueWithSpan, }; use crate::keywords::Keyword; use crate::tokenizer::Token; @@ -2524,3 +2524,113 @@ impl fmt::Display for CreateConnector { Ok(()) } } + +#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))] +pub struct CreateSnowflakeDatabase { + pub or_replace: bool, + pub transient: bool, + pub if_not_exists: bool, + pub name: ObjectName, + pub clone: Option, + pub data_retention_time_in_days: Option, + pub max_data_extension_time_in_days: Option, + pub external_volume: Option, + pub catalog: Option, + pub replace_invalid_characters: Option, + pub default_ddl_collation: Option, + pub storage_serialization_policy: Option, + pub comment: Option, + pub catalog_sync: Option, + pub catalog_sync_namespace_mode: Option, + pub catalog_sync_namespace_flatten_delimiter: Option, + pub with_tags: Option>, + pub with_contacts: Option>, +} + +impl fmt::Display for CreateSnowflakeDatabase { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!( + f, + "CREATE {or_replace}{transient}DATABASE {if_not_exists}{name}", + or_replace = if self.or_replace { "OR REPLACE " } else { "" }, + transient = if self.transient { "TRANSIENT " } else { "" }, + if_not_exists = if self.if_not_exists { + "IF NOT EXISTS " + } else { + "" + }, + name = self.name, + )?; + + if let Some(clone) = &self.clone { + write!(f, " CLONE {clone}")?; + } + + if let Some(value) = self.data_retention_time_in_days { + write!(f, " DATA_RETENTION_TIME_IN_DAYS = {value}")?; + } + + if let Some(value) = self.max_data_extension_time_in_days { + write!(f, " MAX_DATA_EXTENSION_TIME_IN_DAYS = {value}")?; + } + + if let Some(vol) = &self.external_volume { + write!(f, " EXTERNAL_VOLUME = '{vol}'")?; + } + + if let Some(cat) = &self.catalog { + write!(f, " CATALOG = '{cat}'")?; + } + + if let Some(true) = self.replace_invalid_characters { + write!(f, " REPLACE_INVALID_CHARACTERS = TRUE")?; + } else if let Some(false) = self.replace_invalid_characters { + write!(f, " REPLACE_INVALID_CHARACTERS = FALSE")?; + } + + if let Some(collation) = &self.default_ddl_collation { + write!(f, " DEFAULT_DDL_COLLATION = '{collation}'")?; + } + + if let Some(policy) = &self.storage_serialization_policy { + write!(f, " STORAGE_SERIALIZATION_POLICY = {policy}")?; + } + + if let Some(comment) = &self.comment { + write!(f, " COMMENT = '{comment}'")?; + } + + if let Some(sync) = &self.catalog_sync { + write!(f, " CATALOG_SYNC = '{sync}'")?; + } + + if let Some(mode) = &self.catalog_sync_namespace_mode { + write!(f, " CATALOG_SYNC_NAMESPACE_MODE = {mode}")?; + } + + if let Some(delim) = &self.catalog_sync_namespace_flatten_delimiter { + write!(f, " CATALOG_SYNC_NAMESPACE_FLATTEN_DELIMITER = '{delim}'")?; + } + + if let Some(tags) = &self.with_tags { + write!(f, " WITH TAG ({})", display_comma_separated(tags))?; + } + + if let Some(contacts) = &self.with_contacts { + write!( + f, + " WITH CONTACT ({})", + display_comma_separated( + &contacts + .iter() + .map(|(purpose, contact)| format!("{purpose} = {contact}")) + .collect::>() + ) + )?; + } + + Ok(()) + } +} diff --git a/src/ast/helpers/mod.rs b/src/ast/helpers/mod.rs index 55831220d..3efbcf7b0 100644 --- a/src/ast/helpers/mod.rs +++ b/src/ast/helpers/mod.rs @@ -16,5 +16,6 @@ // under the License. pub mod attached_token; pub mod key_value_options; +pub mod stmt_create_database; pub mod stmt_create_table; pub mod stmt_data_loading; diff --git a/src/ast/helpers/stmt_create_database.rs b/src/ast/helpers/stmt_create_database.rs new file mode 100644 index 000000000..6f3bd1621 --- /dev/null +++ b/src/ast/helpers/stmt_create_database.rs @@ -0,0 +1,306 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#[cfg(not(feature = "std"))] +use alloc::{boxed::Box, format, string::String, vec, vec::Vec}; + +#[cfg(feature = "serde")] +use serde::{Deserialize, Serialize}; + +#[cfg(feature = "visitor")] +use sqlparser_derive::{Visit, VisitMut}; + +use crate::ast::ddl::CreateSnowflakeDatabase; +use crate::ast::{ + CatalogSyncNamespaceMode, ObjectName, Statement, StorageSerializationPolicy, Tag, +}; +use crate::parser::ParserError; + +/// Builder for create database statement variant ([1]). +/// +/// This structure helps building and accessing a create database with more ease, without needing to: +/// - Match the enum itself a lot of times; or +/// - Moving a lot of variables around the code. +/// +/// # Example +/// ```rust +/// use sqlparser::ast::helpers::stmt_create_database::CreateDatabaseBuilder; +/// use sqlparser::ast::{ColumnDef, Ident, ObjectName}; +/// let builder = CreateDatabaseBuilder::new(ObjectName::from(vec![Ident::new("database_name")])) +/// .if_not_exists(true); +/// // You can access internal elements with ease +/// assert!(builder.if_not_exists); +/// // Convert to a statement +/// assert_eq!( +/// builder.build().to_string(), +/// "CREATE DATABASE IF NOT EXISTS database_name" +/// ) +/// ``` +/// +/// [1]: crate::ast::Statement::CreateSnowflakeDatabase +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))] +pub struct CreateDatabaseBuilder { + pub or_replace: bool, + pub transient: bool, + pub if_not_exists: bool, + pub name: ObjectName, + pub clone: Option, + pub data_retention_time_in_days: Option, + pub max_data_extension_time_in_days: Option, + pub external_volume: Option, + pub catalog: Option, + pub replace_invalid_characters: Option, + pub default_ddl_collation: Option, + pub storage_serialization_policy: Option, + pub comment: Option, + pub catalog_sync: Option, + pub catalog_sync_namespace_mode: Option, + pub catalog_sync_namespace_flatten_delimiter: Option, + pub with_tags: Option>, + pub with_contacts: Option>, +} + +impl CreateDatabaseBuilder { + pub fn new(name: ObjectName) -> Self { + Self { + or_replace: false, + transient: false, + if_not_exists: false, + name, + clone: None, + data_retention_time_in_days: None, + max_data_extension_time_in_days: None, + external_volume: None, + catalog: None, + replace_invalid_characters: None, + default_ddl_collation: None, + storage_serialization_policy: None, + comment: None, + catalog_sync: None, + catalog_sync_namespace_mode: None, + catalog_sync_namespace_flatten_delimiter: None, + with_tags: None, + with_contacts: None, + } + } + + pub fn or_replace(mut self, or_replace: bool) -> Self { + self.or_replace = or_replace; + self + } + + pub fn transient(mut self, transient: bool) -> Self { + self.transient = transient; + self + } + + pub fn if_not_exists(mut self, if_not_exists: bool) -> Self { + self.if_not_exists = if_not_exists; + self + } + + pub fn clone_clause(mut self, clone: Option) -> Self { + self.clone = clone; + self + } + + pub fn data_retention_time_in_days(mut self, data_retention_time_in_days: Option) -> Self { + self.data_retention_time_in_days = data_retention_time_in_days; + self + } + + pub fn max_data_extension_time_in_days( + mut self, + max_data_extension_time_in_days: Option, + ) -> Self { + self.max_data_extension_time_in_days = max_data_extension_time_in_days; + self + } + + pub fn external_volume(mut self, external_volume: Option) -> Self { + self.external_volume = external_volume; + self + } + + pub fn catalog(mut self, catalog: Option) -> Self { + self.catalog = catalog; + self + } + + pub fn replace_invalid_characters(mut self, replace_invalid_characters: Option) -> Self { + self.replace_invalid_characters = replace_invalid_characters; + self + } + + pub fn default_ddl_collation(mut self, default_ddl_collation: Option) -> Self { + self.default_ddl_collation = default_ddl_collation; + self + } + + pub fn storage_serialization_policy( + mut self, + storage_serialization_policy: Option, + ) -> Self { + self.storage_serialization_policy = storage_serialization_policy; + self + } + + pub fn comment(mut self, comment: Option) -> Self { + self.comment = comment; + self + } + + pub fn catalog_sync(mut self, catalog_sync: Option) -> Self { + self.catalog_sync = catalog_sync; + self + } + + pub fn catalog_sync_namespace_mode( + mut self, + catalog_sync_namespace_mode: Option, + ) -> Self { + self.catalog_sync_namespace_mode = catalog_sync_namespace_mode; + self + } + + pub fn catalog_sync_namespace_flatten_delimiter( + mut self, + catalog_sync_namespace_flatten_delimiter: Option, + ) -> Self { + self.catalog_sync_namespace_flatten_delimiter = catalog_sync_namespace_flatten_delimiter; + self + } + + pub fn with_tags(mut self, with_tags: Option>) -> Self { + self.with_tags = with_tags; + self + } + + pub fn with_contacts(mut self, with_contacts: Option>) -> Self { + self.with_contacts = with_contacts; + self + } + + pub fn build(self) -> Statement { + Statement::CreateSnowflakeDatabase(CreateSnowflakeDatabase { + or_replace: self.or_replace, + transient: self.transient, + if_not_exists: self.if_not_exists, + name: self.name, + clone: self.clone, + data_retention_time_in_days: self.data_retention_time_in_days, + max_data_extension_time_in_days: self.max_data_extension_time_in_days, + external_volume: self.external_volume, + catalog: self.catalog, + replace_invalid_characters: self.replace_invalid_characters, + default_ddl_collation: self.default_ddl_collation, + storage_serialization_policy: self.storage_serialization_policy, + comment: self.comment, + catalog_sync: self.catalog_sync, + catalog_sync_namespace_mode: self.catalog_sync_namespace_mode, + catalog_sync_namespace_flatten_delimiter: self.catalog_sync_namespace_flatten_delimiter, + with_tags: self.with_tags, + with_contacts: self.with_contacts, + }) + } +} + +impl TryFrom for CreateDatabaseBuilder { + type Error = ParserError; + + fn try_from(stmt: Statement) -> Result { + match stmt { + Statement::CreateSnowflakeDatabase(CreateSnowflakeDatabase { + or_replace, + transient, + if_not_exists, + name, + clone, + data_retention_time_in_days, + max_data_extension_time_in_days, + external_volume, + catalog, + replace_invalid_characters, + default_ddl_collation, + storage_serialization_policy, + comment, + catalog_sync, + catalog_sync_namespace_mode, + catalog_sync_namespace_flatten_delimiter, + with_tags, + with_contacts, + }) => Ok(Self { + or_replace, + transient, + if_not_exists, + name, + clone, + data_retention_time_in_days, + max_data_extension_time_in_days, + external_volume, + catalog, + replace_invalid_characters, + default_ddl_collation, + storage_serialization_policy, + comment, + catalog_sync, + catalog_sync_namespace_mode, + catalog_sync_namespace_flatten_delimiter, + with_tags, + with_contacts, + }), + _ => Err(ParserError::ParserError(format!( + "Expected create database statement, but received: {stmt}" + ))), + } + } +} + +#[cfg(test)] +mod tests { + use crate::ast::helpers::stmt_create_database::CreateDatabaseBuilder; + use crate::ast::helpers::stmt_create_table::CreateTableBuilder; + use crate::ast::{Ident, ObjectName, Statement}; + use crate::parser::ParserError; + + #[test] + pub fn test_from_valid_statement() { + let builder = CreateDatabaseBuilder::new(ObjectName::from(vec![Ident::new("db_name")])); + + let stmt = builder.clone().build(); + + assert_eq!(builder, CreateDatabaseBuilder::try_from(stmt).unwrap()); + } + + #[test] + pub fn test_from_invalid_statement() { + let stmt = Statement::Commit { + chain: false, + end: false, + modifier: None, + }; + + assert_eq!( + CreateDatabaseBuilder::try_from(stmt).unwrap_err(), + ParserError::ParserError( + "Expected create database statement, but received: COMMIT".to_owned() + ) + ); + } +} diff --git a/src/ast/mod.rs b/src/ast/mod.rs index 75e88f8a8..5c13f9ace 100644 --- a/src/ast/mod.rs +++ b/src/ast/mod.rs @@ -63,12 +63,12 @@ pub use self::ddl::{ AlterTypeAddValuePosition, AlterTypeOperation, AlterTypeRename, AlterTypeRenameValue, ClusteredBy, ColumnDef, ColumnOption, ColumnOptionDef, ColumnOptions, ColumnPolicy, ColumnPolicyProperty, ConstraintCharacteristics, CreateConnector, CreateDomain, CreateFunction, - Deduplicate, DeferrableInitial, DropBehavior, GeneratedAs, GeneratedExpressionMode, - IdentityParameters, IdentityProperty, IdentityPropertyFormatKind, IdentityPropertyKind, - IdentityPropertyOrder, IndexOption, IndexType, KeyOrIndexDisplay, NullsDistinctOption, Owner, - Partition, ProcedureParam, ReferentialAction, ReplicaIdentity, TableConstraint, - TagsColumnOption, UserDefinedTypeCompositeAttributeDef, UserDefinedTypeRepresentation, - ViewColumnDef, + CreateSnowflakeDatabase, Deduplicate, DeferrableInitial, DropBehavior, GeneratedAs, + GeneratedExpressionMode, IdentityParameters, IdentityProperty, IdentityPropertyFormatKind, + IdentityPropertyKind, IdentityPropertyOrder, IndexOption, IndexType, KeyOrIndexDisplay, + NullsDistinctOption, Owner, Partition, ProcedureParam, ReferentialAction, ReplicaIdentity, + TableConstraint, TagsColumnOption, UserDefinedTypeCompositeAttributeDef, + UserDefinedTypeRepresentation, ViewColumnDef, }; pub use self::dml::{CreateIndex, CreateTable, Delete, IndexColumn, Insert}; pub use self::operator::{BinaryOperator, UnaryOperator}; @@ -3857,6 +3857,31 @@ pub enum Statement { managed_location: Option, }, /// ```sql + /// CREATE [ OR REPLACE ] [ TRANSIENT ] DATABASE [ IF NOT EXISTS ] + /// [ CLONE + /// [ { AT | BEFORE } ( { TIMESTAMP => | OFFSET => | STATEMENT => } ) ] + /// [ IGNORE TABLES WITH INSUFFICIENT DATA RETENTION ] + /// [ IGNORE HYBRID TABLES ] ] + /// [ DATA_RETENTION_TIME_IN_DAYS = ] + /// [ MAX_DATA_EXTENSION_TIME_IN_DAYS = ] + /// [ EXTERNAL_VOLUME = ] + /// [ CATALOG = ] + /// [ REPLACE_INVALID_CHARACTERS = { TRUE | FALSE } ] + /// [ DEFAULT_DDL_COLLATION = '' ] + /// [ STORAGE_SERIALIZATION_POLICY = { COMPATIBLE | OPTIMIZED } ] + /// [ COMMENT = '' ] + /// [ CATALOG_SYNC = '' ] + /// [ CATALOG_SYNC_NAMESPACE_MODE = { NEST | FLATTEN } ] + /// [ CATALOG_SYNC_NAMESPACE_FLATTEN_DELIMITER = '' ] + /// [ [ WITH ] TAG ( = '' [ , = '' , ... ] ) ] + /// [ WITH CONTACT ( = [ , = ... ] ) ] + /// ``` + /// See: + /// + /// + /// Creates a new database in the system. + CreateSnowflakeDatabase(CreateSnowflakeDatabase), + /// ```sql /// CREATE FUNCTION /// ``` /// @@ -4805,6 +4830,7 @@ impl fmt::Display for Statement { } Ok(()) } + Statement::CreateSnowflakeDatabase(create_database) => create_database.fmt(f), Statement::CreateFunction(create_function) => create_function.fmt(f), Statement::CreateDomain(create_domain) => create_domain.fmt(f), Statement::CreateTrigger { @@ -9950,6 +9976,29 @@ impl Display for StorageSerializationPolicy { } } +/// Snowflake CatalogSyncNamespaceMode +/// ```sql +/// [ CATALOG_SYNC_NAMESPACE_MODE = { NEST | FLATTEN } ] +/// ``` +/// +/// +#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))] +pub enum CatalogSyncNamespaceMode { + Nest, + Flatten, +} + +impl Display for CatalogSyncNamespaceMode { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + CatalogSyncNamespaceMode::Nest => write!(f, "NEST"), + CatalogSyncNamespaceMode::Flatten => write!(f, "FLATTEN"), + } + } +} + /// Variants of the Snowflake `COPY INTO` statement #[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] diff --git a/src/ast/spans.rs b/src/ast/spans.rs index 3e82905e1..c4ad79c82 100644 --- a/src/ast/spans.rs +++ b/src/ast/spans.rs @@ -21,24 +21,24 @@ use core::iter; use crate::tokenizer::Span; use super::{ - dcl::SecondaryRoles, value::ValueWithSpan, AccessExpr, AlterColumnOperation, - AlterIndexOperation, AlterTableOperation, Array, Assignment, AssignmentTarget, AttachedToken, - BeginEndStatements, CaseStatement, CloseCursor, ClusteredIndex, ColumnDef, ColumnOption, - ColumnOptionDef, ConditionalStatementBlock, ConditionalStatements, ConflictTarget, ConnectBy, - ConstraintCharacteristics, CopySource, CreateIndex, CreateTable, CreateTableOptions, Cte, - Delete, DoUpdate, ExceptSelectItem, ExcludeSelectItem, Expr, ExprWithAlias, Fetch, FromTable, - Function, FunctionArg, FunctionArgExpr, FunctionArgumentClause, FunctionArgumentList, - FunctionArguments, GroupByExpr, HavingBound, IfStatement, IlikeSelectItem, IndexColumn, Insert, - Interpolate, InterpolateExpr, Join, JoinConstraint, JoinOperator, JsonPath, JsonPathElem, - LateralView, LimitClause, MatchRecognizePattern, Measure, NamedParenthesizedList, - NamedWindowDefinition, ObjectName, ObjectNamePart, Offset, OnConflict, OnConflictAction, - OnInsert, OpenStatement, OrderBy, OrderByExpr, OrderByKind, Partition, PivotValueSource, - ProjectionSelect, Query, RaiseStatement, RaiseStatementValue, ReferentialAction, - RenameSelectItem, ReplaceSelectElement, ReplaceSelectItem, Select, SelectInto, SelectItem, - SetExpr, SqlOption, Statement, Subscript, SymbolDefinition, TableAlias, TableAliasColumnDef, - TableConstraint, TableFactor, TableObject, TableOptionsClustered, TableWithJoins, - UpdateTableFromKind, Use, Value, Values, ViewColumnDef, WhileStatement, - WildcardAdditionalOptions, With, WithFill, + dcl::SecondaryRoles, ddl::CreateSnowflakeDatabase, value::ValueWithSpan, AccessExpr, + AlterColumnOperation, AlterIndexOperation, AlterTableOperation, Array, Assignment, + AssignmentTarget, AttachedToken, BeginEndStatements, CaseStatement, CloseCursor, + ClusteredIndex, ColumnDef, ColumnOption, ColumnOptionDef, ConditionalStatementBlock, + ConditionalStatements, ConflictTarget, ConnectBy, ConstraintCharacteristics, CopySource, + CreateIndex, CreateTable, CreateTableOptions, Cte, Delete, DoUpdate, ExceptSelectItem, + ExcludeSelectItem, Expr, ExprWithAlias, Fetch, FromTable, Function, FunctionArg, + FunctionArgExpr, FunctionArgumentClause, FunctionArgumentList, FunctionArguments, GroupByExpr, + HavingBound, IfStatement, IlikeSelectItem, IndexColumn, Insert, Interpolate, InterpolateExpr, + Join, JoinConstraint, JoinOperator, JsonPath, JsonPathElem, LateralView, LimitClause, + MatchRecognizePattern, Measure, NamedParenthesizedList, NamedWindowDefinition, ObjectName, + ObjectNamePart, Offset, OnConflict, OnConflictAction, OnInsert, OpenStatement, OrderBy, + OrderByExpr, OrderByKind, Partition, PivotValueSource, ProjectionSelect, Query, RaiseStatement, + RaiseStatementValue, ReferentialAction, RenameSelectItem, ReplaceSelectElement, + ReplaceSelectItem, Select, SelectInto, SelectItem, SetExpr, SqlOption, Statement, Subscript, + SymbolDefinition, TableAlias, TableAliasColumnDef, TableConstraint, TableFactor, TableObject, + TableOptionsClustered, TableWithJoins, UpdateTableFromKind, Use, Value, Values, ViewColumnDef, + WhileStatement, WildcardAdditionalOptions, With, WithFill, }; /// Given an iterator of spans, return the [Span::union] of all spans. @@ -386,6 +386,7 @@ impl Spanned for Statement { .chain(returning.iter().flat_map(|i| i.iter().map(|k| k.span()))), ), Statement::Delete(delete) => delete.span(), + Statement::CreateSnowflakeDatabase(create_database) => create_database.span(), Statement::CreateView { or_alter: _, or_replace: _, @@ -616,6 +617,12 @@ impl Spanned for CreateTable { } } +impl Spanned for CreateSnowflakeDatabase { + fn span(&self) -> Span { + union_spans(core::iter::once(self.name.span()).chain(self.clone.iter().map(|c| c.span()))) + } +} + impl Spanned for ColumnDef { fn span(&self) -> Span { let ColumnDef { diff --git a/src/dialect/snowflake.rs b/src/dialect/snowflake.rs index 3b1eff39a..1575e1f20 100644 --- a/src/dialect/snowflake.rs +++ b/src/dialect/snowflake.rs @@ -18,15 +18,17 @@ #[cfg(not(feature = "std"))] use crate::alloc::string::ToString; use crate::ast::helpers::key_value_options::{KeyValueOption, KeyValueOptionType, KeyValueOptions}; +use crate::ast::helpers::stmt_create_database::CreateDatabaseBuilder; use crate::ast::helpers::stmt_create_table::CreateTableBuilder; use crate::ast::helpers::stmt_data_loading::{ FileStagingCommand, StageLoadSelectItem, StageLoadSelectItemKind, StageParamsObject, }; use crate::ast::{ - ColumnOption, ColumnPolicy, ColumnPolicyProperty, CopyIntoSnowflakeKind, Ident, - IdentityParameters, IdentityProperty, IdentityPropertyFormatKind, IdentityPropertyKind, - IdentityPropertyOrder, ObjectName, ObjectNamePart, RowAccessPolicy, ShowObjects, SqlOption, - Statement, TagsColumnOption, WrappedCollection, + CatalogSyncNamespaceMode, ColumnOption, ColumnPolicy, ColumnPolicyProperty, + CopyIntoSnowflakeKind, Ident, IdentityParameters, IdentityProperty, IdentityPropertyFormatKind, + IdentityPropertyKind, IdentityPropertyOrder, ObjectName, ObjectNamePart, RowAccessPolicy, + ShowObjects, SqlOption, Statement, StorageSerializationPolicy, TagsColumnOption, + WrappedCollection, }; use crate::dialect::{Dialect, Precedence}; use crate::keywords::Keyword; @@ -42,7 +44,6 @@ use alloc::vec::Vec; use alloc::{format, vec}; use super::keywords::RESERVED_FOR_IDENTIFIER; -use sqlparser::ast::StorageSerializationPolicy; const RESERVED_KEYWORDS_FOR_SELECT_ITEM_OPERATOR: [Keyword; 1] = [Keyword::CONNECT_BY_ROOT]; /// A [`Dialect`] for [Snowflake](https://www.snowflake.com/) @@ -182,6 +183,8 @@ impl Dialect for SnowflakeDialect { return Some(parse_create_table( or_replace, global, temporary, volatile, transient, iceberg, parser, )); + } else if parser.parse_keyword(Keyword::DATABASE) { + return Some(parse_create_database(or_replace, transient, parser)); } else { // need to go back with the cursor let mut back = 1; @@ -731,6 +734,115 @@ pub fn parse_create_table( Ok(builder.build()) } +/// Parse snowflake create database statement. +/// +pub fn parse_create_database( + or_replace: bool, + transient: bool, + parser: &mut Parser, +) -> Result { + let if_not_exists = parser.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]); + let name = parser.parse_object_name(false)?; + + let mut builder = CreateDatabaseBuilder::new(name) + .or_replace(or_replace) + .transient(transient) + .if_not_exists(if_not_exists); + + loop { + let next_token = parser.next_token(); + match &next_token.token { + Token::Word(word) => match word.keyword { + Keyword::CLONE => { + builder = builder.clone_clause(Some(parser.parse_object_name(false)?)); + } + Keyword::DATA_RETENTION_TIME_IN_DAYS => { + parser.expect_token(&Token::Eq)?; + builder = + builder.data_retention_time_in_days(Some(parser.parse_literal_uint()?)); + } + Keyword::MAX_DATA_EXTENSION_TIME_IN_DAYS => { + parser.expect_token(&Token::Eq)?; + builder = + builder.max_data_extension_time_in_days(Some(parser.parse_literal_uint()?)); + } + Keyword::EXTERNAL_VOLUME => { + parser.expect_token(&Token::Eq)?; + builder = builder.external_volume(Some(parser.parse_literal_string()?)); + } + Keyword::CATALOG => { + parser.expect_token(&Token::Eq)?; + builder = builder.catalog(Some(parser.parse_literal_string()?)); + } + Keyword::REPLACE_INVALID_CHARACTERS => { + parser.expect_token(&Token::Eq)?; + builder = + builder.replace_invalid_characters(Some(parser.parse_boolean_string()?)); + } + Keyword::DEFAULT_DDL_COLLATION => { + parser.expect_token(&Token::Eq)?; + builder = builder.default_ddl_collation(Some(parser.parse_literal_string()?)); + } + Keyword::STORAGE_SERIALIZATION_POLICY => { + parser.expect_token(&Token::Eq)?; + let policy = parse_storage_serialization_policy(parser)?; + builder = builder.storage_serialization_policy(Some(policy)); + } + Keyword::COMMENT => { + parser.expect_token(&Token::Eq)?; + builder = builder.comment(Some(parser.parse_literal_string()?)); + } + Keyword::CATALOG_SYNC => { + parser.expect_token(&Token::Eq)?; + builder = builder.catalog_sync(Some(parser.parse_literal_string()?)); + } + Keyword::CATALOG_SYNC_NAMESPACE_FLATTEN_DELIMITER => { + parser.expect_token(&Token::Eq)?; + builder = builder.catalog_sync_namespace_flatten_delimiter(Some( + parser.parse_literal_string()?, + )); + } + Keyword::CATALOG_SYNC_NAMESPACE_MODE => { + parser.expect_token(&Token::Eq)?; + let mode = + match parser.parse_one_of_keywords(&[Keyword::NEST, Keyword::FLATTEN]) { + Some(Keyword::NEST) => CatalogSyncNamespaceMode::Nest, + Some(Keyword::FLATTEN) => CatalogSyncNamespaceMode::Flatten, + _ => { + return parser.expected("NEST or FLATTEN", next_token); + } + }; + builder = builder.catalog_sync_namespace_mode(Some(mode)); + } + Keyword::WITH => { + if parser.parse_keyword(Keyword::TAG) { + parser.expect_token(&Token::LParen)?; + let tags = parser.parse_comma_separated(Parser::parse_tag)?; + parser.expect_token(&Token::RParen)?; + builder = builder.with_tags(Some(tags)); + } else if parser.parse_keyword(Keyword::CONTACT) { + parser.expect_token(&Token::LParen)?; + let contacts = parser.parse_comma_separated(|p| { + let purpose = p.parse_identifier()?.value; + p.expect_token(&Token::Eq)?; + let contact = p.parse_identifier()?.value; + Ok((purpose, contact)) + })?; + parser.expect_token(&Token::RParen)?; + builder = builder.with_contacts(Some(contacts)); + } else { + return parser.expected("TAG or CONTACT", next_token); + } + } + _ => return parser.expected("end of statementrrr", next_token), + }, + Token::SemiColon | Token::EOF => break, + _ => return parser.expected("end of statement", next_token), + } + } + Ok(builder.build()) +} + pub fn parse_storage_serialization_policy( parser: &mut Parser, ) -> Result { diff --git a/src/keywords.rs b/src/keywords.rs index 9e689a6df..98a75625f 100644 --- a/src/keywords.rs +++ b/src/keywords.rs @@ -166,6 +166,8 @@ define_keywords!( CAST, CATALOG, CATALOG_SYNC, + CATALOG_SYNC_NAMESPACE_FLATTEN_DELIMITER, + CATALOG_SYNC_NAMESPACE_MODE, CATCH, CEIL, CEILING, @@ -213,6 +215,7 @@ define_keywords!( CONNECTOR, CONNECT_BY_ROOT, CONSTRAINT, + CONTACT, CONTAINS, CONTINUE, CONVERT, @@ -366,6 +369,7 @@ define_keywords!( FIRST, FIRST_VALUE, FIXEDSTRING, + FLATTEN, FLOAT, FLOAT32, FLOAT4, @@ -584,6 +588,7 @@ define_keywords!( NATURAL, NCHAR, NCLOB, + NEST, NESTED, NETWORK, NEW, @@ -755,6 +760,7 @@ define_keywords!( REPAIR, REPEATABLE, REPLACE, + REPLACE_INVALID_CHARACTERS, REPLICA, REPLICATE, REPLICATION, diff --git a/src/parser/mod.rs b/src/parser/mod.rs index 47b63da87..8b13f908a 100644 --- a/src/parser/mod.rs +++ b/src/parser/mod.rs @@ -9574,6 +9574,15 @@ impl<'a> Parser<'a> { } } + /// Parse a boolean string + pub fn parse_boolean_string(&mut self) -> Result { + match self.parse_one_of_keywords(&[Keyword::TRUE, Keyword::FALSE]) { + Some(Keyword::TRUE) => Ok(true), + Some(Keyword::FALSE) => Ok(false), + _ => self.expected("TRUE or FALSE", self.peek_token()), + } + } + /// Parse a literal unicode normalization clause pub fn parse_unicode_is_normalized(&mut self, expr: Expr) -> Result { let neg = self.parse_keyword(Keyword::NOT); diff --git a/tests/sqlparser_snowflake.rs b/tests/sqlparser_snowflake.rs index 65546bee0..7cad99793 100644 --- a/tests/sqlparser_snowflake.rs +++ b/tests/sqlparser_snowflake.rs @@ -4438,3 +4438,63 @@ fn test_snowflake_identifier_function() { true ); } + +#[test] +fn test_create_database_basic() { + snowflake().verified_stmt("CREATE DATABASE my_db"); + snowflake().verified_stmt("CREATE OR REPLACE DATABASE my_db"); + snowflake().verified_stmt("CREATE TRANSIENT DATABASE IF NOT EXISTS my_db"); +} + +#[test] +fn test_create_database_clone() { + snowflake().verified_stmt("CREATE DATABASE my_db CLONE src_db"); + snowflake().verified_stmt( + "CREATE OR REPLACE DATABASE my_db CLONE src_db DATA_RETENTION_TIME_IN_DAYS = 1", + ); +} + +#[test] +fn test_create_database_with_all_options() { + snowflake().one_statement_parses_to( + r#" + CREATE OR REPLACE TRANSIENT DATABASE IF NOT EXISTS my_db + CLONE src_db + DATA_RETENTION_TIME_IN_DAYS = 1 + MAX_DATA_EXTENSION_TIME_IN_DAYS = 5 + EXTERNAL_VOLUME = 'volume1' + CATALOG = 'my_catalog' + REPLACE_INVALID_CHARACTERS = TRUE + DEFAULT_DDL_COLLATION = 'en-ci' + STORAGE_SERIALIZATION_POLICY = COMPATIBLE + COMMENT = 'This is my database' + CATALOG_SYNC = 'sync_integration' + CATALOG_SYNC_NAMESPACE_FLATTEN_DELIMITER = '/' + WITH TAG (env = 'prod', team = 'data') + WITH CONTACT (owner = 'admin', dpo = 'compliance') + "#, + "CREATE OR REPLACE TRANSIENT DATABASE IF NOT EXISTS \ + my_db CLONE src_db DATA_RETENTION_TIME_IN_DAYS = 1 MAX_DATA_EXTENSION_TIME_IN_DAYS = 5 \ + EXTERNAL_VOLUME = 'volume1' CATALOG = 'my_catalog' \ + REPLACE_INVALID_CHARACTERS = TRUE DEFAULT_DDL_COLLATION = 'en-ci' \ + STORAGE_SERIALIZATION_POLICY = COMPATIBLE COMMENT = 'This is my database' \ + CATALOG_SYNC = 'sync_integration' CATALOG_SYNC_NAMESPACE_FLATTEN_DELIMITER = '/' \ + WITH TAG (env='prod', team='data') \ + WITH CONTACT (owner = admin, dpo = compliance)", + ); +} + +#[test] +fn test_create_database_errors() { + let err = snowflake() + .parse_sql_statements("CREATE DATABASE") + .unwrap_err() + .to_string(); + assert!(err.contains("Expected"), "Unexpected error: {err}"); + + let err = snowflake() + .parse_sql_statements("CREATE DATABASE my_db CLONE") + .unwrap_err() + .to_string(); + assert!(err.contains("Expected"), "Unexpected error: {err}"); +} From 992a7e94eb4c2a44819ec97acc942541c4967832 Mon Sep 17 00:00:00 2001 From: osipovartem Date: Fri, 11 Jul 2025 19:55:08 +0300 Subject: [PATCH 2/7] Fix clippy --- src/ast/ddl.rs | 15 +++------------ src/ast/helpers/stmt_create_database.rs | 8 +++----- src/ast/mod.rs | 23 +++++++++++++++++++++++ src/dialect/snowflake.rs | 4 ++-- tests/sqlparser_snowflake.rs | 4 ++-- 5 files changed, 33 insertions(+), 21 deletions(-) diff --git a/src/ast/ddl.rs b/src/ast/ddl.rs index 25fbf1a5d..d3a1e7f12 100644 --- a/src/ast/ddl.rs +++ b/src/ast/ddl.rs @@ -31,7 +31,7 @@ use sqlparser_derive::{Visit, VisitMut}; use crate::ast::value::escape_single_quote_string; use crate::ast::{ display_comma_separated, display_separated, ArgMode, CatalogSyncNamespaceMode, CommentDef, - CreateFunctionBody, CreateFunctionUsing, DataType, Expr, FunctionBehavior, + ContactEntry, CreateFunctionBody, CreateFunctionUsing, DataType, Expr, FunctionBehavior, FunctionCalledOnNull, FunctionDeterminismSpecifier, FunctionParallel, Ident, IndexColumn, MySQLColumnPosition, ObjectName, OperateFunctionArg, OrderByExpr, ProjectionSelect, SequenceOptions, SqlOption, StorageSerializationPolicy, Tag, Value, ValueWithSpan, @@ -2546,7 +2546,7 @@ pub struct CreateSnowflakeDatabase { pub catalog_sync_namespace_mode: Option, pub catalog_sync_namespace_flatten_delimiter: Option, pub with_tags: Option>, - pub with_contacts: Option>, + pub with_contacts: Option>, } impl fmt::Display for CreateSnowflakeDatabase { @@ -2619,16 +2619,7 @@ impl fmt::Display for CreateSnowflakeDatabase { } if let Some(contacts) = &self.with_contacts { - write!( - f, - " WITH CONTACT ({})", - display_comma_separated( - &contacts - .iter() - .map(|(purpose, contact)| format!("{purpose} = {contact}")) - .collect::>() - ) - )?; + write!(f, " WITH CONTACT ({})", display_comma_separated(contacts))?; } Ok(()) diff --git a/src/ast/helpers/stmt_create_database.rs b/src/ast/helpers/stmt_create_database.rs index 6f3bd1621..c7f5f78f3 100644 --- a/src/ast/helpers/stmt_create_database.rs +++ b/src/ast/helpers/stmt_create_database.rs @@ -26,7 +26,7 @@ use sqlparser_derive::{Visit, VisitMut}; use crate::ast::ddl::CreateSnowflakeDatabase; use crate::ast::{ - CatalogSyncNamespaceMode, ObjectName, Statement, StorageSerializationPolicy, Tag, + CatalogSyncNamespaceMode, ContactEntry, ObjectName, Statement, StorageSerializationPolicy, Tag, }; use crate::parser::ParserError; @@ -51,7 +51,6 @@ use crate::parser::ParserError; /// ) /// ``` /// -/// [1]: crate::ast::Statement::CreateSnowflakeDatabase #[derive(Debug, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "visitor", derive(Visit, VisitMut))] @@ -73,7 +72,7 @@ pub struct CreateDatabaseBuilder { pub catalog_sync_namespace_mode: Option, pub catalog_sync_namespace_flatten_delimiter: Option, pub with_tags: Option>, - pub with_contacts: Option>, + pub with_contacts: Option>, } impl CreateDatabaseBuilder { @@ -192,7 +191,7 @@ impl CreateDatabaseBuilder { self } - pub fn with_contacts(mut self, with_contacts: Option>) -> Self { + pub fn with_contacts(mut self, with_contacts: Option>) -> Self { self.with_contacts = with_contacts; self } @@ -275,7 +274,6 @@ impl TryFrom for CreateDatabaseBuilder { #[cfg(test)] mod tests { use crate::ast::helpers::stmt_create_database::CreateDatabaseBuilder; - use crate::ast::helpers::stmt_create_table::CreateTableBuilder; use crate::ast::{Ident, ObjectName, Statement}; use crate::parser::ParserError; diff --git a/src/ast/mod.rs b/src/ast/mod.rs index 5c13f9ace..d5e0bd657 100644 --- a/src/ast/mod.rs +++ b/src/ast/mod.rs @@ -9550,6 +9550,29 @@ impl Display for Tag { } } +/// Snowflake `WITH CONTACT ( purpose = contact [ , purpose = contact ...] )` +/// +/// +#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))] +pub struct ContactEntry { + pub purpose: String, + pub contact: String, +} + +impl ContactEntry { + pub fn new(purpose: String, contact: String) -> Self { + Self { purpose, contact } + } +} + +impl Display for ContactEntry { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{} = {}", self.purpose, self.contact) + } +} + /// Helper to indicate if a comment includes the `=` in the display form #[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] diff --git a/src/dialect/snowflake.rs b/src/dialect/snowflake.rs index 1575e1f20..daa455549 100644 --- a/src/dialect/snowflake.rs +++ b/src/dialect/snowflake.rs @@ -24,7 +24,7 @@ use crate::ast::helpers::stmt_data_loading::{ FileStagingCommand, StageLoadSelectItem, StageLoadSelectItemKind, StageParamsObject, }; use crate::ast::{ - CatalogSyncNamespaceMode, ColumnOption, ColumnPolicy, ColumnPolicyProperty, + CatalogSyncNamespaceMode, ColumnOption, ColumnPolicy, ColumnPolicyProperty, ContactEntry, CopyIntoSnowflakeKind, Ident, IdentityParameters, IdentityProperty, IdentityPropertyFormatKind, IdentityPropertyKind, IdentityPropertyOrder, ObjectName, ObjectNamePart, RowAccessPolicy, ShowObjects, SqlOption, Statement, StorageSerializationPolicy, TagsColumnOption, @@ -826,7 +826,7 @@ pub fn parse_create_database( let purpose = p.parse_identifier()?.value; p.expect_token(&Token::Eq)?; let contact = p.parse_identifier()?.value; - Ok((purpose, contact)) + Ok(ContactEntry::new(purpose, contact)) })?; parser.expect_token(&Token::RParen)?; builder = builder.with_contacts(Some(contacts)); diff --git a/tests/sqlparser_snowflake.rs b/tests/sqlparser_snowflake.rs index 7cad99793..dc06d01b0 100644 --- a/tests/sqlparser_snowflake.rs +++ b/tests/sqlparser_snowflake.rs @@ -4374,9 +4374,9 @@ fn test_snowflake_identifier_function() { // Using IDENTIFIER to reference a database match snowflake().verified_stmt("CREATE DATABASE IDENTIFIER('tbl')") { - Statement::CreateDatabase { db_name, .. } => { + Statement::CreateSnowflakeDatabase(CreateSnowflakeDatabase { name, .. }) => { assert_eq!( - db_name, + name, ObjectName(vec![ObjectNamePart::Function(ObjectNamePartFunction { name: Ident::new("IDENTIFIER"), args: vec![FunctionArg::Unnamed(FunctionArgExpr::Expr(Expr::Value( From b9ff319fd1322b635dad3e306c05b38817a0c4ff Mon Sep 17 00:00:00 2001 From: osipovartem Date: Fri, 11 Jul 2025 20:11:22 +0300 Subject: [PATCH 3/7] Fix tests --- tests/sqlparser_common.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs index 15144479c..c805d7379 100644 --- a/tests/sqlparser_common.rs +++ b/tests/sqlparser_common.rs @@ -7898,7 +7898,7 @@ fn parse_exists_subquery() { #[test] fn parse_create_database() { let sql = "CREATE DATABASE mydb"; - match verified_stmt(sql) { + match all_dialects_except(|d| d.is::()).verified_stmt(sql) { Statement::CreateDatabase { db_name, if_not_exists, @@ -7917,7 +7917,7 @@ fn parse_create_database() { #[test] fn parse_create_database_ine() { let sql = "CREATE DATABASE IF NOT EXISTS mydb"; - match verified_stmt(sql) { + match all_dialects_except(|d| d.is::()).verified_stmt(sql) { Statement::CreateDatabase { db_name, if_not_exists, From 4538847c354f2f6c88624ea1adce8d12435fa319 Mon Sep 17 00:00:00 2001 From: osipovartem Date: Fri, 11 Jul 2025 20:14:39 +0300 Subject: [PATCH 4/7] Fix doc --- src/ast/helpers/stmt_create_database.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/ast/helpers/stmt_create_database.rs b/src/ast/helpers/stmt_create_database.rs index c7f5f78f3..49effc770 100644 --- a/src/ast/helpers/stmt_create_database.rs +++ b/src/ast/helpers/stmt_create_database.rs @@ -51,6 +51,7 @@ use crate::parser::ParserError; /// ) /// ``` /// +/// [1]: Statement::CreateTable #[derive(Debug, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "visitor", derive(Visit, VisitMut))] From 7654a49b50aa0d05475901fc145bdf1f8c14dfff Mon Sep 17 00:00:00 2001 From: osipovartem Date: Fri, 11 Jul 2025 20:16:04 +0300 Subject: [PATCH 5/7] Fix doc --- src/ast/helpers/stmt_create_database.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ast/helpers/stmt_create_database.rs b/src/ast/helpers/stmt_create_database.rs index 49effc770..1840441cd 100644 --- a/src/ast/helpers/stmt_create_database.rs +++ b/src/ast/helpers/stmt_create_database.rs @@ -51,7 +51,7 @@ use crate::parser::ParserError; /// ) /// ``` /// -/// [1]: Statement::CreateTable +/// [1]: Statement::CreateSnowflakeDatabase #[derive(Debug, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "visitor", derive(Visit, VisitMut))] From 1d977d19476f496208290d67b9ab052f639c7668 Mon Sep 17 00:00:00 2001 From: osipovartem Date: Tue, 15 Jul 2025 13:57:28 +0300 Subject: [PATCH 6/7] Fix comments --- src/ast/ddl.rs | 111 +----------------- src/ast/helpers/stmt_create_database.rs | 51 ++++++--- src/ast/mod.rs | 144 ++++++++++++++++++------ src/ast/spans.rs | 43 +++---- src/parser/mod.rs | 16 +++ tests/sqlparser_common.rs | 6 +- tests/sqlparser_snowflake.rs | 21 +--- 7 files changed, 191 insertions(+), 201 deletions(-) diff --git a/src/ast/ddl.rs b/src/ast/ddl.rs index d3a1e7f12..51e057840 100644 --- a/src/ast/ddl.rs +++ b/src/ast/ddl.rs @@ -30,11 +30,11 @@ use sqlparser_derive::{Visit, VisitMut}; use crate::ast::value::escape_single_quote_string; use crate::ast::{ - display_comma_separated, display_separated, ArgMode, CatalogSyncNamespaceMode, CommentDef, - ContactEntry, CreateFunctionBody, CreateFunctionUsing, DataType, Expr, FunctionBehavior, - FunctionCalledOnNull, FunctionDeterminismSpecifier, FunctionParallel, Ident, IndexColumn, - MySQLColumnPosition, ObjectName, OperateFunctionArg, OrderByExpr, ProjectionSelect, - SequenceOptions, SqlOption, StorageSerializationPolicy, Tag, Value, ValueWithSpan, + display_comma_separated, display_separated, ArgMode, CommentDef, CreateFunctionBody, + CreateFunctionUsing, DataType, Expr, FunctionBehavior, FunctionCalledOnNull, + FunctionDeterminismSpecifier, FunctionParallel, Ident, IndexColumn, MySQLColumnPosition, + ObjectName, OperateFunctionArg, OrderByExpr, ProjectionSelect, SequenceOptions, SqlOption, Tag, + Value, ValueWithSpan, }; use crate::keywords::Keyword; use crate::tokenizer::Token; @@ -2524,104 +2524,3 @@ impl fmt::Display for CreateConnector { Ok(()) } } - -#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)] -#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))] -pub struct CreateSnowflakeDatabase { - pub or_replace: bool, - pub transient: bool, - pub if_not_exists: bool, - pub name: ObjectName, - pub clone: Option, - pub data_retention_time_in_days: Option, - pub max_data_extension_time_in_days: Option, - pub external_volume: Option, - pub catalog: Option, - pub replace_invalid_characters: Option, - pub default_ddl_collation: Option, - pub storage_serialization_policy: Option, - pub comment: Option, - pub catalog_sync: Option, - pub catalog_sync_namespace_mode: Option, - pub catalog_sync_namespace_flatten_delimiter: Option, - pub with_tags: Option>, - pub with_contacts: Option>, -} - -impl fmt::Display for CreateSnowflakeDatabase { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!( - f, - "CREATE {or_replace}{transient}DATABASE {if_not_exists}{name}", - or_replace = if self.or_replace { "OR REPLACE " } else { "" }, - transient = if self.transient { "TRANSIENT " } else { "" }, - if_not_exists = if self.if_not_exists { - "IF NOT EXISTS " - } else { - "" - }, - name = self.name, - )?; - - if let Some(clone) = &self.clone { - write!(f, " CLONE {clone}")?; - } - - if let Some(value) = self.data_retention_time_in_days { - write!(f, " DATA_RETENTION_TIME_IN_DAYS = {value}")?; - } - - if let Some(value) = self.max_data_extension_time_in_days { - write!(f, " MAX_DATA_EXTENSION_TIME_IN_DAYS = {value}")?; - } - - if let Some(vol) = &self.external_volume { - write!(f, " EXTERNAL_VOLUME = '{vol}'")?; - } - - if let Some(cat) = &self.catalog { - write!(f, " CATALOG = '{cat}'")?; - } - - if let Some(true) = self.replace_invalid_characters { - write!(f, " REPLACE_INVALID_CHARACTERS = TRUE")?; - } else if let Some(false) = self.replace_invalid_characters { - write!(f, " REPLACE_INVALID_CHARACTERS = FALSE")?; - } - - if let Some(collation) = &self.default_ddl_collation { - write!(f, " DEFAULT_DDL_COLLATION = '{collation}'")?; - } - - if let Some(policy) = &self.storage_serialization_policy { - write!(f, " STORAGE_SERIALIZATION_POLICY = {policy}")?; - } - - if let Some(comment) = &self.comment { - write!(f, " COMMENT = '{comment}'")?; - } - - if let Some(sync) = &self.catalog_sync { - write!(f, " CATALOG_SYNC = '{sync}'")?; - } - - if let Some(mode) = &self.catalog_sync_namespace_mode { - write!(f, " CATALOG_SYNC_NAMESPACE_MODE = {mode}")?; - } - - if let Some(delim) = &self.catalog_sync_namespace_flatten_delimiter { - write!(f, " CATALOG_SYNC_NAMESPACE_FLATTEN_DELIMITER = '{delim}'")?; - } - - if let Some(tags) = &self.with_tags { - write!(f, " WITH TAG ({})", display_comma_separated(tags))?; - } - - if let Some(contacts) = &self.with_contacts { - write!(f, " WITH CONTACT ({})", display_comma_separated(contacts))?; - } - - Ok(()) - } -} diff --git a/src/ast/helpers/stmt_create_database.rs b/src/ast/helpers/stmt_create_database.rs index 1840441cd..94997bfa5 100644 --- a/src/ast/helpers/stmt_create_database.rs +++ b/src/ast/helpers/stmt_create_database.rs @@ -24,7 +24,6 @@ use serde::{Deserialize, Serialize}; #[cfg(feature = "visitor")] use sqlparser_derive::{Visit, VisitMut}; -use crate::ast::ddl::CreateSnowflakeDatabase; use crate::ast::{ CatalogSyncNamespaceMode, ContactEntry, ObjectName, Statement, StorageSerializationPolicy, Tag, }; @@ -51,15 +50,17 @@ use crate::parser::ParserError; /// ) /// ``` /// -/// [1]: Statement::CreateSnowflakeDatabase +/// [1]: Statement::CreateDatabase #[derive(Debug, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "visitor", derive(Visit, VisitMut))] pub struct CreateDatabaseBuilder { + pub db_name: ObjectName, + pub if_not_exists: bool, + pub location: Option, + pub managed_location: Option, pub or_replace: bool, pub transient: bool, - pub if_not_exists: bool, - pub name: ObjectName, pub clone: Option, pub data_retention_time_in_days: Option, pub max_data_extension_time_in_days: Option, @@ -79,10 +80,12 @@ pub struct CreateDatabaseBuilder { impl CreateDatabaseBuilder { pub fn new(name: ObjectName) -> Self { Self { + db_name: name, + if_not_exists: false, + location: None, + managed_location: None, or_replace: false, transient: false, - if_not_exists: false, - name, clone: None, data_retention_time_in_days: None, max_data_extension_time_in_days: None, @@ -100,6 +103,16 @@ impl CreateDatabaseBuilder { } } + pub fn location(mut self, location: Option) -> Self { + self.location = location; + self + } + + pub fn managed_location(mut self, managed_location: Option) -> Self { + self.managed_location = managed_location; + self + } + pub fn or_replace(mut self, or_replace: bool) -> Self { self.or_replace = or_replace; self @@ -198,11 +211,13 @@ impl CreateDatabaseBuilder { } pub fn build(self) -> Statement { - Statement::CreateSnowflakeDatabase(CreateSnowflakeDatabase { + Statement::CreateDatabase { + db_name: self.db_name, + if_not_exists: self.if_not_exists, + managed_location: self.managed_location, + location: self.location, or_replace: self.or_replace, transient: self.transient, - if_not_exists: self.if_not_exists, - name: self.name, clone: self.clone, data_retention_time_in_days: self.data_retention_time_in_days, max_data_extension_time_in_days: self.max_data_extension_time_in_days, @@ -217,7 +232,7 @@ impl CreateDatabaseBuilder { catalog_sync_namespace_flatten_delimiter: self.catalog_sync_namespace_flatten_delimiter, with_tags: self.with_tags, with_contacts: self.with_contacts, - }) + } } } @@ -226,11 +241,13 @@ impl TryFrom for CreateDatabaseBuilder { fn try_from(stmt: Statement) -> Result { match stmt { - Statement::CreateSnowflakeDatabase(CreateSnowflakeDatabase { + Statement::CreateDatabase { + db_name, + if_not_exists, + location, + managed_location, or_replace, transient, - if_not_exists, - name, clone, data_retention_time_in_days, max_data_extension_time_in_days, @@ -245,11 +262,13 @@ impl TryFrom for CreateDatabaseBuilder { catalog_sync_namespace_flatten_delimiter, with_tags, with_contacts, - }) => Ok(Self { + } => Ok(Self { + db_name, + if_not_exists, + location, + managed_location, or_replace, transient, - if_not_exists, - name, clone, data_retention_time_in_days, max_data_extension_time_in_days, diff --git a/src/ast/mod.rs b/src/ast/mod.rs index d5e0bd657..7f9102705 100644 --- a/src/ast/mod.rs +++ b/src/ast/mod.rs @@ -63,12 +63,12 @@ pub use self::ddl::{ AlterTypeAddValuePosition, AlterTypeOperation, AlterTypeRename, AlterTypeRenameValue, ClusteredBy, ColumnDef, ColumnOption, ColumnOptionDef, ColumnOptions, ColumnPolicy, ColumnPolicyProperty, ConstraintCharacteristics, CreateConnector, CreateDomain, CreateFunction, - CreateSnowflakeDatabase, Deduplicate, DeferrableInitial, DropBehavior, GeneratedAs, - GeneratedExpressionMode, IdentityParameters, IdentityProperty, IdentityPropertyFormatKind, - IdentityPropertyKind, IdentityPropertyOrder, IndexOption, IndexType, KeyOrIndexDisplay, - NullsDistinctOption, Owner, Partition, ProcedureParam, ReferentialAction, ReplicaIdentity, - TableConstraint, TagsColumnOption, UserDefinedTypeCompositeAttributeDef, - UserDefinedTypeRepresentation, ViewColumnDef, + Deduplicate, DeferrableInitial, DropBehavior, GeneratedAs, GeneratedExpressionMode, + IdentityParameters, IdentityProperty, IdentityPropertyFormatKind, IdentityPropertyKind, + IdentityPropertyOrder, IndexOption, IndexType, KeyOrIndexDisplay, NullsDistinctOption, Owner, + Partition, ProcedureParam, ReferentialAction, ReplicaIdentity, TableConstraint, + TagsColumnOption, UserDefinedTypeCompositeAttributeDef, UserDefinedTypeRepresentation, + ViewColumnDef, }; pub use self::dml::{CreateIndex, CreateTable, Delete, IndexColumn, Insert}; pub use self::operator::{BinaryOperator, UnaryOperator}; @@ -3850,38 +3850,31 @@ pub enum Statement { /// ```sql /// CREATE DATABASE /// ``` + /// See: + /// CreateDatabase { db_name: ObjectName, if_not_exists: bool, location: Option, managed_location: Option, + or_replace: bool, + transient: bool, + clone: Option, + data_retention_time_in_days: Option, + max_data_extension_time_in_days: Option, + external_volume: Option, + catalog: Option, + replace_invalid_characters: Option, + default_ddl_collation: Option, + storage_serialization_policy: Option, + comment: Option, + catalog_sync: Option, + catalog_sync_namespace_mode: Option, + catalog_sync_namespace_flatten_delimiter: Option, + with_tags: Option>, + with_contacts: Option>, }, /// ```sql - /// CREATE [ OR REPLACE ] [ TRANSIENT ] DATABASE [ IF NOT EXISTS ] - /// [ CLONE - /// [ { AT | BEFORE } ( { TIMESTAMP => | OFFSET => | STATEMENT => } ) ] - /// [ IGNORE TABLES WITH INSUFFICIENT DATA RETENTION ] - /// [ IGNORE HYBRID TABLES ] ] - /// [ DATA_RETENTION_TIME_IN_DAYS = ] - /// [ MAX_DATA_EXTENSION_TIME_IN_DAYS = ] - /// [ EXTERNAL_VOLUME = ] - /// [ CATALOG = ] - /// [ REPLACE_INVALID_CHARACTERS = { TRUE | FALSE } ] - /// [ DEFAULT_DDL_COLLATION = '' ] - /// [ STORAGE_SERIALIZATION_POLICY = { COMPATIBLE | OPTIMIZED } ] - /// [ COMMENT = '' ] - /// [ CATALOG_SYNC = '' ] - /// [ CATALOG_SYNC_NAMESPACE_MODE = { NEST | FLATTEN } ] - /// [ CATALOG_SYNC_NAMESPACE_FLATTEN_DELIMITER = '' ] - /// [ [ WITH ] TAG ( = '' [ , = '' , ... ] ) ] - /// [ WITH CONTACT ( = [ , = ... ] ) ] - /// ``` - /// See: - /// - /// - /// Creates a new database in the system. - CreateSnowflakeDatabase(CreateSnowflakeDatabase), - /// ```sql /// CREATE FUNCTION /// ``` /// @@ -4816,21 +4809,98 @@ impl fmt::Display for Statement { if_not_exists, location, managed_location, + or_replace, + transient, + clone, + data_retention_time_in_days, + max_data_extension_time_in_days, + external_volume, + catalog, + replace_invalid_characters, + default_ddl_collation, + storage_serialization_policy, + comment, + catalog_sync, + catalog_sync_namespace_mode, + catalog_sync_namespace_flatten_delimiter, + with_tags, + with_contacts, } => { - write!(f, "CREATE DATABASE")?; - if *if_not_exists { - write!(f, " IF NOT EXISTS")?; - } - write!(f, " {db_name}")?; + write!( + f, + "CREATE {or_replace}{transient}DATABASE {if_not_exists}{name}", + or_replace = if *or_replace { "OR REPLACE " } else { "" }, + transient = if *transient { "TRANSIENT " } else { "" }, + if_not_exists = if *if_not_exists { "IF NOT EXISTS " } else { "" }, + name = db_name, + )?; + if let Some(l) = location { write!(f, " LOCATION '{l}'")?; } if let Some(ml) = managed_location { write!(f, " MANAGEDLOCATION '{ml}'")?; } + if let Some(clone) = clone { + write!(f, " CLONE {clone}")?; + } + + if let Some(value) = data_retention_time_in_days { + write!(f, " DATA_RETENTION_TIME_IN_DAYS = {value}")?; + } + + if let Some(value) = max_data_extension_time_in_days { + write!(f, " MAX_DATA_EXTENSION_TIME_IN_DAYS = {value}")?; + } + + if let Some(vol) = external_volume { + write!(f, " EXTERNAL_VOLUME = '{vol}'")?; + } + + if let Some(cat) = catalog { + write!(f, " CATALOG = '{cat}'")?; + } + + if let Some(true) = replace_invalid_characters { + write!(f, " REPLACE_INVALID_CHARACTERS = TRUE")?; + } else if let Some(false) = replace_invalid_characters { + write!(f, " REPLACE_INVALID_CHARACTERS = FALSE")?; + } + + if let Some(collation) = default_ddl_collation { + write!(f, " DEFAULT_DDL_COLLATION = '{collation}'")?; + } + + if let Some(policy) = storage_serialization_policy { + write!(f, " STORAGE_SERIALIZATION_POLICY = {policy}")?; + } + + if let Some(comment) = comment { + write!(f, " COMMENT = '{comment}'")?; + } + + if let Some(sync) = catalog_sync { + write!(f, " CATALOG_SYNC = '{sync}'")?; + } + + if let Some(mode) = catalog_sync_namespace_mode { + write!(f, " CATALOG_SYNC_NAMESPACE_MODE = {mode}")?; + } + + if let Some(delim) = catalog_sync_namespace_flatten_delimiter { + write!(f, " CATALOG_SYNC_NAMESPACE_FLATTEN_DELIMITER = '{delim}'")?; + } + + if let Some(tags) = with_tags { + write!(f, " WITH TAG ({})", display_comma_separated(tags))?; + } + + if let Some(contacts) = with_contacts { + write!(f, " WITH CONTACT ({})", display_comma_separated(contacts))?; + } + Ok(()) } - Statement::CreateSnowflakeDatabase(create_database) => create_database.fmt(f), Statement::CreateFunction(create_function) => create_function.fmt(f), Statement::CreateDomain(create_domain) => create_domain.fmt(f), Statement::CreateTrigger { diff --git a/src/ast/spans.rs b/src/ast/spans.rs index c4ad79c82..3e82905e1 100644 --- a/src/ast/spans.rs +++ b/src/ast/spans.rs @@ -21,24 +21,24 @@ use core::iter; use crate::tokenizer::Span; use super::{ - dcl::SecondaryRoles, ddl::CreateSnowflakeDatabase, value::ValueWithSpan, AccessExpr, - AlterColumnOperation, AlterIndexOperation, AlterTableOperation, Array, Assignment, - AssignmentTarget, AttachedToken, BeginEndStatements, CaseStatement, CloseCursor, - ClusteredIndex, ColumnDef, ColumnOption, ColumnOptionDef, ConditionalStatementBlock, - ConditionalStatements, ConflictTarget, ConnectBy, ConstraintCharacteristics, CopySource, - CreateIndex, CreateTable, CreateTableOptions, Cte, Delete, DoUpdate, ExceptSelectItem, - ExcludeSelectItem, Expr, ExprWithAlias, Fetch, FromTable, Function, FunctionArg, - FunctionArgExpr, FunctionArgumentClause, FunctionArgumentList, FunctionArguments, GroupByExpr, - HavingBound, IfStatement, IlikeSelectItem, IndexColumn, Insert, Interpolate, InterpolateExpr, - Join, JoinConstraint, JoinOperator, JsonPath, JsonPathElem, LateralView, LimitClause, - MatchRecognizePattern, Measure, NamedParenthesizedList, NamedWindowDefinition, ObjectName, - ObjectNamePart, Offset, OnConflict, OnConflictAction, OnInsert, OpenStatement, OrderBy, - OrderByExpr, OrderByKind, Partition, PivotValueSource, ProjectionSelect, Query, RaiseStatement, - RaiseStatementValue, ReferentialAction, RenameSelectItem, ReplaceSelectElement, - ReplaceSelectItem, Select, SelectInto, SelectItem, SetExpr, SqlOption, Statement, Subscript, - SymbolDefinition, TableAlias, TableAliasColumnDef, TableConstraint, TableFactor, TableObject, - TableOptionsClustered, TableWithJoins, UpdateTableFromKind, Use, Value, Values, ViewColumnDef, - WhileStatement, WildcardAdditionalOptions, With, WithFill, + dcl::SecondaryRoles, value::ValueWithSpan, AccessExpr, AlterColumnOperation, + AlterIndexOperation, AlterTableOperation, Array, Assignment, AssignmentTarget, AttachedToken, + BeginEndStatements, CaseStatement, CloseCursor, ClusteredIndex, ColumnDef, ColumnOption, + ColumnOptionDef, ConditionalStatementBlock, ConditionalStatements, ConflictTarget, ConnectBy, + ConstraintCharacteristics, CopySource, CreateIndex, CreateTable, CreateTableOptions, Cte, + Delete, DoUpdate, ExceptSelectItem, ExcludeSelectItem, Expr, ExprWithAlias, Fetch, FromTable, + Function, FunctionArg, FunctionArgExpr, FunctionArgumentClause, FunctionArgumentList, + FunctionArguments, GroupByExpr, HavingBound, IfStatement, IlikeSelectItem, IndexColumn, Insert, + Interpolate, InterpolateExpr, Join, JoinConstraint, JoinOperator, JsonPath, JsonPathElem, + LateralView, LimitClause, MatchRecognizePattern, Measure, NamedParenthesizedList, + NamedWindowDefinition, ObjectName, ObjectNamePart, Offset, OnConflict, OnConflictAction, + OnInsert, OpenStatement, OrderBy, OrderByExpr, OrderByKind, Partition, PivotValueSource, + ProjectionSelect, Query, RaiseStatement, RaiseStatementValue, ReferentialAction, + RenameSelectItem, ReplaceSelectElement, ReplaceSelectItem, Select, SelectInto, SelectItem, + SetExpr, SqlOption, Statement, Subscript, SymbolDefinition, TableAlias, TableAliasColumnDef, + TableConstraint, TableFactor, TableObject, TableOptionsClustered, TableWithJoins, + UpdateTableFromKind, Use, Value, Values, ViewColumnDef, WhileStatement, + WildcardAdditionalOptions, With, WithFill, }; /// Given an iterator of spans, return the [Span::union] of all spans. @@ -386,7 +386,6 @@ impl Spanned for Statement { .chain(returning.iter().flat_map(|i| i.iter().map(|k| k.span()))), ), Statement::Delete(delete) => delete.span(), - Statement::CreateSnowflakeDatabase(create_database) => create_database.span(), Statement::CreateView { or_alter: _, or_replace: _, @@ -617,12 +616,6 @@ impl Spanned for CreateTable { } } -impl Spanned for CreateSnowflakeDatabase { - fn span(&self) -> Span { - union_spans(core::iter::once(self.name.span()).chain(self.clone.iter().map(|c| c.span()))) - } -} - impl Spanned for ColumnDef { fn span(&self) -> Span { let ColumnDef { diff --git a/src/parser/mod.rs b/src/parser/mod.rs index 8b13f908a..afe9ec5a6 100644 --- a/src/parser/mod.rs +++ b/src/parser/mod.rs @@ -4937,6 +4937,22 @@ impl<'a> Parser<'a> { if_not_exists: ine, location, managed_location, + or_replace: false, + transient: false, + clone: None, + data_retention_time_in_days: None, + max_data_extension_time_in_days: None, + external_volume: None, + catalog: None, + replace_invalid_characters: None, + default_ddl_collation: None, + storage_serialization_policy: None, + comment: None, + catalog_sync: None, + catalog_sync_namespace_mode: None, + catalog_sync_namespace_flatten_delimiter: None, + with_tags: None, + with_contacts: None, }) } diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs index c805d7379..4b1dbf09b 100644 --- a/tests/sqlparser_common.rs +++ b/tests/sqlparser_common.rs @@ -7898,12 +7898,13 @@ fn parse_exists_subquery() { #[test] fn parse_create_database() { let sql = "CREATE DATABASE mydb"; - match all_dialects_except(|d| d.is::()).verified_stmt(sql) { + match verified_stmt(sql) { Statement::CreateDatabase { db_name, if_not_exists, location, managed_location, + .. } => { assert_eq!("mydb", db_name.to_string()); assert!(!if_not_exists); @@ -7917,12 +7918,13 @@ fn parse_create_database() { #[test] fn parse_create_database_ine() { let sql = "CREATE DATABASE IF NOT EXISTS mydb"; - match all_dialects_except(|d| d.is::()).verified_stmt(sql) { + match verified_stmt(sql) { Statement::CreateDatabase { db_name, if_not_exists, location, managed_location, + .. } => { assert_eq!("mydb", db_name.to_string()); assert!(if_not_exists); diff --git a/tests/sqlparser_snowflake.rs b/tests/sqlparser_snowflake.rs index dc06d01b0..5d931c474 100644 --- a/tests/sqlparser_snowflake.rs +++ b/tests/sqlparser_snowflake.rs @@ -4374,9 +4374,9 @@ fn test_snowflake_identifier_function() { // Using IDENTIFIER to reference a database match snowflake().verified_stmt("CREATE DATABASE IDENTIFIER('tbl')") { - Statement::CreateSnowflakeDatabase(CreateSnowflakeDatabase { name, .. }) => { + Statement::CreateDatabase { db_name, .. } => { assert_eq!( - name, + db_name, ObjectName(vec![ObjectNamePart::Function(ObjectNamePartFunction { name: Ident::new("IDENTIFIER"), args: vec![FunctionArg::Unnamed(FunctionArgExpr::Expr(Expr::Value( @@ -4440,22 +4440,14 @@ fn test_snowflake_identifier_function() { } #[test] -fn test_create_database_basic() { +fn test_create_database() { snowflake().verified_stmt("CREATE DATABASE my_db"); snowflake().verified_stmt("CREATE OR REPLACE DATABASE my_db"); snowflake().verified_stmt("CREATE TRANSIENT DATABASE IF NOT EXISTS my_db"); -} - -#[test] -fn test_create_database_clone() { snowflake().verified_stmt("CREATE DATABASE my_db CLONE src_db"); snowflake().verified_stmt( "CREATE OR REPLACE DATABASE my_db CLONE src_db DATA_RETENTION_TIME_IN_DAYS = 1", ); -} - -#[test] -fn test_create_database_with_all_options() { snowflake().one_statement_parses_to( r#" CREATE OR REPLACE TRANSIENT DATABASE IF NOT EXISTS my_db @@ -4469,6 +4461,7 @@ fn test_create_database_with_all_options() { STORAGE_SERIALIZATION_POLICY = COMPATIBLE COMMENT = 'This is my database' CATALOG_SYNC = 'sync_integration' + CATALOG_SYNC_NAMESPACE_MODE = NEST CATALOG_SYNC_NAMESPACE_FLATTEN_DELIMITER = '/' WITH TAG (env = 'prod', team = 'data') WITH CONTACT (owner = 'admin', dpo = 'compliance') @@ -4478,14 +4471,12 @@ fn test_create_database_with_all_options() { EXTERNAL_VOLUME = 'volume1' CATALOG = 'my_catalog' \ REPLACE_INVALID_CHARACTERS = TRUE DEFAULT_DDL_COLLATION = 'en-ci' \ STORAGE_SERIALIZATION_POLICY = COMPATIBLE COMMENT = 'This is my database' \ - CATALOG_SYNC = 'sync_integration' CATALOG_SYNC_NAMESPACE_FLATTEN_DELIMITER = '/' \ + CATALOG_SYNC = 'sync_integration' CATALOG_SYNC_NAMESPACE_MODE = NEST \ + CATALOG_SYNC_NAMESPACE_FLATTEN_DELIMITER = '/' \ WITH TAG (env='prod', team='data') \ WITH CONTACT (owner = admin, dpo = compliance)", ); -} -#[test] -fn test_create_database_errors() { let err = snowflake() .parse_sql_statements("CREATE DATABASE") .unwrap_err() From 8736660375a4395eec19a643ec3034fc13d5e33f Mon Sep 17 00:00:00 2001 From: osipovartem Date: Tue, 15 Jul 2025 14:25:44 +0300 Subject: [PATCH 7/7] Fix comments --- src/dialect/snowflake.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/dialect/snowflake.rs b/src/dialect/snowflake.rs index daa455549..1fc437b41 100644 --- a/src/dialect/snowflake.rs +++ b/src/dialect/snowflake.rs @@ -834,7 +834,7 @@ pub fn parse_create_database( return parser.expected("TAG or CONTACT", next_token); } } - _ => return parser.expected("end of statementrrr", next_token), + _ => return parser.expected("end of statement", next_token), }, Token::SemiColon | Token::EOF => break, _ => return parser.expected("end of statement", next_token),