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 d88d9e71c2
commit 5904e4ac79
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 ( import (
"fmt" "fmt"
"strings"
"github.com/hashicorp/go-memdb" "github.com/hashicorp/go-memdb"
) )
@ -75,11 +76,37 @@ func indexTableSchema() *memdb.TableSchema {
Name: indexID, Name: indexID,
AllowMissing: false, AllowMissing: false,
Unique: true, Unique: true,
Indexer: &memdb.StringFieldIndex{ Indexer: indexerSingle{
Field: "Key", readIndex: indexFromString,
Lowercase: true, 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) return fmt.Errorf("failed to retrieve existing index: %s", err)
} }
// Always take the first update, otherwise do the > check. // if this is an update check the idx
if ti == nil { if ti != nil {
if err := tx.Insert(tableIndex, &IndexEntry{table, idx}); err != nil { cur, ok := ti.(*IndexEntry)
return fmt.Errorf("failed updating index %s", err) 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 { if err := tx.Insert(tableIndex, &IndexEntry{table, idx}); err != nil {
return fmt.Errorf("failed updating index %s", err) return fmt.Errorf("failed updating index %s", err)
}
} }
return nil return nil
} }