Skip to content

Commit

Permalink
sql/mysql: add support for table-level auto_increment
Browse files Browse the repository at this point in the history
  • Loading branch information
a8m committed Feb 12, 2022
1 parent 038f875 commit 2bb71cc
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 4 deletions.
18 changes: 14 additions & 4 deletions schema/schemaspec/spec.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,18 +103,28 @@ type (
}
)

// Int returns an integer from the Value of the Attr. If The value is not a LiteralValue or the value
// Int returns an int from the Value of the Attr. If The value is not a LiteralValue or the value
// cannot be converted to an integer an error is returned.
func (a *Attr) Int() (int, error) {
i, err := a.Int64()
if err != nil {
return 0, err
}
return int(i), nil
}

// Int64 returns an int64 from the Value of the Attr. If The value is not a LiteralValue or the value
// cannot be converted to an integer an error is returned.
func (a *Attr) Int64() (int64, error) {
lit, ok := a.V.(*LiteralValue)
if !ok {
return 0, fmt.Errorf("schema: cannot read attribute %q as literal", a.K)
}
s, err := strconv.Atoi(lit.V)
i, err := strconv.ParseInt(lit.V, 10, 64)
if err != nil {
return 0, fmt.Errorf("schema: cannot read attribute %q as int: %w", a.K, err)
return 0, fmt.Errorf("schema: cannot read attribute %q as integer: %w", a.K, err)
}
return s, nil
return i, nil
}

// String returns a string from the Value of the Attr. If The value is not a LiteralValue
Expand Down
9 changes: 9 additions & 0 deletions sql/mysql/sqlspec.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,15 @@ func convertTable(spec *sqlspec.Table, parent *schema.Schema) (*schema.Table, er
if err := convertCharset(spec, &t.Attrs); err != nil {
return nil, err
}
// MySQL allows setting the initial AUTO_INCREMENT value
// on the table definition.
if attr, ok := spec.Attr("auto_increment"); ok {
b, err := attr.Int64()
if err != nil {
return nil, err
}
t.AddAttrs(&AutoIncrement{V: b})
}
return t, err
}

Expand Down
2 changes: 2 additions & 0 deletions sql/mysql/sqlspec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ table "table" {
enforced = false
}
comment = "table comment"
auto_increment = 1000
}
table "accounts" {
Expand Down Expand Up @@ -185,6 +186,7 @@ table "accounts" {
Attrs: []schema.Attr{&Enforced{V: false}},
},
&schema.Comment{Text: "table comment"},
&AutoIncrement{V: 1000},
},
},
{
Expand Down

0 comments on commit 2bb71cc

Please sign in to comment.