Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for BigQuery table and view options #1061

Merged
merged 5 commits into from
Jan 23, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions src/ast/ddl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ use sqlparser_derive::{Visit, VisitMut};
use crate::ast::value::escape_single_quote_string;
use crate::ast::{
display_comma_separated, display_separated, DataType, Expr, Ident, ObjectName, SequenceOptions,
SqlOption,
};
use crate::tokenizer::Token;

Expand Down Expand Up @@ -527,6 +528,29 @@ impl fmt::Display for ColumnDef {
}
}

/// Column definition for a view.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you please add some examples to this doc comment showing what is allowed (and not)?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated the description

#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct ViewColumnDef {
pub name: Ident,
pub options: Option<Vec<SqlOption>>,
}

impl fmt::Display for ViewColumnDef {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.name)?;
if let Some(options) = self.options.as_ref() {
write!(
f,
" OPTIONS({})",
display_comma_separated(options.as_slice())
)?;
}
Ok(())
}
}

/// An optionally-named `ColumnOption`: `[ CONSTRAINT <name> ] <column-option>`.
///
/// Note that implementations are substantially more permissive than the ANSI
Expand Down Expand Up @@ -601,6 +625,14 @@ pub enum ColumnOption {
generation_expr: Option<Expr>,
generation_expr_mode: Option<GeneratedExpressionMode>,
},
/// BigQuery specific: Explicit column options in a view [1] or table [2]
/// Syntax
/// ```sql
/// OPTIONS(description="field desc")
/// ```
/// [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#view_column_option_list
/// [2]: https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#column_option_list
SqlOptions(Vec<SqlOption>),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Given the SQL is OPTIONs what would you think about keeping the AST similar?

Suggested change
SqlOptions(Vec<SqlOption>),
Options(Vec<SqlOption>),

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done!

}

impl fmt::Display for ColumnOption {
Expand Down Expand Up @@ -674,6 +706,9 @@ impl fmt::Display for ColumnOption {
Ok(())
}
}
SqlOptions(options) => {
write!(f, "OPTIONS({})", display_comma_separated(options))
}
}
}
}
Expand Down
14 changes: 12 additions & 2 deletions src/ast/helpers/stmt_create_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ use serde::{Deserialize, Serialize};
use sqlparser_derive::{Visit, VisitMut};

use crate::ast::{
ColumnDef, FileFormat, HiveDistributionStyle, HiveFormat, Ident, ObjectName, OnCommit, Query,
SqlOption, Statement, TableConstraint,
ColumnDef, CreateTableConfiguration, FileFormat, HiveDistributionStyle, HiveFormat, Ident,
ObjectName, OnCommit, Query, SqlOption, Statement, TableConstraint,
};
use crate::parser::ParserError;

Expand Down Expand Up @@ -72,6 +72,7 @@ pub struct CreateTableBuilder {
pub on_commit: Option<OnCommit>,
pub on_cluster: Option<String>,
pub order_by: Option<Vec<Ident>>,
pub table_config: Option<Box<CreateTableConfiguration>>,
pub strict: bool,
}

Expand Down Expand Up @@ -105,6 +106,7 @@ impl CreateTableBuilder {
on_commit: None,
on_cluster: None,
order_by: None,
table_config: None,
strict: false,
}
}
Expand Down Expand Up @@ -236,6 +238,11 @@ impl CreateTableBuilder {
self
}

pub fn table_config(mut self, table_config: Option<Box<CreateTableConfiguration>>) -> Self {
self.table_config = table_config;
self
}

pub fn strict(mut self, strict: bool) -> Self {
self.strict = strict;
self
Expand Down Expand Up @@ -270,6 +277,7 @@ impl CreateTableBuilder {
on_commit: self.on_commit,
on_cluster: self.on_cluster,
order_by: self.order_by,
table_config: self.table_config,
strict: self.strict,
}
}
Expand Down Expand Up @@ -310,6 +318,7 @@ impl TryFrom<Statement> for CreateTableBuilder {
on_commit,
on_cluster,
order_by,
table_config: config,
strict,
} => Ok(Self {
or_replace,
Expand Down Expand Up @@ -339,6 +348,7 @@ impl TryFrom<Statement> for CreateTableBuilder {
on_commit,
on_cluster,
order_by,
table_config: config,
strict,
}),
_ => Err(ParserError::ParserError(format!(
Expand Down
100 changes: 93 additions & 7 deletions src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ pub use self::ddl::{
AlterColumnOperation, AlterIndexOperation, AlterTableOperation, ColumnDef, ColumnOption,
ColumnOptionDef, GeneratedAs, GeneratedExpressionMode, IndexType, KeyOrIndexDisplay, Partition,
ProcedureParam, ReferentialAction, TableConstraint, UserDefinedTypeCompositeAttributeDef,
UserDefinedTypeRepresentation,
UserDefinedTypeRepresentation, ViewColumnDef,
};
pub use self::operator::{BinaryOperator, UnaryOperator};
pub use self::query::{
Expand Down Expand Up @@ -1364,6 +1364,38 @@ pub enum Password {
NullPassword,
}

/// Sql options of a `CREATE TABLE` statement.
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum CreateTableOptions {
None,
/// Options specified using the `WITH` keyword.
/// e.g. `WITH (description = "123")`
///
/// <https://www.postgresql.org/docs/current/sql-createtable.html>
With(Vec<SqlOption>),
/// Options specified using the `OPTIONS` keyword.
/// e.g. `OPTIONS(description = "123")`
///
/// <https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#table_option_list>
Options(Vec<SqlOption>),
}

impl fmt::Display for CreateTableOptions {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
CreateTableOptions::With(with_options) => {
write!(f, "WITH ({})", display_comma_separated(with_options))
}
CreateTableOptions::Options(options) => {
write!(f, "OPTIONS({})", display_comma_separated(options))
}
CreateTableOptions::None => Ok(()),
}
}
}

/// A top-level statement (SELECT, INSERT, CREATE, etc.)
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
Expand Down Expand Up @@ -1512,9 +1544,9 @@ pub enum Statement {
materialized: bool,
/// View name
name: ObjectName,
columns: Vec<Ident>,
columns: Vec<ViewColumnDef>,
query: Box<Query>,
with_options: Vec<SqlOption>,
options: CreateTableOptions,
cluster_by: Vec<Ident>,
/// if true, has RedShift [`WITH NO SCHEMA BINDING`] clause <https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_VIEW.html>
with_no_schema_binding: bool,
Expand Down Expand Up @@ -1560,6 +1592,8 @@ pub enum Statement {
/// than empty (represented as ()), the latter meaning "no sorting".
/// <https://clickhouse.com/docs/en/sql-reference/statements/create/table/>
order_by: Option<Vec<Ident>>,
/// Database specific configuration during table creation.
table_config: Option<Box<CreateTableConfiguration>>,
/// SQLite "STRICT" clause.
/// if the "STRICT" table-option keyword is added to the end, after the closing ")",
/// then strict typing rules apply to that table.
Expand Down Expand Up @@ -2499,7 +2533,7 @@ impl fmt::Display for Statement {
columns,
query,
materialized,
with_options,
options,
cluster_by,
with_no_schema_binding,
if_not_exists,
Expand All @@ -2514,15 +2548,18 @@ impl fmt::Display for Statement {
temporary = if *temporary { "TEMPORARY " } else { "" },
if_not_exists = if *if_not_exists { "IF NOT EXISTS " } else { "" }
)?;
if !with_options.is_empty() {
write!(f, " WITH ({})", display_comma_separated(with_options))?;
if matches!(options, CreateTableOptions::With(_)) {
write!(f, " {options}")?;
}
if !columns.is_empty() {
write!(f, " ({})", display_comma_separated(columns))?;
}
if !cluster_by.is_empty() {
write!(f, " CLUSTER BY ({})", display_comma_separated(cluster_by))?;
}
if matches!(options, CreateTableOptions::Options(_)) {
write!(f, " {options}")?;
}
write!(f, " AS {query}")?;
if *with_no_schema_binding {
write!(f, " WITH NO SCHEMA BINDING")?;
Expand Down Expand Up @@ -2557,6 +2594,7 @@ impl fmt::Display for Statement {
on_commit,
on_cluster,
order_by,
table_config,
strict,
} => {
// We want to allow the following options
Expand Down Expand Up @@ -2713,6 +2751,27 @@ impl fmt::Display for Statement {
if let Some(order_by) = order_by {
write!(f, " ORDER BY ({})", display_comma_separated(order_by))?;
}
if let Some(CreateTableConfiguration::BigQuery(big_query_config)) =
table_config.as_ref().map(|c| c.as_ref())
{
if let Some(partition_by) = big_query_config.partition_by.as_ref() {
write!(f, " PARTITION BY {partition_by}")?;
}
if let Some(cluster_by) = big_query_config.cluster_by.as_ref() {
write!(
f,
" CLUSTER BY {}",
display_comma_separated(cluster_by.as_slice())
)?;
}
if let Some(options) = big_query_config.options.as_ref() {
write!(
f,
" OPTIONS({})",
display_comma_separated(options.as_slice())
)?;
}
}
if let Some(query) = query {
write!(f, " AS {query}")?;
}
Expand Down Expand Up @@ -4220,12 +4279,39 @@ pub struct HiveFormat {
pub location: Option<String>,
}

/// Represents BigQuery specific configuration like partitioning, clustering
/// information during table creation.
///
/// <https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#create_table_statement>
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct BigQueryCreateTableConfiguration {
/// A partition expression for the table.
/// <https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#partition_expression>
pub partition_by: Option<Expr>,
/// Table clustering column list.
/// <https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#table_option_list>
pub cluster_by: Option<Vec<Ident>>,
/// Table options list.
/// <https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#table_option_list>
pub options: Option<Vec<SqlOption>>,
}

/// Represents database specific configuration during table creation.
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum CreateTableConfiguration {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if you considered inlining these into Statement::CreateTable rather than adding a new structure?

Like

/// CREATE TABLE
CreateTable {
    or_replace: bool,
    temporary: bool,
    external: bool,
    /// A partition expression for the table.
    /// <https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#partition_expression>
    partition_by: Option<Expr>,
    /// Table clustering column list.
    /// <https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#table_option_list>
     cluster_by: Option<Vec<Ident>>,
    /// Table options list.
    /// <https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#table_option_list>
     options: Option<Vec<SqlOption>>,
...

I think that might be more consistent with other dialect specific fields as well as order_by and strict.

Having an extra struct here also may be confusing as it doesn't seem to mirror the structure of the SQL -- for example, it seems to imply to me that there is some sort of "CONFIG" keyword / clause that appears in the SQL when https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#create_table_statement seems to imply that PARTITION BY CLUSTER BY and OPTIONS are clauses of the CREATE TABLE statement itself

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah yes I figured to have them inline initially, agree that makes it less confusing. The only issue was with serializing back to SQL text - since the fields in bigquery's case have a defined order (e.g PARTITION BY before CLUSTER BY), the inlined fields might end up not being reusable by other dialects if they show up at different parts of the CREATE statement. I'm not so sure if that's worth optimizing for though, so happy to just inline them if that's preferrable

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think an inlined version would be better to maintain consistency. If someone needs a different order when serializing for another dialect we can add that as a follow on PR perhaps.

If for some reason we need to keep the separate struct I think that would be acceptable if there were some doc comments explaining the rational (as that is not easy to understand from the code).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That sounds good! Will make updates to this

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Inlined!

BigQuery(BigQueryCreateTableConfiguration),
}

#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct SqlOption {
pub name: Ident,
pub value: Value,
pub value: Expr,
}

impl fmt::Display for SqlOption {
Expand Down
Loading
Loading