Skip to content

Add support column prefix index for MySQL #1732

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

Closed
wants to merge 5 commits into from
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 20 additions & 18 deletions src/ast/ddl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,9 @@ use crate::ast::value::escape_single_quote_string;
use crate::ast::{
display_comma_separated, display_separated, CommentDef, CreateFunctionBody,
CreateFunctionUsing, DataType, Expr, FunctionBehavior, FunctionCalledOnNull,
FunctionDeterminismSpecifier, FunctionParallel, Ident, MySQLColumnPosition, ObjectName,
OperateFunctionArg, OrderByExpr, ProjectionSelect, SequenceOptions, SqlOption, Tag, Value,
FunctionDeterminismSpecifier, FunctionParallel, Ident, IndexExpr, MySQLColumnPosition,
ObjectName, OperateFunctionArg, OrderByExpr, ProjectionSelect, SequenceOptions, SqlOption, Tag,
Value,
};
use crate::keywords::Keyword;
use crate::tokenizer::Token;
Expand Down Expand Up @@ -832,8 +833,8 @@ pub enum TableConstraint {
///
/// [1]: IndexType
index_type: Option<IndexType>,
/// Identifiers of the columns that are unique.
columns: Vec<Ident>,
/// Index expr list.
index_exprs: Vec<IndexExpr>,
index_options: Vec<IndexOption>,
characteristics: Option<ConstraintCharacteristics>,
/// Optional Postgres nulls handling: `[ NULLS [ NOT ] DISTINCT ]`
Expand Down Expand Up @@ -868,8 +869,8 @@ pub enum TableConstraint {
///
/// [1]: IndexType
index_type: Option<IndexType>,
/// Identifiers of the columns that form the primary key.
columns: Vec<Ident>,
/// Index expr list.
index_exprs: Vec<IndexExpr>,
index_options: Vec<IndexOption>,
characteristics: Option<ConstraintCharacteristics>,
},
Expand Down Expand Up @@ -907,8 +908,8 @@ pub enum TableConstraint {
///
/// [1]: IndexType
index_type: Option<IndexType>,
/// Referred column identifier list.
columns: Vec<Ident>,
/// Index expr list.
index_exprs: Vec<IndexExpr>,
},
/// MySQLs [fulltext][1] definition. Since the [`SPATIAL`][2] definition is exactly the same,
/// and MySQL displays both the same way, it is part of this definition as well.
Expand All @@ -930,8 +931,8 @@ pub enum TableConstraint {
index_type_display: KeyOrIndexDisplay,
/// Optional index name.
opt_index_name: Option<Ident>,
/// Referred column identifier list.
columns: Vec<Ident>,
/// Index expr list.
index_exprs: Vec<IndexExpr>,
},
}

Expand All @@ -943,7 +944,7 @@ impl fmt::Display for TableConstraint {
index_name,
index_type_display,
index_type,
columns,
index_exprs,
index_options,
characteristics,
nulls_distinct,
Expand All @@ -954,7 +955,7 @@ impl fmt::Display for TableConstraint {
display_constraint_name(name),
display_option_spaced(index_name),
display_option(" USING ", "", index_type),
display_comma_separated(columns),
display_comma_separated(index_exprs),
)?;

if !index_options.is_empty() {
Expand All @@ -968,7 +969,7 @@ impl fmt::Display for TableConstraint {
name,
index_name,
index_type,
columns,
index_exprs,
index_options,
characteristics,
} => {
Expand All @@ -978,7 +979,7 @@ impl fmt::Display for TableConstraint {
display_constraint_name(name),
display_option_spaced(index_name),
display_option(" USING ", "", index_type),
display_comma_separated(columns),
display_comma_separated(index_exprs),
)?;

if !index_options.is_empty() {
Expand Down Expand Up @@ -1025,7 +1026,7 @@ impl fmt::Display for TableConstraint {
display_as_key,
name,
index_type,
columns,
index_exprs,
} => {
write!(f, "{}", if *display_as_key { "KEY" } else { "INDEX" })?;
if let Some(name) = name {
Expand All @@ -1034,15 +1035,16 @@ impl fmt::Display for TableConstraint {
if let Some(index_type) = index_type {
write!(f, " USING {index_type}")?;
}
write!(f, " ({})", display_comma_separated(columns))?;

write!(f, " ({})", display_comma_separated(index_exprs))?;

Ok(())
}
Self::FulltextOrSpatial {
fulltext,
index_type_display,
opt_index_name,
columns,
index_exprs,
} => {
if *fulltext {
write!(f, "FULLTEXT")?;
Expand All @@ -1056,7 +1058,7 @@ impl fmt::Display for TableConstraint {
write!(f, " {name}")?;
}

write!(f, " ({})", display_comma_separated(columns))?;
write!(f, " ({})", display_comma_separated(index_exprs))?;

Ok(())
}
Expand Down
31 changes: 31 additions & 0 deletions src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8690,6 +8690,37 @@ pub enum CopyIntoSnowflakeKind {
Location,
}

/// Index Field
///
/// This structure used here [`MySQL` CREATE INDEX][1], [`PostgreSQL` CREATE INDEX][2], [`MySQL` CREATE TABLE][3].
///
/// [1]: https://dev.mysql.com/doc/refman/8.3/en/create-index.html
/// [2]: https://www.postgresql.org/docs/17/sql-createindex.html
/// [3]: https://dev.mysql.com/doc/refman/8.3/en/create-table.html

#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct IndexExpr {
pub expr: Expr,
pub collation: Option<ObjectName>,
pub operator_class: Option<Expr>,
pub order_options: OrderByOptions,
}

impl fmt::Display for IndexExpr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.expr)?;
if let Some(collation) = &self.collation {
write!(f, "{collation}")?;
}
if let Some(operator) = &self.operator_class {
write!(f, "{operator}")?;
}
write!(f, "{}", self.order_options)
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
33 changes: 23 additions & 10 deletions src/ast/spans.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ use super::{
CopySource, CreateIndex, CreateTable, CreateTableOptions, Cte, Delete, DoUpdate,
ExceptSelectItem, ExcludeSelectItem, Expr, ExprWithAlias, Fetch, FromTable, Function,
FunctionArg, FunctionArgExpr, FunctionArgumentClause, FunctionArgumentList, FunctionArguments,
GroupByExpr, HavingBound, IlikeSelectItem, Insert, Interpolate, InterpolateExpr, Join,
JoinConstraint, JoinOperator, JsonPath, JsonPathElem, LateralView, MatchRecognizePattern,
GroupByExpr, HavingBound, IlikeSelectItem, IndexExpr, Insert, Interpolate, InterpolateExpr,
Join, JoinConstraint, JoinOperator, JsonPath, JsonPathElem, LateralView, MatchRecognizePattern,
Measure, NamedWindowDefinition, ObjectName, ObjectNamePart, Offset, OnConflict,
OnConflictAction, OnInsert, OrderBy, OrderByExpr, OrderByKind, Partition, PivotValueSource,
ProjectionSelect, Query, ReferentialAction, RenameSelectItem, ReplaceSelectElement,
Expand Down Expand Up @@ -628,29 +628,29 @@ impl Spanned for TableConstraint {
index_name,
index_type_display: _,
index_type: _,
columns,
index_exprs,
index_options: _,
characteristics,
nulls_distinct: _,
} => union_spans(
name.iter()
.map(|i| i.span)
.chain(index_name.iter().map(|i| i.span))
.chain(columns.iter().map(|i| i.span))
.chain(index_exprs.iter().map(|i| i.span()))
.chain(characteristics.iter().map(|i| i.span())),
),
TableConstraint::PrimaryKey {
name,
index_name,
index_type: _,
columns,
index_exprs,
index_options: _,
characteristics,
} => union_spans(
name.iter()
.map(|i| i.span)
.chain(index_name.iter().map(|i| i.span))
.chain(columns.iter().map(|i| i.span))
.chain(index_exprs.iter().map(|i| i.span()))
.chain(characteristics.iter().map(|i| i.span())),
),
TableConstraint::ForeignKey {
Expand Down Expand Up @@ -678,22 +678,22 @@ impl Spanned for TableConstraint {
display_as_key: _,
name,
index_type: _,
columns,
index_exprs,
} => union_spans(
name.iter()
.map(|i| i.span)
.chain(columns.iter().map(|i| i.span)),
.chain(index_exprs.iter().map(|i| i.span())),
),
TableConstraint::FulltextOrSpatial {
fulltext: _,
index_type_display: _,
opt_index_name,
columns,
index_exprs,
} => union_spans(
opt_index_name
.iter()
.map(|i| i.span)
.chain(columns.iter().map(|i| i.span)),
.chain(index_exprs.iter().map(|i| i.span())),
),
}
}
Expand Down Expand Up @@ -2178,6 +2178,19 @@ impl Spanned for TableObject {
}
}

impl Spanned for IndexExpr {
fn span(&self) -> Span {
let IndexExpr {
expr,
collation: _,
operator_class: _,
order_options: _,
} = self;

union_spans(core::iter::once(expr.span()))
}
}

#[cfg(test)]
pub mod tests {
use crate::dialect::{Dialect, GenericDialect, SnowflakeDialect};
Expand Down
Loading