Skip to content

Commit

Permalink
statedb: Add checks to see if table is registered
Browse files Browse the repository at this point in the history
If a user forgets to register a table with the DB instance and then
proceeds to use it, the tablePos defaults to 0. This causes writes to
the table to end up in the wrong table.

This commit defaults the table pos to -1 to cause deliberate panics if
the code ever attempts to use the index of a unregistered table. This
commit also adds checks on the read and write transactions to detect
when an unregistered table is being used and throw a clear error.

Signed-off-by: Dylan Reimerink <[email protected]>
  • Loading branch information
dylandreimerink authored and joamaki committed Aug 2, 2024
1 parent dc95f9b commit 475849f
Show file tree
Hide file tree
Showing 4 changed files with 11 additions and 0 deletions.
3 changes: 3 additions & 0 deletions db.go
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,9 @@ func (h Handle) WriteTxn(table TableMeta, tables ...TableMeta) WriteTxn {
smus := internal.SortableMutexes{}
for _, table := range allTables {
smus = append(smus, table.sortableMutex())
if table.tablePos() < 0 {
panic(tableError(table.Name(), ErrTableNotRegistered))
}
}
lockAt := time.Now()
smus.Lock()
Expand Down
4 changes: 4 additions & 0 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ var (
// that share the same table name.
ErrDuplicateTable = errors.New("table already exists")

// ErrTableNotRegistered indicates that a user tries to write to a table that has not been
// registered with this StateDB instance.
ErrTableNotRegistered = errors.New("table not registered")

// ErrPrimaryIndexNotUnique indicates that the primary index for the table is not marked unique.
ErrPrimaryIndexNotUnique = errors.New("primary index not unique")

Expand Down
1 change: 1 addition & 0 deletions table.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ func NewTable[Obj any](
primaryIndexer: primaryIndexer,
secondaryAnyIndexers: make(map[string]anyIndexer, len(secondaryIndexers)),
indexPositions: make(map[string]int),
pos: -1,
}

table.indexPositions[primaryIndexer.indexName()] = PrimaryIndexPos
Expand Down
3 changes: 3 additions & 0 deletions txn.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ func (txn *txn) getRevision(meta TableMeta) Revision {
// indexReadTxn returns a transaction to read from the specific index.
// If the table or index is not found this returns nil & error.
func (txn *txn) indexReadTxn(meta TableMeta, indexPos int) (indexReadTxn, error) {
if meta.tablePos() < 0 {
return indexReadTxn{}, tableError(meta.Name(), ErrTableNotRegistered)
}
if txn.modifiedTables != nil {
entry := txn.modifiedTables[meta.tablePos()]
if entry != nil {
Expand Down

0 comments on commit 475849f

Please sign in to comment.