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

(WIP) Adds support for generated columns in mysql (in create statements) #5867

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
30 changes: 30 additions & 0 deletions src/sqlfluff/dialects/dialect_mysql.py
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,34 @@ class AliasExpressionSegment(BaseSegment):
Dedent,
)

# Mainly adapted from the sparksql implementation
class GeneratedColumnDefinitionSegment(BaseSegment):
"""A generated column definition.

e.g. email_domain CHAR(100) AS (SUBSTRING_INDEX(email, '@', -1))
https://dev.mysql.com/doc/refman/8.0/en/create-table-generated-columns.html
"""
type = "generated_column_definition"

match_grammar: Matchable = Sequence(
Ref("SingleIdentifierGrammar"), # Column name
Ref("DatatypeSegment"), # Column type
Bracketed(Anything(), optional=True), # For types like VARCHAR(100)
Sequence(
Sequence("GENERATED", "ALWAYS", optional=True),
"AS",
Bracketed(
OneOf(
Ref("FunctionSegment"),
Ref("BareFunctionSegment"),
),
),
OneOf("VIRTUAL", "STORED", optional=True)
),
AnyNumberOf(
Ref("ColumnConstraintSegment", optional=True),
),
)

class ColumnDefinitionSegment(BaseSegment):
"""A column definition, e.g. for CREATE TABLE or ALTER TABLE."""
Expand Down Expand Up @@ -380,6 +408,8 @@ class CreateTableStatementSegment(ansi.CreateTableStatementSegment):
https://dev.mysql.com/doc/refman/8.0/en/create-table.html
"""

# TODO check if here is the right place to add the new option of the
# generated column definition
match_grammar = ansi.CreateTableStatementSegment.match_grammar.copy(
insert=[
AnyNumberOf(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@

CREATE TABLE emails (
email CHAR(100) NOT NULL,
email_domain CHAR(100) AS (SUBSTRING_INDEX(email, '@', -1)),
email_domain2 CHAR(100) GENERATED ALWAYS AS (SUBSTRING_INDEX(email, '@', -1)) STORED,
email_domain3 CHAR(100) GENERATED ALWAYS AS (SUBSTRING_INDEX(email, '@', -1)) VIRTUAL
);