|
| 1 | +// Copyright 2023 PingCAP, Inc. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a Copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +// TableRowStatsCache is the cache of table row count. |
| 16 | + |
| 17 | +package cache |
| 18 | + |
| 19 | +import ( |
| 20 | + "strconv" |
| 21 | + "strings" |
| 22 | + "time" |
| 23 | + |
| 24 | + "github.com/pingcap/tidb/pkg/meta/model" |
| 25 | + "github.com/pingcap/tidb/pkg/sessionctx" |
| 26 | + "github.com/pingcap/tidb/pkg/statistics/handle/util" |
| 27 | + "github.com/pingcap/tidb/pkg/types" |
| 28 | + "github.com/pingcap/tidb/pkg/util/chunk" |
| 29 | + "github.com/pingcap/tidb/pkg/util/syncutil" |
| 30 | +) |
| 31 | + |
| 32 | +// TableRowStatsCache is the cache of table row count. |
| 33 | +var TableRowStatsCache = &StatsTableRowCache{ |
| 34 | + tableRows: make(map[int64]uint64), |
| 35 | + colLength: make(map[tableHistID]uint64), |
| 36 | +} |
| 37 | + |
| 38 | +// tableStatsCacheExpiry is the expiry time for table stats cache. |
| 39 | +var tableStatsCacheExpiry = 3 * time.Second |
| 40 | + |
| 41 | +type tableHistID struct { |
| 42 | + tableID int64 |
| 43 | + histID int64 |
| 44 | +} |
| 45 | + |
| 46 | +// StatsTableRowCache is used to cache the count of table rows. |
| 47 | +type StatsTableRowCache struct { |
| 48 | + tableRows map[int64]uint64 |
| 49 | + colLength map[tableHistID]uint64 |
| 50 | + mu syncutil.RWMutex |
| 51 | +} |
| 52 | + |
| 53 | +// GetTableRows gets the count of table rows. |
| 54 | +func (c *StatsTableRowCache) GetTableRows(id int64) uint64 { |
| 55 | + c.mu.RLock() |
| 56 | + defer c.mu.RUnlock() |
| 57 | + return c.tableRows[id] |
| 58 | +} |
| 59 | + |
| 60 | +// GetColLength gets the length of the column. |
| 61 | +func (c *StatsTableRowCache) GetColLength(id tableHistID) uint64 { |
| 62 | + c.mu.RLock() |
| 63 | + defer c.mu.RUnlock() |
| 64 | + return c.colLength[id] |
| 65 | +} |
| 66 | + |
| 67 | +// UpdateByID tries to update the cache by table ID. |
| 68 | +func (c *StatsTableRowCache) UpdateByID(sctx sessionctx.Context, id int64) error { |
| 69 | + tableRows, err := getRowCountTables(sctx, id) |
| 70 | + if err != nil { |
| 71 | + return err |
| 72 | + } |
| 73 | + colLength, err := getColLengthTables(sctx, id) |
| 74 | + if err != nil { |
| 75 | + return err |
| 76 | + } |
| 77 | + c.mu.Lock() |
| 78 | + defer c.mu.Unlock() |
| 79 | + c.tableRows[id] = tableRows[id] |
| 80 | + for k, v := range colLength { |
| 81 | + c.colLength[k] = v |
| 82 | + } |
| 83 | + return nil |
| 84 | +} |
| 85 | + |
| 86 | +// EstimateDataLength returns the estimated data length in bytes of a given table info. |
| 87 | +// Returns row count, average row length, total data length, and all indexed column length. |
| 88 | +func (c *StatsTableRowCache) EstimateDataLength(table *model.TableInfo) ( |
| 89 | + rowCount uint64, avgRowLength uint64, dataLength uint64, indexLength uint64) { |
| 90 | + rowCount = c.GetTableRows(table.ID) |
| 91 | + dataLength, indexLength = c.GetDataAndIndexLength(table, table.ID, rowCount) |
| 92 | + if table.GetPartitionInfo() != nil { |
| 93 | + // For partition table, data only stores in partition level. |
| 94 | + // Keep `indexLength` for global index. |
| 95 | + rowCount, dataLength = 0, 0 |
| 96 | + for _, pi := range table.GetPartitionInfo().Definitions { |
| 97 | + piRowCnt := c.GetTableRows(pi.ID) |
| 98 | + rowCount += piRowCnt |
| 99 | + parDataLen, parIndexLen := c.GetDataAndIndexLength(table, pi.ID, piRowCnt) |
| 100 | + dataLength += parDataLen |
| 101 | + indexLength += parIndexLen |
| 102 | + } |
| 103 | + } |
| 104 | + avgRowLength = uint64(0) |
| 105 | + if rowCount != 0 { |
| 106 | + avgRowLength = dataLength / rowCount |
| 107 | + } |
| 108 | + |
| 109 | + if table.IsSequence() { |
| 110 | + // sequence is always 1 row regardless of stats. |
| 111 | + rowCount = 1 |
| 112 | + } |
| 113 | + return |
| 114 | +} |
| 115 | + |
| 116 | +func getRowCountTables(sctx sessionctx.Context, tableIDs ...int64) (map[int64]uint64, error) { |
| 117 | + var rows []chunk.Row |
| 118 | + var err error |
| 119 | + if len(tableIDs) == 0 { |
| 120 | + rows, _, err = util.ExecWithOpts(sctx, nil, "select table_id, count from mysql.stats_meta") |
| 121 | + } else { |
| 122 | + inTblIDs := buildInTableIDsString(tableIDs) |
| 123 | + sql := "select table_id, count from mysql.stats_meta where " + inTblIDs |
| 124 | + rows, _, err = util.ExecWithOpts(sctx, nil, sql) |
| 125 | + } |
| 126 | + if err != nil { |
| 127 | + return nil, err |
| 128 | + } |
| 129 | + |
| 130 | + rowCountMap := make(map[int64]uint64, len(rows)) |
| 131 | + for _, row := range rows { |
| 132 | + tableID := row.GetInt64(0) |
| 133 | + rowCnt := row.GetUint64(1) |
| 134 | + rowCountMap[tableID] = rowCnt |
| 135 | + } |
| 136 | + return rowCountMap, nil |
| 137 | +} |
| 138 | + |
| 139 | +func buildInTableIDsString(tableIDs []int64) string { |
| 140 | + var whereBuilder strings.Builder |
| 141 | + whereBuilder.WriteString("table_id in (") |
| 142 | + for i, id := range tableIDs { |
| 143 | + whereBuilder.WriteString(strconv.FormatInt(id, 10)) |
| 144 | + if i != len(tableIDs)-1 { |
| 145 | + whereBuilder.WriteString(",") |
| 146 | + } |
| 147 | + } |
| 148 | + whereBuilder.WriteString(")") |
| 149 | + return whereBuilder.String() |
| 150 | +} |
| 151 | + |
| 152 | +func getColLengthTables(sctx sessionctx.Context, tableIDs ...int64) (map[tableHistID]uint64, error) { |
| 153 | + var rows []chunk.Row |
| 154 | + var err error |
| 155 | + if len(tableIDs) == 0 { |
| 156 | + sql := "select table_id, hist_id, tot_col_size from mysql.stats_histograms where is_index = 0" |
| 157 | + rows, _, err = util.ExecWithOpts(sctx, nil, sql) |
| 158 | + } else { |
| 159 | + inTblIDs := buildInTableIDsString(tableIDs) |
| 160 | + sql := "select table_id, hist_id, tot_col_size from mysql.stats_histograms where is_index = 0 and " + inTblIDs |
| 161 | + rows, _, err = util.ExecWithOpts(sctx, nil, sql) |
| 162 | + } |
| 163 | + if err != nil { |
| 164 | + return nil, err |
| 165 | + } |
| 166 | + |
| 167 | + colLengthMap := make(map[tableHistID]uint64, len(rows)) |
| 168 | + for _, row := range rows { |
| 169 | + tableID := row.GetInt64(0) |
| 170 | + histID := row.GetInt64(1) |
| 171 | + totalSize := row.GetInt64(2) |
| 172 | + if totalSize < 0 { |
| 173 | + totalSize = 0 |
| 174 | + } |
| 175 | + colLengthMap[tableHistID{tableID: tableID, histID: histID}] = uint64(totalSize) |
| 176 | + } |
| 177 | + return colLengthMap, nil |
| 178 | +} |
| 179 | + |
| 180 | +// GetDataAndIndexLength gets the data and index length of the table. |
| 181 | +func (c *StatsTableRowCache) GetDataAndIndexLength(info *model.TableInfo, physicalID int64, rowCount uint64) (dataLength, indexLength uint64) { |
| 182 | + columnLength := make([]uint64, len(info.Columns)) |
| 183 | + for i, col := range info.Columns { |
| 184 | + if col.State != model.StatePublic { |
| 185 | + continue |
| 186 | + } |
| 187 | + var length uint64 |
| 188 | + if storageLen := col.FieldType.StorageLength(); storageLen != types.VarStorageLen { |
| 189 | + length = rowCount * uint64(storageLen) |
| 190 | + } else { |
| 191 | + length = c.GetColLength(tableHistID{tableID: physicalID, histID: col.ID}) |
| 192 | + } |
| 193 | + dataLength += length |
| 194 | + columnLength[i] = length |
| 195 | + } |
| 196 | + |
| 197 | + for _, idx := range info.Indices { |
| 198 | + if idx.State != model.StatePublic { |
| 199 | + continue |
| 200 | + } |
| 201 | + if info.GetPartitionInfo() != nil { |
| 202 | + // Global indexes calculated in table level. |
| 203 | + if idx.Global && info.ID != physicalID { |
| 204 | + continue |
| 205 | + } |
| 206 | + // Normal indexes calculated in partition level. |
| 207 | + if !idx.Global && info.ID == physicalID { |
| 208 | + continue |
| 209 | + } |
| 210 | + } |
| 211 | + for _, col := range idx.Columns { |
| 212 | + if col.Length == types.UnspecifiedLength { |
| 213 | + indexLength += columnLength[col.Offset] |
| 214 | + } else { |
| 215 | + indexLength += rowCount * uint64(col.Length) |
| 216 | + } |
| 217 | + } |
| 218 | + } |
| 219 | + return dataLength, indexLength |
| 220 | +} |
0 commit comments