forked from pingcap/tidb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanalyze.go
245 lines (223 loc) · 6.58 KB
/
analyze.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
// Copyright 2017 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
package executor
import (
"math/rand"
"strconv"
"time"
"github.com/juju/errors"
"github.com/pingcap/tidb/ast"
"github.com/pingcap/tidb/context"
"github.com/pingcap/tidb/expression"
"github.com/pingcap/tidb/model"
"github.com/pingcap/tidb/sessionctx"
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/sessionctx/varsutil"
"github.com/pingcap/tidb/statistics"
"github.com/pingcap/tidb/util/types"
)
var _ Executor = &AnalyzeExec{}
// AnalyzeExec represents Analyze executor.
type AnalyzeExec struct {
ctx context.Context
tasks []*analyzeTask
}
const (
maxSampleCount = 10000
maxSketchSize = 1000
defaultBucketCount = 256
)
// Schema implements the Executor Schema interface.
func (e *AnalyzeExec) Schema() *expression.Schema {
return expression.NewSchema()
}
// Open implements the Executor Open interface.
func (e *AnalyzeExec) Open() error {
for _, task := range e.tasks {
err := task.src.Open()
if err != nil {
return errors.Trace(err)
}
}
return nil
}
// Close implements the Executor Close interface.
func (e *AnalyzeExec) Close() error {
for _, task := range e.tasks {
err := task.src.Close()
if err != nil {
return errors.Trace(err)
}
}
return nil
}
// Next implements the Executor Next interface.
func (e *AnalyzeExec) Next() (*Row, error) {
concurrency, err := getBuildStatsConcurrency(e.ctx)
if err != nil {
return nil, errors.Trace(err)
}
taskCh := make(chan *analyzeTask, len(e.tasks))
resultCh := make(chan analyzeResult, len(e.tasks))
for i := 0; i < concurrency; i++ {
go e.analyzeWorker(taskCh, resultCh)
}
for _, task := range e.tasks {
taskCh <- task
}
close(taskCh)
results := make([]analyzeResult, 0, len(e.tasks))
for i := 0; i < len(e.tasks); i++ {
result := <-resultCh
results = append(results, result)
if result.err != nil {
return nil, errors.Trace(err)
}
}
for _, result := range results {
for _, hg := range result.hist {
err = hg.SaveToStorage(e.ctx, result.tableID, result.count, result.isIndex)
if err != nil {
return nil, errors.Trace(err)
}
}
}
dom := sessionctx.GetDomain(e.ctx)
lease := dom.StatsHandle().Lease
if lease > 0 {
// We sleep two lease to make sure other tidb node has updated this node.
time.Sleep(lease * 2)
} else {
err := dom.StatsHandle().Update(GetInfoSchema(e.ctx))
if err != nil {
return nil, errors.Trace(err)
}
}
return nil, nil
}
func getBuildStatsConcurrency(ctx context.Context) (int, error) {
sessionVars := ctx.GetSessionVars()
concurrency, err := varsutil.GetSessionSystemVar(sessionVars, variable.TiDBBuildStatsConcurrency)
if err != nil {
return 0, errors.Trace(err)
}
c, err := strconv.ParseInt(concurrency, 10, 64)
return int(c), errors.Trace(err)
}
type taskType int
const (
pkTask taskType = iota
colTask
idxTask
)
type analyzeTask struct {
taskType taskType
tableInfo *model.TableInfo
indexInfo *model.IndexInfo
Columns []*model.ColumnInfo
src Executor
}
type analyzeResult struct {
tableID int64
hist []*statistics.Histogram
count int64
isIndex int
err error
}
func (e *AnalyzeExec) analyzeWorker(taskCh <-chan *analyzeTask, resultCh chan<- analyzeResult) {
for task := range taskCh {
switch task.taskType {
case pkTask:
resultCh <- e.analyzePK(task)
case colTask:
resultCh <- e.analyzeColumns(task)
case idxTask:
resultCh <- e.analyzeIndex(task)
}
}
}
func (e *AnalyzeExec) analyzePK(task *analyzeTask) analyzeResult {
count, hg, err := statistics.BuildPK(e.ctx, defaultBucketCount, task.Columns[0].ID, &recordSet{executor: task.src})
return analyzeResult{tableID: task.tableInfo.ID, hist: []*statistics.Histogram{hg}, count: count, isIndex: 0, err: err}
}
func (e *AnalyzeExec) analyzeColumns(task *analyzeTask) analyzeResult {
collectors, err := CollectSamplesAndEstimateNDVs(&recordSet{executor: task.src}, len(task.Columns))
if err != nil {
return analyzeResult{err: err}
}
result := analyzeResult{tableID: task.tableInfo.ID, count: collectors[0].Count + collectors[0].NullCount, isIndex: 0}
for i, col := range task.Columns {
hg, err := statistics.BuildColumn(e.ctx, defaultBucketCount, col.ID, collectors[i].Sketch.NDV(), collectors[i].Count, collectors[i].NullCount, collectors[i].samples)
result.hist = append(result.hist, hg)
if err != nil && result.err == nil {
result.err = err
}
}
return result
}
func (e *AnalyzeExec) analyzeIndex(task *analyzeTask) analyzeResult {
count, hg, err := statistics.BuildIndex(e.ctx, defaultBucketCount, task.indexInfo.ID, &recordSet{executor: task.src})
return analyzeResult{tableID: task.tableInfo.ID, hist: []*statistics.Histogram{hg}, count: count, isIndex: 1, err: err}
}
// SampleCollector will collect samples and calculate the count and ndv of an attribute.
type SampleCollector struct {
samples []types.Datum
NullCount int64
Count int64
Sketch *statistics.FMSketch
}
func (c *SampleCollector) collect(d types.Datum) error {
if d.IsNull() {
c.NullCount++
return nil
}
c.Count++
if len(c.samples) < maxSampleCount {
c.samples = append(c.samples, d)
} else {
shouldAdd := rand.Int63n(c.Count) < maxSampleCount
if shouldAdd {
idx := rand.Intn(maxSampleCount)
c.samples[idx] = d
}
}
return errors.Trace(c.Sketch.InsertValue(d))
}
// CollectSamplesAndEstimateNDVs collects sample from the result set using Reservoir Sampling algorithm,
// and estimates NDVs using FM Sketch during the collecting process. It returns the sample collectors which contain total
// count, null count and distinct values count.
// See https://en.wikipedia.org/wiki/Reservoir_sampling
// Exported for test.
func CollectSamplesAndEstimateNDVs(e ast.RecordSet, numCols int) ([]*SampleCollector, error) {
collectors := make([]*SampleCollector, numCols)
for i := range collectors {
collectors[i] = &SampleCollector{
Sketch: statistics.NewFMSketch(maxSketchSize),
}
}
for {
row, err := e.Next()
if err != nil {
return nil, errors.Trace(err)
}
if row == nil {
return collectors, nil
}
for i, val := range row.Data {
err = collectors[i].collect(val)
if err != nil {
return nil, errors.Trace(err)
}
}
}
}