mirror of https://github.com/status-im/consul.git
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:
parent
d88d9e71c2
commit
5904e4ac79
|
@ -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
|
||||
}
|
||||
|
|
|
@ -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
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue