Refactor table index (#11131)

* convert tableIndex to use the new pattern

* make `indexFromString` available for oss as well

* refactor `indexUpdateMaxTxn`
This commit is contained in:
Dhia Ayachi 2021-09-23 11:06:23 -04:00 committed by GitHub
parent c87d57bfeb
commit ebe333b947
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 42 additions and 12 deletions

View File

@ -2,6 +2,7 @@ package state
import (
"fmt"
"strings"
"github.com/hashicorp/go-memdb"
)
@ -75,11 +76,37 @@ func indexTableSchema() *memdb.TableSchema {
Name: indexID,
AllowMissing: false,
Unique: true,
Indexer: &memdb.StringFieldIndex{
Field: "Key",
Lowercase: true,
Indexer: indexerSingle{
readIndex: indexFromString,
writeIndex: indexNameFromIndexEntry,
},
},
},
}
}
func indexNameFromIndexEntry(raw interface{}) ([]byte, error) {
p, ok := raw.(*IndexEntry)
if !ok {
return nil, fmt.Errorf("unexpected type %T for IndexEntry index", raw)
}
if p.Key == "" {
return nil, errMissingValueForIndex
}
var b indexBuilder
b.String(strings.ToLower(p.Key))
return b.Bytes(), nil
}
func indexFromString(raw interface{}) ([]byte, error) {
q, ok := raw.(string)
if !ok {
return nil, fmt.Errorf("unexpected type %T for string prefix query", raw)
}
var b indexBuilder
b.String(strings.ToLower(q))
return b.Bytes(), nil
}

View File

@ -295,17 +295,20 @@ func indexUpdateMaxTxn(tx WriteTxn, idx uint64, table string) error {
return fmt.Errorf("failed to retrieve existing index: %s", err)
}
// Always take the first update, otherwise do the > check.
if ti == nil {
if err := tx.Insert(tableIndex, &IndexEntry{table, idx}); err != nil {
return fmt.Errorf("failed updating index %s", err)
// if this is an update check the idx
if ti != nil {
cur, ok := ti.(*IndexEntry)
if !ok {
return fmt.Errorf("failed updating index %T need to be `*IndexEntry`", ti)
}
// Stored index is newer, don't insert the index
if idx <= cur.Value {
return nil
}
return nil
}
if cur, ok := ti.(*IndexEntry); ok && idx > cur.Value {
if err := tx.Insert(tableIndex, &IndexEntry{table, idx}); err != nil {
return fmt.Errorf("failed updating index %s", err)
}
if err := tx.Insert(tableIndex, &IndexEntry{table, idx}); err != nil {
return fmt.Errorf("failed updating index %s", err)
}
return nil
}