-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
show_ranges.go
85 lines (79 loc) · 2.61 KB
/
show_ranges.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// Copyright 2019 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package delegate
import (
"encoding/hex"
"fmt"
"github.com/cockroachdb/cockroach/pkg/sql/lex"
"github.com/cockroachdb/cockroach/pkg/sql/opt/cat"
"github.com/cockroachdb/cockroach/pkg/sql/privilege"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
)
// delegateShowRanges implements the SHOW RANGES statement:
// SHOW RANGES FROM TABLE t
// SHOW RANGES FROM INDEX t@idx
// SHOW RANGES FROM DATABASE db
//
// These statements show the ranges corresponding to the given table or index,
// along with the list of replicas and the lease holder.
func (d *delegator) delegateShowRanges(n *tree.ShowRanges) (tree.Statement, error) {
if n.DatabaseName != "" {
const dbQuery = `
SELECT
table_name,
CASE
WHEN crdb_internal.pretty_key(r.start_key, 2) = '' THEN NULL
ELSE crdb_internal.pretty_key(r.start_key, 2)
END AS start_key,
CASE
WHEN crdb_internal.pretty_key(r.end_key, 2) = '' THEN NULL
ELSE crdb_internal.pretty_key(r.end_key, 2)
END AS end_key,
range_id,
range_size / 1000000 as range_size_mb,
lease_holder,
replica_localities[1] as lease_holder_locality,
replicas,
replica_localities
FROM %[1]s.crdb_internal.ranges AS r
WHERE database_name=%[2]s
ORDER BY table_name, r.start_key
`
return parse(fmt.Sprintf(dbQuery, n.DatabaseName, lex.EscapeSQLString(n.DatabaseName)))
}
idx, _, err := cat.ResolveTableIndex(
d.ctx, d.catalog, cat.Flags{AvoidDescriptorCaches: true}, &n.TableOrIndex,
)
if err != nil {
return nil, err
}
if err := d.catalog.CheckPrivilege(d.ctx, idx.Table(), privilege.SELECT); err != nil {
return nil, err
}
span := idx.Span()
startKey := hex.EncodeToString([]byte(span.Key))
endKey := hex.EncodeToString([]byte(span.EndKey))
return parse(fmt.Sprintf(`
SELECT
CASE WHEN r.start_key <= x'%s' THEN NULL ELSE crdb_internal.pretty_key(r.start_key, 2) END AS start_key,
CASE WHEN r.end_key >= x'%s' THEN NULL ELSE crdb_internal.pretty_key(r.end_key, 2) END AS end_key,
range_id,
range_size / 1000000 as range_size_mb,
lease_holder,
replica_localities[1] as lease_holder_locality,
replicas,
replica_localities
FROM crdb_internal.ranges AS r
WHERE (r.start_key < x'%s')
AND (r.end_key > x'%s') ORDER BY r.start_key
`,
startKey, endKey, endKey, startKey,
))
}