Skip to content

Commit

Permalink
fix a bug that nullable unique index can not find null values using i…
Browse files Browse the repository at this point in the history
…ndex. (pingcap#7163)
  • Loading branch information
winkyao committed Jul 27, 2018
1 parent a78037d commit c3e2963
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
14 changes: 14 additions & 0 deletions distsql/request_builder.go
Expand Up @@ -306,8 +306,22 @@ func encodeIndexKey(sc *stmtctx.StatementContext, ran *ranger.NewRange) ([]byte,
if err != nil {
return nil, nil, errors.Trace(err)
}

if !ran.HighExclude {
high = []byte(kv.Key(high).PrefixNext())
}

var hasNull bool
for _, highVal := range ran.HighVal {
if highVal.IsNull() {
hasNull = true
break
}
}

if hasNull {
// Append 0 to make unique-key range [null, null] to be a scan rather than point-get.
high = []byte(kv.Key(high).Next())
}
return low, high, nil
}
25 changes: 25 additions & 0 deletions executor/distsql_test.go
Expand Up @@ -167,3 +167,28 @@ func (s *testSuite) TestBigIntPK(c *C) {
tk.MustExec("insert into t values(1, 1, 1), (9223372036854775807, 2, 2)")
tk.MustQuery("select * from t use index(idx) order by a").Check(testkit.Rows("1 1 1", "9223372036854775807 2 2"))
}

func (s *testSuite) TestUniqueKeyNullValueSelect(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.MustExec("drop table if exists t")
// test null in unique-key
tk.MustExec("create table t (id int default null, c varchar(20), unique id (id));")
tk.MustExec("insert t (c) values ('a'), ('b'), ('c');")
res := tk.MustQuery("select * from t where id is null;")
res.Check(testkit.Rows("<nil> a", "<nil> b", "<nil> c"))

// test null in mul unique-key
tk.MustExec("drop table t")
tk.MustExec("create table t (id int default null, b int default 1, c varchar(20), unique id_c(id, b));")
tk.MustExec("insert t (c) values ('a'), ('b'), ('c');")
res = tk.MustQuery("select * from t where id is null and b = 1;")
res.Check(testkit.Rows("<nil> 1 a", "<nil> 1 b", "<nil> 1 c"))

tk.MustExec("drop table t")
// test null in non-unique-key
tk.MustExec("create table t (id int default null, c varchar(20), key id (id));")
tk.MustExec("insert t (c) values ('a'), ('b'), ('c');")
res = tk.MustQuery("select * from t where id is null;")
res.Check(testkit.Rows("<nil> a", "<nil> b", "<nil> c"))
}
4 changes: 4 additions & 0 deletions util/ranger/types.go
Expand Up @@ -94,6 +94,10 @@ func (ran *NewRange) IsPoint(sc *stmtctx.StatementContext) bool {
if cmp != 0 {
return false
}

if a.IsNull() {
return false
}
}
return !ran.LowExclude && !ran.HighExclude
}
Expand Down

0 comments on commit c3e2963

Please sign in to comment.