table: add ColumnOffset to get column offset with name

This commit is contained in:
siddontang
2015-09-22 14:39:30 +08:00
parent 15c5ea5a0d
commit 8f7fa8c2d8
3 changed files with 57 additions and 0 deletions

View File

@ -107,6 +107,9 @@ type Table interface {
// LockRow locks a row.
// If update is true, set row lock key to current txn.
LockRow(ctx context.Context, h int64, update bool) error
// ColumnOffset gets the column offset in whole columns with column name.
ColumnOffset(name string) (int, error)
}
// TableFromMeta builds a table.Table from *model.TableInfo.

View File

@ -558,6 +558,38 @@ func (t *Table) AllocAutoID() (int64, error) {
return t.alloc.Alloc(t.ID)
}
// ColumnOffset implements table.Table ColumnOffset interface.
func (t *Table) ColumnOffset(name string) (int, error) {
seps := strings.Split(name, ".")
var (
table string
col string
)
// Now we only support column or table.column qualified name.
// TODO: support db.table.column later.
if len(seps) == 1 {
col = name
} else if len(seps) == 2 {
table = seps[0]
col = seps[1]
} else {
return -1, errors.Errorf("invalid column format %s", name)
}
if len(table) > 0 && table != t.Name.O {
return -1, errors.Errorf("column table %s is not equal %s", table, t.Name.O)
}
for _, c := range t.Columns {
if strings.EqualFold(col, c.Name.L) {
return c.Offset, nil
}
}
return -1, errors.Errorf("unknown column %s", name)
}
func init() {
table.TableFromMeta = TableFromMeta
}

View File

@ -102,6 +102,28 @@ func (ts *testSuite) TestBasic(c *C) {
c.Assert(cnt, Equals, 0)
_, err = ts.se.Execute("drop table test.t")
c.Assert(err, IsNil)
offsetTbl := []struct {
Name string
Offset int
}{
{"a", 0},
{"b", 1},
{"c", -1},
{"t.a", 0},
{"t.c", -1},
{"t1.c", -1},
{"test.test.t.c", -1},
}
for _, t := range offsetTbl {
index, err := tb.ColumnOffset(t.Name)
if t.Offset == -1 {
c.Assert(err, NotNil)
} else {
c.Assert(index, Equals, t.Offset)
}
}
}
func countEntriesWithPrefix(ctx context.Context, prefix string) (int, error) {