本文整理匯總了Golang中github.com/cockroachdb/cockroach/keys.MakeTablePrefix函數的典型用法代碼示例。如果您正苦於以下問題:Golang MakeTablePrefix函數的具體用法?Golang MakeTablePrefix怎麽用?Golang MakeTablePrefix使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了MakeTablePrefix函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: TestObjectIDForKey
func TestObjectIDForKey(t *testing.T) {
defer leaktest.AfterTest(t)
testCases := []struct {
key roachpb.RKey
success bool
id uint32
}{
// Before the structured span.
{roachpb.RKeyMin, false, 0},
// Boundaries of structured span.
{roachpb.RKeyMax, false, 0},
// Valid, even if there are things after the ID.
{keys.MakeKey(keys.MakeTablePrefix(42), roachpb.RKey("\xff")), true, 42},
{keys.MakeTablePrefix(0), true, 0},
{keys.MakeTablePrefix(999), true, 999},
}
for tcNum, tc := range testCases {
id, success := config.ObjectIDForKey(tc.key)
if success != tc.success {
t.Errorf("#%d: expected success=%t", tcNum, tc.success)
continue
}
if id != tc.id {
t.Errorf("#%d: expected id=%d, got %d", tcNum, tc.id, id)
}
}
}
示例2: TestStoreZoneUpdateAndRangeSplit
// TestStoreZoneUpdateAndRangeSplit verifies that modifying the zone
// configuration changes range max bytes and Range.maybeSplit() takes
// max bytes into account when deciding whether to enqueue a range for
// splitting. It further verifies that the range is in fact split on
// exceeding zone's RangeMaxBytes.
func TestStoreZoneUpdateAndRangeSplit(t *testing.T) {
defer leaktest.AfterTest(t)
t.Skip("#3762")
store, stopper := createTestStore(t)
config.TestingSetupZoneConfigHook(stopper)
defer stopper.Stop()
maxBytes := int64(1 << 16)
// Set max bytes.
descID := uint32(keys.MaxReservedDescID + 1)
config.TestingSetZoneConfig(descID, &config.ZoneConfig{RangeMaxBytes: maxBytes})
// Trigger gossip callback.
if err := store.Gossip().AddInfoProto(gossip.KeySystemConfig, &config.SystemConfig{}, 0); err != nil {
t.Fatal(err)
}
// Wait for the range to be split along table boundaries.
originalRange := store.LookupReplica(roachpb.RKey(keys.UserTableDataMin), nil)
var rng *storage.Replica
if err := util.IsTrueWithin(func() bool {
rng = store.LookupReplica(keys.MakeTablePrefix(descID), nil)
return rng.RangeID != originalRange.RangeID
}, splitTimeout); err != nil {
t.Fatalf("failed to notice range max bytes update: %s", err)
}
// Check range's max bytes settings.
if rng.GetMaxBytes() != maxBytes {
t.Fatalf("range max bytes mismatch, got: %d, expected: %d", rng.GetMaxBytes(), maxBytes)
}
// Make sure the second range goes to the end.
if !roachpb.RKeyMax.Equal(rng.Desc().EndKey) {
t.Fatalf("second range has split: %+v", rng.Desc())
}
// Look in the range after prefix we're writing to.
fillRange(store, rng.RangeID, keys.MakeTablePrefix(descID), maxBytes, t)
// Verify that the range is in fact split (give it a few seconds for very
// slow test machines).
var newRng *storage.Replica
util.SucceedsWithin(t, splitTimeout, func() error {
newRng = store.LookupReplica(keys.MakeTablePrefix(descID+1), nil)
if newRng.RangeID == rng.RangeID {
return util.Errorf("range has not yet split")
}
return nil
})
// Make sure the new range goes to the end.
if !roachpb.RKeyMax.Equal(newRng.Desc().EndKey) {
t.Fatalf("second range has split: %+v", rng.Desc())
}
}
示例3: TestStoreZoneUpdateAndRangeSplit
// TestStoreZoneUpdateAndRangeSplit verifies that modifying the zone
// configuration changes range max bytes and Range.maybeSplit() takes
// max bytes into account when deciding whether to enqueue a range for
// splitting. It further verifies that the range is in fact split on
// exceeding zone's RangeMaxBytes.
func TestStoreZoneUpdateAndRangeSplit(t *testing.T) {
defer leaktest.AfterTest(t)
store, stopper := createTestStore(t)
config.TestingSetupZoneConfigHook(stopper)
defer stopper.Stop()
maxBytes := int64(1 << 16)
// Set max bytes.
config.TestingSetZoneConfig(1000, &config.ZoneConfig{RangeMaxBytes: maxBytes})
// Trigger gossip callback.
if err := store.Gossip().AddInfoProto(gossip.KeySystemConfig, &config.SystemConfig{}, 0); err != nil {
t.Fatal(err)
}
// Wait for the range to be split along table boundaries.
originalRange := store.LookupReplica(roachpb.RKeyMin, nil)
var rng *storage.Replica
if err := util.IsTrueWithin(func() bool {
rng = store.LookupReplica(keys.MakeTablePrefix(1000), nil)
return rng.Desc().RangeID != originalRange.Desc().RangeID
}, 50*time.Millisecond); err != nil {
t.Fatalf("failed to notice range max bytes update: %s", err)
}
// Check range's max bytes settings.
if rng.GetMaxBytes() != maxBytes {
t.Fatalf("range max bytes mismatch, got: %d, expected: %d", rng.GetMaxBytes(), maxBytes)
}
// Make sure the second range goes to the end.
if !roachpb.RKeyMax.Equal(rng.Desc().EndKey) {
t.Fatalf("second range has split: %+v", rng.Desc())
}
// Look in the range after prefix we're writing to.
fillRange(store, rng.Desc().RangeID, keys.MakeTablePrefix(1000), maxBytes, t)
// Verify that the range is in fact split (give it a second for very slow test machines).
var newRng *storage.Replica
if err := util.IsTrueWithin(func() bool {
newRng = store.LookupReplica(keys.MakeTablePrefix(2000), nil)
return newRng.Desc().RangeID != rng.Desc().RangeID
}, time.Second); err != nil {
t.Errorf("expected range to split within 1s")
}
// Make sure the new range goes to the end.
if !roachpb.RKeyMax.Equal(newRng.Desc().EndKey) {
t.Fatalf("second range has split: %+v", rng.Desc())
}
}
示例4: TestStoreZoneUpdateAndRangeSplit
// TestStoreZoneUpdateAndRangeSplit verifies that modifying the zone
// configuration changes range max bytes and Range.maybeSplit() takes
// max bytes into account when deciding whether to enqueue a range for
// splitting. It further verifies that the range is in fact split on
// exceeding zone's RangeMaxBytes.
func TestStoreZoneUpdateAndRangeSplit(t *testing.T) {
defer leaktest.AfterTest(t)()
store, stopper, _ := createTestStore(t)
config.TestingSetupZoneConfigHook(stopper)
defer stopper.Stop()
maxBytes := int64(1 << 16)
// Set max bytes.
descID := uint32(keys.MaxReservedDescID + 1)
config.TestingSetZoneConfig(descID, &config.ZoneConfig{RangeMaxBytes: maxBytes})
// Trigger gossip callback.
if err := store.Gossip().AddInfoProto(gossip.KeySystemConfig, &config.SystemConfig{}, 0); err != nil {
t.Fatal(err)
}
tableBoundary := keys.MakeTablePrefix(descID)
{
var rng *storage.Replica
// Wait for the range to be split along table boundaries.
expectedRSpan := roachpb.RSpan{Key: roachpb.RKey(tableBoundary), EndKey: roachpb.RKeyMax}
util.SucceedsSoon(t, func() error {
rng = store.LookupReplica(tableBoundary, nil)
if actualRSpan := rng.Desc().RSpan(); !actualRSpan.Equal(expectedRSpan) {
return util.Errorf("expected range %s to span %s", rng, expectedRSpan)
}
return nil
})
// Check range's max bytes settings.
if actualMaxBytes := rng.GetMaxBytes(); actualMaxBytes != maxBytes {
t.Fatalf("range %s max bytes mismatch, got: %d, expected: %d", rng, actualMaxBytes, maxBytes)
}
// Look in the range after prefix we're writing to.
fillRange(store, rng.RangeID, tableBoundary, maxBytes, t)
}
// Verify that the range is in fact split.
util.SucceedsSoon(t, func() error {
rng := store.LookupReplica(keys.MakeTablePrefix(descID+1), nil)
rngDesc := rng.Desc()
rngStart, rngEnd := rngDesc.StartKey, rngDesc.EndKey
if rngStart.Equal(tableBoundary) || !rngEnd.Equal(roachpb.RKeyMax) {
return util.Errorf("range %s has not yet split", rng)
}
return nil
})
}
示例5: GetLargestObjectID
// GetLargestObjectID returns the largest object ID found in the config.
// This could be either a table or a database.
func (s *SystemConfig) GetLargestObjectID() (uint32, error) {
testingLock.Lock()
hook := TestingLargestIDHook
testingLock.Unlock()
if hook != nil {
return hook(), nil
}
if len(s.Values) == 0 {
return 0, fmt.Errorf("empty system values in config")
}
// Search for the first key after the descriptor table.
// We can't use GetValue as we don't mind if there is nothing after
// the descriptor table.
key := proto.Key(keys.MakeTablePrefix(keys.DescriptorTableID + 1))
index := sort.Search(len(s.Values), func(i int) bool {
return !s.Values[i].Key.Less(key)
})
if index == 0 {
return 0, fmt.Errorf("descriptor table not found in system config of %d values", len(s.Values))
}
// This is the last key of the descriptor table.
key = s.Values[index-1].Key
// Extract object ID from key.
// TODO(marc): move sql/keys.go to keys (or similar) and use a DecodeDescMetadataKey.
// We should also check proper encoding.
descriptorPrefix := keys.MakeTablePrefix(keys.DescriptorTableID)
remaining := bytes.TrimPrefix(key, descriptorPrefix)
// TrimPrefix returns the bytes unchanged if the prefix does not match.
if len(remaining) == len(key) {
return 0, fmt.Errorf("descriptor table not found in system config of %d values", len(s.Values))
}
// DescriptorTable.PrimaryIndex.ID
remaining, _, err := encoding.DecodeUvarint(remaining)
if err != nil {
return 0, err
}
// descID
_, id, err := encoding.DecodeUvarint(remaining)
if err != nil {
return 0, err
}
return uint32(id), nil
}
示例6: sqlKV
func sqlKV(tableID uint32, indexID, descriptorID uint64) roachpb.KeyValue {
k := keys.MakeTablePrefix(tableID)
k = encoding.EncodeUvarintAscending(k, indexID)
k = encoding.EncodeUvarintAscending(k, descriptorID)
k = encoding.EncodeUvarintAscending(k, 12345) // Column ID, but could be anything.
return kv(k, nil)
}
示例7: RefreshLeases
// RefreshLeases starts a goroutine that refreshes the lease manager
// leases for tables received in the latest system configuration via gossip.
func (m *LeaseManager) RefreshLeases(s *stop.Stopper, db *client.DB, gossip *gossip.Gossip) {
s.RunWorker(func() {
descKeyPrefix := keys.MakeTablePrefix(uint32(sqlbase.DescriptorTable.ID))
gossipUpdateC := gossip.RegisterSystemConfigChannel()
for {
select {
case <-gossipUpdateC:
cfg, _ := gossip.GetSystemConfig()
if m.testingKnobs.GossipUpdateEvent != nil {
m.testingKnobs.GossipUpdateEvent(cfg)
}
// Read all tables and their versions
if log.V(2) {
log.Info("received a new config; will refresh leases")
}
// Loop through the configuration to find all the tables.
for _, kv := range cfg.Values {
if !bytes.HasPrefix(kv.Key, descKeyPrefix) {
continue
}
// Attempt to unmarshal config into a table/database descriptor.
var descriptor sqlbase.Descriptor
if err := kv.Value.GetProto(&descriptor); err != nil {
log.Warningf("%s: unable to unmarshal descriptor %v", kv.Key, kv.Value)
continue
}
switch union := descriptor.Union.(type) {
case *sqlbase.Descriptor_Table:
table := union.Table
if err := table.Validate(); err != nil {
log.Errorf("%s: received invalid table descriptor: %v", kv.Key, table)
continue
}
if log.V(2) {
log.Infof("%s: refreshing lease table: %d (%s), version: %d",
kv.Key, table.ID, table.Name, table.Version)
}
// Try to refresh the table lease to one >= this version.
if t := m.findTableState(table.ID, false /* create */, nil); t != nil {
if err := t.purgeOldLeases(
db, table.Deleted(), table.Version, m.LeaseStore); err != nil {
log.Warningf("error purging leases for table %d(%s): %s",
table.ID, table.Name, err)
}
}
case *sqlbase.Descriptor_Database:
// Ignore.
}
}
if m.testingKnobs.TestingLeasesRefreshedEvent != nil {
m.testingKnobs.TestingLeasesRefreshedEvent(cfg)
}
case <-s.ShouldStop():
return
}
}
})
}
示例8: Truncate
// Truncate deletes all rows from a table.
// Privileges: DROP on table.
// Notes: postgres requires TRUNCATE.
// mysql requires DROP (for mysql >= 5.1.16, DELETE before that).
func (p *planner) Truncate(n *parser.Truncate) (planNode, *roachpb.Error) {
b := client.Batch{}
for _, tableQualifiedName := range n.Tables {
tableDesc, pErr := p.getTableLease(tableQualifiedName)
if pErr != nil {
return nil, pErr
}
if err := p.checkPrivilege(&tableDesc, privilege.DROP); err != nil {
return nil, roachpb.NewError(err)
}
tablePrefix := keys.MakeTablePrefix(uint32(tableDesc.ID))
// Delete rows and indexes starting with the table's prefix.
tableStartKey := roachpb.Key(tablePrefix)
tableEndKey := tableStartKey.PrefixEnd()
if log.V(2) {
log.Infof("DelRange %s - %s", tableStartKey, tableEndKey)
}
b.DelRange(tableStartKey, tableEndKey, false)
}
if pErr := p.txn.Run(&b); pErr != nil {
return nil, pErr
}
return &emptyNode{}, nil
}
示例9: monkey
func (z *zeroSum) monkey(tableID uint32, d time.Duration) {
r := newRand()
zipf := z.accountDistribution(r)
for {
time.Sleep(time.Duration(rand.Float64() * float64(d)))
key := keys.MakeTablePrefix(tableID)
key = encoding.EncodeVarintAscending(key, int64(zipf.Uint64()))
key = keys.MakeRowSentinelKey(key)
switch r.Intn(2) {
case 0:
if err := z.split(z.randNode(r.Intn), key); err != nil {
if strings.Contains(err.Error(), "range is already split at key") ||
strings.Contains(err.Error(), "conflict updating range descriptors") {
continue
}
z.maybeLogError(err)
} else {
atomic.AddUint64(&z.stats.splits, 1)
}
case 1:
if transferred, err := z.transferLease(z.randNode(r.Intn), r, key); err != nil {
z.maybeLogError(err)
} else if transferred {
atomic.AddUint64(&z.stats.transfers, 1)
}
}
}
}
示例10: TestStoreRangeSplitWithMaxBytesUpdate
// TestStoreRangeSplitWithMaxBytesUpdate tests a scenario where a new
// zone config that updates the max bytes is set and triggers a range
// split.
func TestStoreRangeSplitWithMaxBytesUpdate(t *testing.T) {
defer leaktest.AfterTest(t)
store, stopper := createTestStore(t)
config.TestingSetupZoneConfigHook(stopper)
defer stopper.Stop()
origRng := store.LookupReplica(roachpb.RKeyMin, nil)
// Set max bytes.
maxBytes := int64(1 << 16)
config.TestingSetZoneConfig(1000, &config.ZoneConfig{RangeMaxBytes: maxBytes})
// Trigger gossip callback.
if err := store.Gossip().AddInfoProto(gossip.KeySystemConfig, &config.SystemConfig{}, 0); err != nil {
t.Fatal(err)
}
// Verify that the range is split and the new range has the correct max bytes.
util.SucceedsWithin(t, time.Second, func() error {
newRng := store.LookupReplica(keys.MakeTablePrefix(1000), nil)
if newRng.Desc().RangeID == origRng.Desc().RangeID {
return util.Errorf("expected new range created by split")
}
if newRng.GetMaxBytes() != maxBytes {
return util.Errorf("expected %d max bytes for the new range, but got %d",
maxBytes, newRng.GetMaxBytes())
}
return nil
})
}
示例11: MakeZoneKey
// MakeZoneKey returns the key for 'id's entry in the system.zones table.
func MakeZoneKey(id ID) roachpb.Key {
k := keys.MakeTablePrefix(uint32(ZonesTable.ID))
k = encoding.EncodeUvarint(k, uint64(ZonesTable.PrimaryIndex.ID))
k = encoding.EncodeUvarint(k, uint64(id))
k = encoding.EncodeUvarint(k, uint64(ZonesTable.Columns[1].ID))
return k
}
示例12: MakeDescMetadataKey
// MakeDescMetadataKey returns the key for the descriptor.
func MakeDescMetadataKey(descID ID) roachpb.Key {
k := keys.MakeTablePrefix(uint32(DescriptorTable.ID))
k = encoding.EncodeUvarint(k, uint64(DescriptorTable.PrimaryIndex.ID))
k = encoding.EncodeUvarint(k, uint64(descID))
k = encoding.EncodeUvarint(k, uint64(DescriptorTable.Columns[1].ID))
return k
}
示例13: Truncate
// Truncate deletes all rows from a table.
// Privileges: DROP on table.
// Notes: postgres requires TRUNCATE.
// mysql requires DROP (for mysql >= 5.1.16, DELETE before that).
func (p *planner) Truncate(n *parser.Truncate) (planNode, error) {
b := client.Batch{}
for _, tableQualifiedName := range n.Tables {
tableDesc, err := p.getTableDesc(tableQualifiedName)
if err != nil {
return nil, err
}
if err := p.checkPrivilege(tableDesc, privilege.DROP); err != nil {
return nil, err
}
tablePrefix := keys.MakeTablePrefix(uint32(tableDesc.ID))
// Delete rows and indexes starting with the table's prefix.
tableStartKey := proto.Key(tablePrefix)
tableEndKey := tableStartKey.PrefixEnd()
if log.V(2) {
log.Infof("DelRange %s - %s", prettyKey(tableStartKey, 0), prettyKey(tableEndKey, 0))
}
b.DelRange(tableStartKey, tableEndKey)
}
if err := p.txn.Run(&b); err != nil {
return nil, err
}
return &valuesNode{}, nil
}
示例14: ComputeSplitKeys
// ComputeSplitKeys takes a start and end key and returns an array of keys
// at which to split the span [start, end).
// The only required splits are at each user table prefix.
func (s SystemConfig) ComputeSplitKeys(startKey, endKey roachpb.RKey) []roachpb.RKey {
testingLock.Lock()
tableSplitsDisabled := testingDisableTableSplits
testingLock.Unlock()
if tableSplitsDisabled {
return nil
}
tableStart := roachpb.RKey(keys.UserTableDataMin)
if !tableStart.Less(endKey) {
// This range is before the user tables span: no required splits.
return nil
}
startID, ok := ObjectIDForKey(startKey)
if !ok || startID <= keys.MaxReservedDescID {
// The start key is either:
// - not part of the structured data span
// - part of the system span
// In either case, start looking for splits at the first ID usable
// by the user data span.
startID = keys.MaxReservedDescID + 1
} else {
// The start key is either already a split key, or after the split
// key for its ID. We can skip straight to the next one.
startID++
}
// Find the largest object ID.
// We can't keep splitting until we reach endKey as it could be roachpb.KeyMax.
endID, err := s.GetLargestObjectID()
if err != nil {
log.Errorf("unable to determine largest object ID from system config: %s", err)
return nil
}
// Build key prefixes for sequential table IDs until we reach endKey.
var splitKeys []roachpb.RKey
var key roachpb.RKey
// endID could be smaller than startID if we don't have user tables.
for id := startID; id <= endID; id++ {
key = keys.MakeTablePrefix(id)
// Skip if the range starts on a split key.
if !startKey.Less(key) {
continue
}
// Handle the case where EndKey is already a table prefix.
if !key.Less(endKey) {
break
}
splitKeys = append(splitKeys, key)
}
return splitKeys
}
示例15: RefreshLeases
// RefreshLeases starts a goroutine that refreshes the lease manager
// leases for tables received in the latest system configuration via gossip.
func (m *LeaseManager) RefreshLeases(s *stop.Stopper, db *client.DB, gossip *gossip.Gossip) {
s.RunWorker(func() {
descKeyPrefix := keys.MakeTablePrefix(uint32(DescriptorTable.ID))
gossip.RegisterSystemConfigCallback(m.updateSystemConfig)
for {
select {
case <-m.newConfig:
// Read all tables and their versions
cfg := m.getSystemConfig()
if log.V(2) {
log.Info("received a new config %v", cfg)
}
// Loop through the configuration to find all the tables.
for _, kv := range cfg.Values {
if kv.Value.Tag != roachpb.ValueType_BYTES {
continue
}
if !bytes.HasPrefix(kv.Key, descKeyPrefix) {
continue
}
// Attempt to unmarshal config into a table/database descriptor.
var descriptor Descriptor
if err := kv.Value.GetProto(&descriptor); err != nil {
log.Warningf("unable to unmarshal descriptor %v", kv.Value)
continue
}
switch union := descriptor.Union.(type) {
case *Descriptor_Table:
table := union.Table
if err := table.Validate(); err != nil {
log.Errorf("received invalid table descriptor: %v", table)
continue
}
if log.V(2) {
log.Infof("refreshing lease table: %d, version: %d", table.ID, table.Version)
}
// Try to refresh the table lease to one >= this version.
if err := m.refreshLease(db, table.ID, table.Version); err != nil {
log.Warning(err)
}
case *Descriptor_Database:
// Ignore.
}
}
case <-s.ShouldStop():
return
}
}
})
}