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

executor, session: refine insert unsigned bigint autoIncreID #8181

Merged
merged 24 commits into from
Dec 18, 2018
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
a7df24d
executor, session: refine insert unsigned bigint autoIncreID
XuHuaiyu Nov 5, 2018
9d21807
address comment
XuHuaiyu Nov 8, 2018
2db694e
update parser
XuHuaiyu Nov 12, 2018
1eb9325
Merge branch 'master' of https://github.com/pingcap/tidb into unsigne…
XuHuaiyu Nov 12, 2018
53fd0a6
address comment
XuHuaiyu Nov 12, 2018
758fd31
address comment
XuHuaiyu Nov 13, 2018
a68a08d
make golint happy
XuHuaiyu Nov 13, 2018
c1e1ff6
address commen
XuHuaiyu Nov 13, 2018
9104f74
Merge branch 'master' of https://github.com/pingcap/tidb into unsigne…
XuHuaiyu Nov 16, 2018
fc03231
Merge branch 'master' of https://github.com/pingcap/tidb into unsigne…
XuHuaiyu Dec 10, 2018
82b12d5
address comment
XuHuaiyu Dec 10, 2018
2e8b425
remove go.sum
XuHuaiyu Dec 10, 2018
ce0e447
merge master
XuHuaiyu Dec 10, 2018
874ff0b
address comment
XuHuaiyu Dec 13, 2018
d0616ac
Merge branch 'master' into unsigned_autoid
jackysp Dec 17, 2018
6792306
add unit tests for Allocator
XuHuaiyu Dec 18, 2018
46d20a4
Merge branch 'master' of https://github.com/pingcap/tidb into unsigne…
XuHuaiyu Dec 18, 2018
548ea41
Merge branch 'unsigned_autoid' of https://github.com/XuHuaiyu/tidb in…
XuHuaiyu Dec 18, 2018
61bfec6
update go.mod
XuHuaiyu Dec 18, 2018
6c4419c
address comment
XuHuaiyu Dec 18, 2018
3f1fcb4
make tidy
XuHuaiyu Dec 18, 2018
71ea318
go mod tidy
XuHuaiyu Dec 18, 2018
18c62fe
Merge branch 'master' into unsigned_autoid
XuHuaiyu Dec 18, 2018
d688346
Merge branch 'master' into unsigned_autoid
XuHuaiyu Dec 18, 2018
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
2 changes: 1 addition & 1 deletion ddl/column_change_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,7 @@ func getCurrentTable(d *ddl, schemaID, tableID int64) (table.Table, error) {
if err != nil {
return nil, errors.Trace(err)
}
alloc := autoid.NewAllocator(d.store, schemaID)
alloc := autoid.NewAllocator(d.store, schemaID, false)
tbl, err := table.TableFromMeta(alloc, tblInfo)
if err != nil {
return nil, errors.Trace(err)
Expand Down
6 changes: 5 additions & 1 deletion ddl/ddl_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -984,7 +984,11 @@ func checkCharsetAndCollation(cs string, co string) error {
// handleAutoIncID handles auto_increment option in DDL. It creates a ID counter for the table and initiates the counter to a proper value.
// For example if the option sets auto_increment to 10. The counter will be set to 9. So the next allocated ID will be 10.
func (d *ddl) handleAutoIncID(tbInfo *model.TableInfo, schemaID int64) error {
alloc := autoid.NewAllocator(d.store, tbInfo.GetDBID(schemaID))
isAutoIncColUnsigned := false
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 it is better to extract these lines to a function.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

you mean line1024~1028?

Copy link
Member

Choose a reason for hiding this comment

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

Yes, I see some similar code in this PR.

if autoIncrementCol := tbInfo.GetAutoIncrementColInfo(); autoIncrementCol != nil {
isAutoIncColUnsigned = mysql.HasUnsignedFlag(autoIncrementCol.Flag)
}
alloc := autoid.NewAllocator(d.store, tbInfo.GetDBID(schemaID), isAutoIncColUnsigned)
tbInfo.State = model.StatePublic
tb, err := table.TableFromMeta(alloc, tbInfo)
if err != nil {
Expand Down
7 changes: 6 additions & 1 deletion ddl/table.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (

"github.com/pingcap/errors"
"github.com/pingcap/parser/model"
"github.com/pingcap/parser/mysql"
"github.com/pingcap/tidb/ddl/util"
"github.com/pingcap/tidb/infoschema"
"github.com/pingcap/tidb/kv"
Expand Down Expand Up @@ -154,7 +155,11 @@ func splitTableRegion(store kv.Storage, tableID int64) {
}

func getTable(store kv.Storage, schemaID int64, tblInfo *model.TableInfo) (table.Table, error) {
alloc := autoid.NewAllocator(store, tblInfo.GetDBID(schemaID))
isAutoIncColUnsigned := false
if autoIncrementCol := tblInfo.GetAutoIncrementColInfo(); autoIncrementCol != nil {
isAutoIncColUnsigned = mysql.HasUnsignedFlag(autoIncrementCol.Flag)
}
alloc := autoid.NewAllocator(store, tblInfo.GetDBID(schemaID), isAutoIncColUnsigned)
tbl, err := table.TableFromMeta(alloc, tblInfo)
return tbl, errors.Trace(err)
}
Expand Down
2 changes: 1 addition & 1 deletion ddl/table_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ func testGetTableWithError(d *ddl, schemaID, tableID int64) (table.Table, error)
if tblInfo == nil {
return nil, errors.New("table not found")
}
alloc := autoid.NewAllocator(d.store, schemaID)
alloc := autoid.NewAllocator(d.store, schemaID, false)
tbl, err := table.TableFromMeta(alloc, tblInfo)
if err != nil {
return nil, errors.Trace(err)
Expand Down
2 changes: 1 addition & 1 deletion executor/executor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2816,7 +2816,7 @@ func (s *testSuite) TestCheckIndex(c *C) {
c.Assert(err, IsNil)
tbInfo := tbl.Meta()

alloc := autoid.NewAllocator(s.store, dbInfo.ID)
alloc := autoid.NewAllocator(s.store, dbInfo.ID, false)
tb, err := tables.TableFromMeta(alloc, tbInfo)
c.Assert(err, IsNil)

Expand Down
6 changes: 4 additions & 2 deletions executor/insert_common.go
Original file line number Diff line number Diff line change
Expand Up @@ -446,10 +446,12 @@ func (e *InsertValues) adjustAutoIncrementDatum(d types.Datum, hasValue bool, c
d.SetNull()
}
if !d.IsNull() {
recordID, err = d.ToInt64(e.ctx.GetSessionVars().StmtCtx)
sc := e.ctx.GetSessionVars().StmtCtx
datum, err := d.ConvertTo(sc, &c.FieldType)
if e.filterErr(err) != nil {
return types.Datum{}, errors.Trace(err)
return types.Datum{}, err
}
recordID = datum.GetInt64()
}
// Use the value if it's not null and not 0.
if recordID != 0 {
Expand Down
13 changes: 11 additions & 2 deletions infoschema/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (

"github.com/pingcap/errors"
"github.com/pingcap/parser/model"
"github.com/pingcap/parser/mysql"
"github.com/pingcap/tidb/meta"
"github.com/pingcap/tidb/meta/autoid"
"github.com/pingcap/tidb/perfschema"
Expand Down Expand Up @@ -173,7 +174,11 @@ func (b *Builder) applyCreateTable(m *meta.Meta, dbInfo *model.DBInfo, tableID i
}
if alloc == nil {
schemaID := dbInfo.ID
alloc = autoid.NewAllocator(b.handle.store, tblInfo.GetDBID(schemaID))
isAutoIncColUnsigned := false
if autoIncrementCol := tblInfo.GetAutoIncrementColInfo(); autoIncrementCol != nil {
isAutoIncColUnsigned = mysql.HasUnsignedFlag(autoIncrementCol.Flag)
}
alloc = autoid.NewAllocator(b.handle.store, tblInfo.GetDBID(schemaID), isAutoIncColUnsigned)
}
tbl, err := tables.TableFromMeta(alloc, tblInfo)
if err != nil {
Expand Down Expand Up @@ -276,7 +281,11 @@ func (b *Builder) createSchemaTablesForDB(di *model.DBInfo) error {
b.is.schemaMap[di.Name.L] = schTbls
for _, t := range di.Tables {
schemaID := di.ID
alloc := autoid.NewAllocator(b.handle.store, t.GetDBID(schemaID))
isAutoIncColUnsigned := false
if autoIncrementCol := t.GetAutoIncrementColInfo(); autoIncrementCol != nil {
isAutoIncColUnsigned = mysql.HasUnsignedFlag(autoIncrementCol.Flag)
}
alloc := autoid.NewAllocator(b.handle.store, t.GetDBID(schemaID), isAutoIncColUnsigned)
var tbl table.Table
tbl, err := tables.TableFromMeta(alloc, t)
if err != nil {
Expand Down
64 changes: 49 additions & 15 deletions meta/autoid/autoid.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ type allocator struct {
end int64
store kv.Storage
// dbID is current database's ID.
dbID int64
dbID int64
isUnsigned bool
}

// GetStep is only used by tests
Expand Down Expand Up @@ -91,7 +92,10 @@ func (alloc *allocator) NextGlobalAutoID(tableID int64) (int64, error) {
return errors.Trace(err1)
})
metrics.AutoIDHistogram.WithLabelValues(metrics.GlobalAutoID, metrics.RetLabel(err)).Observe(time.Since(startTime).Seconds())
return autoID + 1, errors.Trace(err)
if alloc.isUnsigned {
return int64(uint64(autoID) + 1), err
}
return autoID + 1, err
}

// Rebase implements autoid.Allocator Rebase interface.
Expand All @@ -104,40 +108,69 @@ func (alloc *allocator) Rebase(tableID, requiredBase int64, allocIDs bool) error

alloc.mu.Lock()
defer alloc.mu.Unlock()
if requiredBase <= alloc.base {
// Satisfied by alloc.base, nothing to do.

// Satisfied by alloc.base, nothing to do.
if !alloc.isUnsigned && requiredBase <= alloc.base {
return nil
} else if alloc.isUnsigned && uint64(requiredBase) <= uint64(alloc.base) {
return nil
}
if requiredBase <= alloc.end {
// Satisfied by alloc.end, need to updata alloc.base.

// Satisfied by alloc.end, need to update alloc.base.
if !alloc.isUnsigned && requiredBase <= alloc.end {
alloc.base = requiredBase
return nil
} else if alloc.isUnsigned && uint64(requiredBase) <= uint64(alloc.end) {
alloc.base = requiredBase
return nil
}
var newBase, newEnd int64
var uNewBase, uNewEnd uint64
startTime := time.Now()
err := kv.RunInNewTxn(alloc.store, true, func(txn kv.Transaction) error {
m := meta.NewMeta(txn)
currentEnd, err1 := m.GetAutoTableID(alloc.dbID, tableID)
if err1 != nil {
return errors.Trace(err1)
}
uCurrentEnd, uRequiredBase := uint64(currentEnd), uint64(requiredBase)
if allocIDs {
newBase = mathutil.MaxInt64(currentEnd, requiredBase)
newEnd = newBase + step
if alloc.isUnsigned {
Copy link
Contributor

Choose a reason for hiding this comment

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

You want to prevent overflow?
Should we

if uNewBase > (math.Uint64 - step) {
   panic
}

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yes,
but why we panic here? @tiancaiamao

Copy link
Contributor

Choose a reason for hiding this comment

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

Well, maybe error or warning...
I mean, if the ID overflow, it should not be changed to math.Uint64

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This check is used to prevent the alloc.end overflow.
alloc.base is checked here.

It may be reasonable to change alloc.end to math.Uint64 if it will overflow?
@tiancaiamao

Copy link
Contributor

Choose a reason for hiding this comment

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

If alloc.end overflow, what will happen?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@tiancaiamao
The result of TiDB master:

tidb> create table t(a bigint signed not null auto_increment, unique key(a));
Query OK, 0 rows affected (0.02 sec)

tidb> insert into t value(9223372036854775806);
Query OK, 1 row affected (0.00 sec)

tidb> insert into t value();
Query OK, 1 row affected (0.00 sec)

tidb> insert into t value();
Query OK, 1 row affected (0.00 sec)

tidb> insert into t value();
Query OK, 1 row affected (0.00 sec)

tidb> insert into t value();
Query OK, 1 row affected (0.00 sec)

tidb> select * from t;
+----------------------+
| a                    |
+----------------------+
| -9223372036854775808 |
| -9223372036854775806 |
| -9223372036854775804 |
| -9223372036854775802 |
|  9223372036854775806 |
+----------------------+
5 rows in set (0.00 sec)

Copy link
Contributor

Choose a reason for hiding this comment

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

Overwrite the old row id is dangerous for data consistency.
Is it acceptable to change the behavior to throw error?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

As a tradeoff, #8181 (review) may be better?

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 throw error is simple, easier, and more robust.

uNewBase = mathutil.MaxUint64(uCurrentEnd, uRequiredBase)
uNewEnd = uNewBase + uint64(step)
} else {
newBase = mathutil.MaxInt64(currentEnd, requiredBase)
newEnd = newBase + step
}
} else {
if currentEnd >= requiredBase {

if !alloc.isUnsigned && currentEnd >= requiredBase {
Copy link
Contributor

Choose a reason for hiding this comment

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

ditto.

Copy link
Contributor

Choose a reason for hiding this comment

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

!alloc.isUnsigned will always be true here?

newBase = currentEnd
newEnd = currentEnd
// Required base satisfied, we don't need to update KV.
return nil
} else if alloc.isUnsigned && uCurrentEnd >= uRequiredBase {
uNewBase = uCurrentEnd
uNewEnd = uCurrentEnd
return nil
}
// If we don't want to allocate IDs, for example when creating a table with a given base value,
// We need to make sure when other TiDB server allocates ID for the first time, requiredBase + 1
// will be allocated, so we need to increase the end to exactly the requiredBase.
newBase = requiredBase
newEnd = requiredBase
if !alloc.isUnsigned {
newBase = requiredBase
newEnd = requiredBase
} else {
uNewBase = uRequiredBase
uNewEnd = uRequiredBase
}

}
if !alloc.isUnsigned {
_, err1 = m.GenAutoTableID(alloc.dbID, tableID, newEnd-currentEnd)
} else {
_, err1 = m.GenAutoTableID(alloc.dbID, tableID, int64(uNewEnd-uCurrentEnd))
}
_, err1 = m.GenAutoTableID(alloc.dbID, tableID, newEnd-currentEnd)
return errors.Trace(err1)
})
metrics.AutoIDHistogram.WithLabelValues(metrics.TableAutoIDRebase, metrics.RetLabel(err)).Observe(time.Since(startTime).Seconds())
Expand Down Expand Up @@ -237,10 +270,11 @@ func (alloc *memoryAllocator) Alloc(tableID int64) (int64, error) {
}

// NewAllocator returns a new auto increment id generator on the store.
func NewAllocator(store kv.Storage, dbID int64) Allocator {
func NewAllocator(store kv.Storage, dbID int64, isUnsigned bool) Allocator {
return &allocator{
store: store,
dbID: dbID,
store: store,
dbID: dbID,
isUnsigned: isUnsigned,
}
}

Expand Down
14 changes: 7 additions & 7 deletions meta/autoid/autoid_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func (*testSuite) TestT(c *C) {
})
c.Assert(err, IsNil)

alloc := autoid.NewAllocator(store, 1)
alloc := autoid.NewAllocator(store, 1, false)
Copy link
Contributor

Choose a reason for hiding this comment

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

Please add some tests for NewAllocator when isUnsigned is true. Otherwise, the test coverage of this package will decrease.

c.Assert(alloc, NotNil)

globalAutoId, err := alloc.NextGlobalAutoID(1)
Expand Down Expand Up @@ -97,25 +97,25 @@ func (*testSuite) TestT(c *C) {
c.Assert(err, IsNil)
c.Assert(id, Equals, int64(3011))

alloc = autoid.NewAllocator(store, 1)
alloc = autoid.NewAllocator(store, 1, false)
c.Assert(alloc, NotNil)
id, err = alloc.Alloc(1)
c.Assert(err, IsNil)
c.Assert(id, Equals, int64(autoid.GetStep()+1))

alloc = autoid.NewAllocator(store, 1)
alloc = autoid.NewAllocator(store, 1, false)
c.Assert(alloc, NotNil)
err = alloc.Rebase(2, int64(1), false)
c.Assert(err, IsNil)
id, err = alloc.Alloc(2)
c.Assert(err, IsNil)
c.Assert(id, Equals, int64(2))

alloc = autoid.NewAllocator(store, 1)
alloc = autoid.NewAllocator(store, 1, false)
c.Assert(alloc, NotNil)
err = alloc.Rebase(3, int64(3210), false)
c.Assert(err, IsNil)
alloc = autoid.NewAllocator(store, 1)
alloc = autoid.NewAllocator(store, 1, false)
c.Assert(alloc, NotNil)
err = alloc.Rebase(3, int64(3000), false)
c.Assert(err, IsNil)
Expand Down Expand Up @@ -159,7 +159,7 @@ func (*testSuite) TestConcurrentAlloc(c *C) {
errCh := make(chan error, count)

allocIDs := func() {
alloc := autoid.NewAllocator(store, dbID)
alloc := autoid.NewAllocator(store, dbID, false)
for j := 0; j < int(autoid.GetStep())+5; j++ {
id, err1 := alloc.Alloc(tblID)
if err1 != nil {
Expand Down Expand Up @@ -213,7 +213,7 @@ func (*testSuite) TestRollbackAlloc(c *C) {
injectConf := new(kv.InjectionConfig)
injectConf.SetCommitError(errors.New("injected"))
injectedStore := kv.NewInjectedStore(store, injectConf)
alloc := autoid.NewAllocator(injectedStore, 1)
alloc := autoid.NewAllocator(injectedStore, 1, false)
_, err = alloc.Alloc(2)
c.Assert(err, NotNil)
c.Assert(alloc.Base(), Equals, int64(0))
Expand Down
7 changes: 7 additions & 0 deletions session/session_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -704,6 +704,13 @@ func (s *testSessionSuite) TestAutoIncrementID(c *C) {

tk.MustQuery("select last_insert_id(20)").Check(testkit.Rows(fmt.Sprint(20)))
tk.MustQuery("select last_insert_id()").Check(testkit.Rows(fmt.Sprint(20)))

tk.MustExec("drop table if exists autoid")
tk.MustExec("create table autoid(`auto_inc_id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,UNIQUE KEY `auto_inc_id` (`auto_inc_id`))")
tk.MustExec("insert into autoid values(9223372036854775808);")
tk.MustExec("insert into autoid values();")
tk.MustExec("insert into autoid values();")
tk.MustQuery("select * from autoid").Check(testkit.Rows("9223372036854775808", "9223372036854775810", "9223372036854775812"))
}

func (s *testSessionSuite) TestAutoIncrementWithRetry(c *C) {
Expand Down
2 changes: 1 addition & 1 deletion util/admin/admin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ func (s *testSuite) TestScan(c *C) {
c.Assert(err, IsNil)
tbInfo := tbl.Meta()

alloc := autoid.NewAllocator(s.store, dbInfo.ID)
alloc := autoid.NewAllocator(s.store, dbInfo.ID, false)
tb, err := tables.TableFromMeta(alloc, tbInfo)
c.Assert(err, IsNil)
indices := tb.Indices()
Expand Down