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

*: support create table with range type table partition. #6251

Merged
merged 8 commits into from
Apr 12, 2018
Merged
Show file tree
Hide file tree
Changes from 7 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
17 changes: 17 additions & 0 deletions ast/ddl.go
Original file line number Diff line number Diff line change
Expand Up @@ -403,6 +403,7 @@ type CreateTableStmt struct {
Cols []*ColumnDef
Constraints []*Constraint
Options []*TableOption
Partition *PartitionOptions
}

// Accept implements Node Accept interface.
Expand Down Expand Up @@ -846,3 +847,19 @@ func (n *TruncateTableStmt) Accept(v Visitor) (Node, bool) {
n.Table = node.(*TableName)
return v.Leave(n)
}

// PartitionDefinition defines a single partition.
type PartitionDefinition struct {
Copy link
Member

Choose a reason for hiding this comment

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

s/PartitionDefinition/RangePartitionDefinition/ ?

Copy link
Member Author

Choose a reason for hiding this comment

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

It can hold other partition types.

Name string
LessThan []ExprNode
MaxValue bool
Comment string
}

// PartitionOptions specifies the partition options.
type PartitionOptions struct {
Tp model.PartitionType
Expr ExprNode
ColumnNames []*ColumnName
Definitions []*PartitionDefinition
}
3 changes: 1 addition & 2 deletions ddl/ddl.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,8 +154,7 @@ var (
type DDL interface {
CreateSchema(ctx sessionctx.Context, name model.CIStr, charsetInfo *ast.CharsetOpt) error
DropSchema(ctx sessionctx.Context, schema model.CIStr) error
CreateTable(ctx sessionctx.Context, ident ast.Ident, cols []*ast.ColumnDef,
constrs []*ast.Constraint, options []*ast.TableOption) error
CreateTable(ctx sessionctx.Context, stmt *ast.CreateTableStmt) error
CreateTableWithLike(ctx sessionctx.Context, ident, referIdent ast.Ident) error
DropTable(ctx sessionctx.Context, tableIdent ast.Ident) (err error)
CreateIndex(ctx sessionctx.Context, tableIdent ast.Ident, unique bool, indexName model.CIStr,
Expand Down
52 changes: 48 additions & 4 deletions ddl/ddl_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -740,14 +740,22 @@ func (d *ddl) CreateTableWithLike(ctx sessionctx.Context, ident, referIdent ast.
return errors.Trace(err)
}

func (d *ddl) CreateTable(ctx sessionctx.Context, ident ast.Ident, colDefs []*ast.ColumnDef,
constraints []*ast.Constraint, options []*ast.TableOption) (err error) {
func (d *ddl) CreateTable(ctx sessionctx.Context, s *ast.CreateTableStmt) (err error) {
ident := ast.Ident{Schema: s.Table.Schema, Name: s.Table.Name}
if s.ReferTable != nil {
referIdent := ast.Ident{Schema: s.ReferTable.Schema, Name: s.ReferTable.Name}
return d.CreateTableWithLike(ctx, ident, referIdent)
}
colDefs := s.Cols
is := d.GetInformationSchema()
schema, ok := is.SchemaByName(ident.Schema)
if !ok {
return infoschema.ErrDatabaseNotExists.GenByArgs(ident.Schema)
}
if is.TableExists(ident.Schema, ident.Name) {
if s.IfNotExists {
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 add a test to cover this logic?

return nil
}
return infoschema.ErrTableExists.GenByArgs(ident)
}
if err = checkTooLongTable(ident.Name); err != nil {
Expand All @@ -766,7 +774,7 @@ func (d *ddl) CreateTable(ctx sessionctx.Context, ident ast.Ident, colDefs []*as
return errors.Trace(err)
}

cols, newConstraints, err := buildColumnsAndConstraints(ctx, colDefs, constraints)
cols, newConstraints, err := buildColumnsAndConstraints(ctx, colDefs, s.Constraints)
if err != nil {
return errors.Trace(err)
}
Expand All @@ -780,6 +788,42 @@ func (d *ddl) CreateTable(ctx sessionctx.Context, ident ast.Ident, colDefs []*as
if err != nil {
return errors.Trace(err)
}
if s.Partition != nil {
pi := &model.PartitionInfo{
Type: s.Partition.Tp,
Expr: s.Partition.Expr.Text(),
}
if s.Partition.Expr != nil {
buf := new(bytes.Buffer)
s.Partition.Expr.Format(buf)
pi.Expr = buf.String()
} else if s.Partition.ColumnNames != nil {
pi.Columns = make([]model.CIStr, 0, len(s.Partition.ColumnNames))
for _, cn := range s.Partition.ColumnNames {
pi.Columns = append(pi.Columns, cn.Name)
}
}
for _, def := range s.Partition.Definitions {
// TODO: generate multiple global ID for paritions.
pid, err1 := d.genGlobalID()
if err1 != nil {
return errors.Trace(err1)
}
piDef := model.PartitionDefinition{
Name: def.Name,
ID: pid,
Comment: def.Comment,
MaxValue: def.MaxValue,
}
for _, expr := range def.LessThan {
buf := new(bytes.Buffer)
expr.Format(buf)
piDef.LessThan = append(piDef.LessThan, buf.String())
}
pi.Definitions = append(pi.Definitions, piDef)
}
tbInfo.Partition = pi
}

job := &model.Job{
SchemaID: schema.ID,
Expand All @@ -789,7 +833,7 @@ func (d *ddl) CreateTable(ctx sessionctx.Context, ident ast.Ident, colDefs []*as
Args: []interface{}{tbInfo},
}

handleTableOptions(options, tbInfo)
handleTableOptions(s.Options, tbInfo)
err = checkCharsetAndCollation(tbInfo.Charset, tbInfo.Collate)
if err != nil {
return errors.Trace(err)
Expand Down
28 changes: 28 additions & 0 deletions ddl/ddl_db_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1407,6 +1407,7 @@ func (s *testDBSuite) TestCreateTableWithLike(c *C) {
func (s *testDBSuite) TestCreateTable(c *C) {
s.tk.MustExec("use test")
s.tk.MustExec("CREATE TABLE `t` (`a` double DEFAULT 1.0 DEFAULT now() DEFAULT 2.0 );")
s.tk.MustExec("CREATE TABLE IF NOT EXISTS `t` (`a` double DEFAULT 1.0 DEFAULT now() DEFAULT 2.0 );")
ctx := s.tk.Se.(sessionctx.Context)
is := domain.GetDomain(ctx).InfoSchema()
tbl, err := is.TableByName(model.NewCIStr("test"), model.NewCIStr("t"))
Expand All @@ -1426,6 +1427,33 @@ func (s *testDBSuite) TestCreateTable(c *C) {
c.Assert(err, NotNil)
}

func (s *testDBSuite) TestCreateTableWithPartition(c *C) {
s.tk.MustExec("use test")
s.tk.MustExec(`CREATE TABLE tp (a int) PARTITION BY RANGE(a) (
PARTITION p0 VALUES LESS THAN (10),
PARTITION p1 VALUES LESS THAN (20),
PARTITION p2 VALUES LESS THAN (MAXVALUE)
);`)
ctx := s.tk.Se.(sessionctx.Context)
is := domain.GetDomain(ctx).InfoSchema()
tbl, err := is.TableByName(model.NewCIStr("test"), model.NewCIStr("tp"))
c.Assert(err, IsNil)
c.Assert(tbl.Meta().Partition, NotNil)
part := tbl.Meta().Partition
c.Assert(part.Type, Equals, model.PartitionTypeRange)
c.Assert(part.Expr, Equals, "`a`")
for _, pdef := range part.Definitions {
c.Assert(pdef.ID, Greater, int64(0))
}
c.Assert(part.Definitions, HasLen, 3)
c.Assert(part.Definitions[0].LessThan[0], Equals, "10")
c.Assert(part.Definitions[0].Name, Equals, "p0")
c.Assert(part.Definitions[1].LessThan[0], Equals, "20")
c.Assert(part.Definitions[1].Name, Equals, "p1")
c.Assert(part.Definitions[2].MaxValue, IsTrue)
c.Assert(part.Definitions[2].Name, Equals, "p2")
}

func (s *testDBSuite) TestTruncateTable(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
Expand Down
15 changes: 1 addition & 14 deletions executor/ddl.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,20 +120,7 @@ func (e *DDLExec) executeCreateDatabase(s *ast.CreateDatabaseStmt) error {
}

func (e *DDLExec) executeCreateTable(s *ast.CreateTableStmt) error {
ident := ast.Ident{Schema: s.Table.Schema, Name: s.Table.Name}
var err error
if s.ReferTable == nil {
err = domain.GetDomain(e.ctx).DDL().CreateTable(e.ctx, ident, s.Cols, s.Constraints, s.Options)
} else {
referIdent := ast.Ident{Schema: s.ReferTable.Schema, Name: s.ReferTable.Name}
err = domain.GetDomain(e.ctx).DDL().CreateTableWithLike(e.ctx, ident, referIdent)
}
if infoschema.ErrTableExists.Equal(err) {
if s.IfNotExists {
return nil
}
return err
}
err := domain.GetDomain(e.ctx).DDL().CreateTable(e.ctx, s)
return errors.Trace(err)
}

Expand Down
30 changes: 30 additions & 0 deletions model/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,8 @@ type TableInfo struct {

// ShardRowIDBits specify if the implicit row ID is sharded.
ShardRowIDBits uint64

Partition *PartitionInfo
}

// GetUpdateTime gets the table's updating time.
Expand Down Expand Up @@ -221,6 +223,34 @@ func (t *TableInfo) ColumnIsInIndex(c *ColumnInfo) bool {
return false
}

// PartitionType is the type for PartitionInfo
type PartitionType int

// Partition types.
const (
PartitionTypeRange PartitionType = 1
PartitionTypeHash PartitionType = 2
PartitionTypeList PartitionType = 3
)

// PartitionInfo provides table partition info.
type PartitionInfo struct {
Type PartitionType
Expr string
Columns []CIStr

Definitions []PartitionDefinition
}

// PartitionDefinition defines a single partition.
type PartitionDefinition struct {
ID int64
Name string
LessThan []string
Copy link
Member

Choose a reason for hiding this comment

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

LessThan is only used in range partition ?

Copy link
Member Author

Choose a reason for hiding this comment

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

Yes

Copy link
Member

Choose a reason for hiding this comment

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

so how do we define a hash or list or key partition ?

Copy link
Contributor

Choose a reason for hiding this comment

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

It would be implemented later... @zz-jason

Copy link
Member

Choose a reason for hiding this comment

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

I think we should implement a more extensible struct to define partition info.

Copy link
Member Author

Choose a reason for hiding this comment

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

It's compatible when we add new fields later.

Comment string `json:"omit_empty"`
MaxValue bool
}

// IndexColumn provides index column info.
type IndexColumn struct {
Name CIStr `json:"name"` // Index name
Expand Down
96 changes: 80 additions & 16 deletions parser/parser.y
Original file line number Diff line number Diff line change
Expand Up @@ -666,6 +666,7 @@ import (
PartitionDefinitionListOpt "Partition definition list option"
PartitionOpt "Partition option"
PartitionNumOpt "PARTITION NUM option"
PartDefCommentOpt "Partition comment"
PartDefValuesOpt "VALUES {LESS THAN {(expr | value_list) | MAXVALUE} | IN {value_list}"
PartDefStorageOpt "ENGINE = xxx or empty"
PasswordOpt "Password option"
Expand Down Expand Up @@ -1703,12 +1704,17 @@ CreateTableStmt:
yylex.Errorf("Column Definition List can't be empty.")
return 1
}
var part *ast.PartitionOptions
if $9 != nil {
part = $9.(*ast.PartitionOptions)
}
$$ = &ast.CreateTableStmt{
Table: $4.(*ast.TableName),
IfNotExists: $3.(bool),
Cols: columnDefs,
Constraints: constraints,
Options: $8.([]*ast.TableOption),
Partition: part,
}
}
| "CREATE" "TABLE" IfNotExists TableName "LIKE" TableName
Expand All @@ -1725,49 +1731,107 @@ DefaultKwdOpt:
| "DEFAULT"

PartitionOpt:
{}
{
$$ = nil
}
| "PARTITION" "BY" "KEY" '(' ColumnNameList ')' PartitionNumOpt PartitionDefinitionListOpt
{}
{
$$ = nil
}
| "PARTITION" "BY" "HASH" '(' Expression ')' PartitionNumOpt PartitionDefinitionListOpt
{}
{
$$ = nil
}
| "PARTITION" "BY" "RANGE" '(' Expression ')' PartitionNumOpt PartitionDefinitionListOpt
{}
{
var defs []*ast.PartitionDefinition
if $8 != nil {
defs = $8.([]*ast.PartitionDefinition)
}
$$ = &ast.PartitionOptions{
Tp: model.PartitionTypeRange,
Expr: $5.(ast.ExprNode),
Definitions: defs,
}
}
| "PARTITION" "BY" "RANGE" "COLUMNS" '(' ColumnNameList ')' PartitionNumOpt PartitionDefinitionListOpt
{}
{
var defs []*ast.PartitionDefinition
if $9 != nil {
defs = $9.([]*ast.PartitionDefinition)
}
$$ = &ast.PartitionOptions{
Tp: model.PartitionTypeRange,
ColumnNames: $6.([]*ast.ColumnName),
Definitions: defs,
}
}

PartitionNumOpt:
{}
| "PARTITIONS" NUM
{}

PartitionDefinitionListOpt:
{}
{
$$ = nil
}
| '(' PartitionDefinitionList ')'
{}
{
$$ = $2.([]*ast.PartitionDefinition)
}

PartitionDefinitionList:
PartitionDefinition
{}
{
$$ = []*ast.PartitionDefinition{$1.(*ast.PartitionDefinition)}
}
| PartitionDefinitionList ',' PartitionDefinition
{}
{
$$ = append($1.([]*ast.PartitionDefinition), $3.(*ast.PartitionDefinition))
}

PartitionDefinition:
"PARTITION" Identifier PartDefValuesOpt PartDefCommentOpt PartDefStorageOpt
{}
{
partDef := &ast.PartitionDefinition{
Name: $2,
Comment: $4.(string),
}
switch $3.(type) {
case []ast.ExprNode:
partDef.LessThan = $3.([]ast.ExprNode)
case bool:
partDef.MaxValue = true
}
$$ = partDef
}

PartDefCommentOpt:
{}
{
$$ = ""
}
| "COMMENT" eq stringLit
{}
{
$$ = $3
}

PartDefValuesOpt:
{}
{
$$ = nil
}
| "VALUES" "LESS" "THAN" "MAXVALUE"
{}
{
$$ = true
}
| "VALUES" "LESS" "THAN" '(' "MAXVALUE" ')'
{}
{
$$ = true
}
| "VALUES" "LESS" "THAN" '(' ExpressionList ')'
{}
{
$$ = $5
}

PartDefStorageOpt:
{}
Expand Down