Skip to content

Commit

Permalink
sql: refactor setval() to be a schema change for cached sequences
Browse files Browse the repository at this point in the history
Sequences with cached values invalidate values when new descriptor
versions are seen. Previously, setval() was not a schema change, so
it did not invalidate the cache when called. This change ensures that
setval() is a schema change for cached sequences so that cached
values get invalidated when setval() is called.

Release note: None
  • Loading branch information
jayshrivastava committed Feb 2, 2021
1 parent 46f7b9d commit 110cb70
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 4 deletions.
18 changes: 18 additions & 0 deletions pkg/sql/logictest/testdata/logic_test/sequences
Expand Up @@ -1327,5 +1327,23 @@ SELECT last_value FROM cache_test
----
70

# Verify that setval() will invalidate the cache.

query I
SELECT setval('cache_test', 81, false)
----
81

# 10 new values (81,82,...,90) are cached.
query I
SELECT nextval('cache_test')
----
81

query I
SELECT last_value FROM cache_test
----
90

statement ok
DROP SEQUENCE cache_test
24 changes: 20 additions & 4 deletions pkg/sql/sequence.go
Expand Up @@ -211,10 +211,26 @@ func (p *planner) SetSequenceValue(
return err
}

// TODO(vilterp): not supposed to mix usage of Inc and Put on a key,
// according to comments on Inc operation. Switch to Inc if `desired-current`
// overflows correctly.
return p.txn.Put(ctx, seqValueKey, newVal)
if descriptor.GetSequenceOpts().CacheSize <= 1 {
// TODO(vilterp): not supposed to mix usage of Inc and Put on a key,
// according to comments on Inc operation. Switch to Inc if `desired-current`
// overflows correctly.
return p.txn.Put(ctx, seqValueKey, newVal)
}

// If there are cached values, changing the value of the sequence should invalidate the cache.
// For simplicity, the cache invalidates implicitly when it sees new descriptor versions. Thus,
// a schema change is triggered here to make sure the cache gets invalidated.
mutableDescriptor, err := resolver.ResolveMutableExistingTableObject(ctx, p, seqName, true, tree.ResolveRequireSequenceDesc)

if err := p.txn.Put(ctx, seqValueKey, newVal); err != nil {
return err
}

if err != nil {
return err
}
return p.writeSchemaChange(ctx, mutableDescriptor, descpb.InvalidMutationID, fmt.Sprintf("setval('%s')", seqName.String()))
}

// MakeSequenceKeyVal returns the key and value of a sequence being set
Expand Down

0 comments on commit 110cb70

Please sign in to comment.