Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ddl: migrate part of ddl package code from Execute/ExecRestricted to safe API (2) #22729

Merged
merged 7 commits into from
Feb 5, 2021
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 17 additions & 12 deletions ddl/delete_range.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ package ddl
import (
"context"
"encoding/hex"
"fmt"
"math"
"strings"
"sync"
"sync/atomic"

Expand All @@ -36,7 +36,7 @@ import (

const (
insertDeleteRangeSQLPrefix = `INSERT IGNORE INTO mysql.gc_delete_range VALUES `
insertDeleteRangeSQLValue = `("%d", "%d", "%s", "%s", "%d")`
insertDeleteRangeSQLValue = `(%?, %?, %?, %?, %?)`
insertDeleteRangeSQL = insertDeleteRangeSQLPrefix + insertDeleteRangeSQLValue

delBatchSize = 65536
Expand Down Expand Up @@ -403,44 +403,49 @@ func insertJobIntoDeleteRangeTable(ctx sessionctx.Context, job *model.Job) error

func doBatchDeleteIndiceRange(s sqlexec.SQLExecutor, jobID, tableID int64, indexIDs []int64, ts uint64) error {
logutil.BgLogger().Info("[ddl] batch insert into delete-range indices", zap.Int64("jobID", jobID), zap.Int64s("elementIDs", indexIDs))
sql := insertDeleteRangeSQLPrefix
paramsList := make([]interface{}, 0, len(indexIDs)*5)
var buf strings.Builder
buf.WriteString(insertDeleteRangeSQLPrefix)
for i, indexID := range indexIDs {
startKey := tablecodec.EncodeTableIndexPrefix(tableID, indexID)
endKey := tablecodec.EncodeTableIndexPrefix(tableID, indexID+1)
startKeyEncoded := hex.EncodeToString(startKey)
endKeyEncoded := hex.EncodeToString(endKey)
sql += fmt.Sprintf(insertDeleteRangeSQLValue, jobID, indexID, startKeyEncoded, endKeyEncoded, ts)
buf.WriteString(insertDeleteRangeSQLValue)
if i != len(indexIDs)-1 {
sql += ","
buf.WriteString(",")
}
paramsList = append(paramsList, jobID, indexID, startKeyEncoded, endKeyEncoded, ts)
}
_, err := s.Execute(context.Background(), sql)
_, err := s.ExecuteInternal(context.Background(), buf.String(), paramsList...)
return errors.Trace(err)
}

func doInsert(s sqlexec.SQLExecutor, jobID int64, elementID int64, startKey, endKey kv.Key, ts uint64) error {
logutil.BgLogger().Info("[ddl] insert into delete-range table", zap.Int64("jobID", jobID), zap.Int64("elementID", elementID))
startKeyEncoded := hex.EncodeToString(startKey)
endKeyEncoded := hex.EncodeToString(endKey)
sql := fmt.Sprintf(insertDeleteRangeSQL, jobID, elementID, startKeyEncoded, endKeyEncoded, ts)
_, err := s.Execute(context.Background(), sql)
_, err := s.ExecuteInternal(context.Background(), insertDeleteRangeSQL, jobID, elementID, startKeyEncoded, endKeyEncoded, ts)
return errors.Trace(err)
}

func doBatchInsert(s sqlexec.SQLExecutor, jobID int64, tableIDs []int64, ts uint64) error {
logutil.BgLogger().Info("[ddl] batch insert into delete-range table", zap.Int64("jobID", jobID), zap.Int64s("elementIDs", tableIDs))
sql := insertDeleteRangeSQLPrefix
var buf strings.Builder
buf.WriteString(insertDeleteRangeSQLPrefix)
paramsList := make([]interface{}, 0, len(tableIDs)*5)
for i, tableID := range tableIDs {
startKey := tablecodec.EncodeTablePrefix(tableID)
endKey := tablecodec.EncodeTablePrefix(tableID + 1)
startKeyEncoded := hex.EncodeToString(startKey)
endKeyEncoded := hex.EncodeToString(endKey)
sql += fmt.Sprintf(insertDeleteRangeSQLValue, jobID, tableID, startKeyEncoded, endKeyEncoded, ts)
buf.WriteString(insertDeleteRangeSQLValue)
if i != len(tableIDs)-1 {
sql += ","
buf.WriteString(",")
}
paramsList = append(paramsList, jobID, tableID, startKeyEncoded, endKeyEncoded, ts)
}
_, err := s.Execute(context.Background(), sql)
_, err := s.ExecuteInternal(context.Background(), buf.String(), paramsList...)
return errors.Trace(err)
}

Expand Down
109 changes: 83 additions & 26 deletions ddl/partition.go
Original file line number Diff line number Diff line change
Expand Up @@ -1337,6 +1337,7 @@ func (w *worker) onExchangeTablePartition(d *ddlCtx, t *meta.Meta, job *model.Jo

func checkExchangePartitionRecordValidation(w *worker, pt *model.TableInfo, index int, schemaName, tableName model.CIStr) error {
var sql string
var paramList []interface{}

pi := pt.Partition

Expand All @@ -1345,23 +1346,28 @@ func checkExchangePartitionRecordValidation(w *worker, pt *model.TableInfo, inde
if pi.Num == 1 {
return nil
}
sql = fmt.Sprintf("select 1 from `%s`.`%s` where mod(%s, %d) != %d limit 1", schemaName.L, tableName.L, pi.Expr, pi.Num, index)
var buf strings.Builder
buf.WriteString("select 1 from %n.%n where mod(")
buf.WriteString(pi.Expr)
buf.WriteString(", %?) != %? limit 1")
sql = buf.String()
paramList = append(paramList, schemaName.L, tableName.L, pi.Num, index)
case model.PartitionTypeRange:
// Table has only one partition and has the maximum value
if len(pi.Definitions) == 1 && strings.EqualFold(pi.Definitions[index].LessThan[0], partitionMaxValue) {
return nil
}
// For range expression and range columns
if len(pi.Columns) == 0 {
sql = buildCheckSQLForRangeExprPartition(pi, index, schemaName, tableName)
sql, paramList = buildCheckSQLForRangeExprPartition(pi, index, schemaName, tableName)
} else if len(pi.Columns) == 1 {
sql = buildCheckSQLForRangeColumnsPartition(pi, index, schemaName, tableName)
sql, paramList = buildCheckSQLForRangeColumnsPartition(pi, index, schemaName, tableName)
}
case model.PartitionTypeList:
if len(pi.Columns) == 0 {
sql = buildCheckSQLForListPartition(pi, index, schemaName, tableName)
sql, paramList = buildCheckSQLForListPartition(pi, index, schemaName, tableName)
} else if len(pi.Columns) == 1 {
sql = buildCheckSQLForListColumnsPartition(pi, index, schemaName, tableName)
sql, paramList = buildCheckSQLForListColumnsPartition(pi, index, schemaName, tableName)
}
default:
return errUnsupportedPartitionType.GenWithStackByArgs(pt.Name.O)
Expand All @@ -1374,7 +1380,11 @@ func checkExchangePartitionRecordValidation(w *worker, pt *model.TableInfo, inde
}
defer w.sessPool.put(ctx)

rows, _, err := ctx.(sqlexec.RestrictedSQLExecutor).ExecRestrictedSQL(sql)
stmt, err := ctx.(sqlexec.RestrictedSQLExecutor).ParseWithParams(context.Background(), sql, paramList...)
if err != nil {
return errors.Trace(err)
}
rows, _, err := ctx.(sqlexec.RestrictedSQLExecutor).ExecRestrictedStmt(context.Background(), stmt)
if err != nil {
return errors.Trace(err)
}
Expand All @@ -1385,46 +1395,93 @@ func checkExchangePartitionRecordValidation(w *worker, pt *model.TableInfo, inde
return nil
}

func buildCheckSQLForRangeExprPartition(pi *model.PartitionInfo, index int, schemaName, tableName model.CIStr) string {
func buildCheckSQLForRangeExprPartition(pi *model.PartitionInfo, index int, schemaName, tableName model.CIStr) (string, []interface{}) {
var buf strings.Builder
paramList := make([]interface{}, 0, 4)
// Since the pi.Expr string may contain the identifier, which couldn't be escaped in our ParseWithParams(...)
// So we write it to the origin sql string here.
if index == 0 {
return fmt.Sprintf("select 1 from `%s`.`%s` where %s >= %s limit 1", schemaName.L, tableName.L, pi.Expr, pi.Definitions[index].LessThan[0])
buf.WriteString("select 1 from %n.%n where ")
buf.WriteString(pi.Expr)
buf.WriteString(" >= %? limit 1")
paramList = append(paramList, schemaName.L, tableName.L, trimQuotation(pi.Definitions[index].LessThan[0]))
return buf.String(), paramList
} else if index == len(pi.Definitions)-1 && strings.EqualFold(pi.Definitions[index].LessThan[0], partitionMaxValue) {
return fmt.Sprintf("select 1 from `%s`.`%s` where %s < %s limit 1", schemaName.L, tableName.L, pi.Expr, pi.Definitions[index-1].LessThan[0])
buf.WriteString("select 1 from %n.%n where ")
buf.WriteString(pi.Expr)
buf.WriteString(" < %? limit 1")
paramList = append(paramList, schemaName.L, tableName.L, trimQuotation(pi.Definitions[index-1].LessThan[0]))
return buf.String(), paramList
} else {
return fmt.Sprintf("select 1 from `%s`.`%s` where %s < %s or %s >= %s limit 1", schemaName.L, tableName.L, pi.Expr, pi.Definitions[index-1].LessThan[0], pi.Expr, pi.Definitions[index].LessThan[0])
buf.WriteString("select 1 from %n.%n where ")
buf.WriteString(pi.Expr)
buf.WriteString(" < %? or ")
buf.WriteString(pi.Expr)
buf.WriteString(" >= %? limit 1")
paramList = append(paramList, schemaName.L, tableName.L, trimQuotation(pi.Definitions[index-1].LessThan[0]), trimQuotation(pi.Definitions[index].LessThan[0]))
return buf.String(), paramList
}
}

func buildCheckSQLForRangeColumnsPartition(pi *model.PartitionInfo, index int, schemaName, tableName model.CIStr) string {
func trimQuotation(str string) string {
return strings.Trim(str, "\"")
}

func buildCheckSQLForRangeColumnsPartition(pi *model.PartitionInfo, index int, schemaName, tableName model.CIStr) (string, []interface{}) {
paramList := make([]interface{}, 0, 6)
colName := pi.Columns[0].L
if index == 0 {
return fmt.Sprintf("select 1 from `%s`.`%s` where `%s` >= %s limit 1", schemaName.L, tableName.L, colName, pi.Definitions[index].LessThan[0])
paramList = append(paramList, schemaName.L, tableName.L, colName, trimQuotation(pi.Definitions[index].LessThan[0]))
return "select 1 from %n.%n where %n >= %? limit 1", paramList
} else if index == len(pi.Definitions)-1 && strings.EqualFold(pi.Definitions[index].LessThan[0], partitionMaxValue) {
return fmt.Sprintf("select 1 from `%s`.`%s` where `%s` < %s limit 1", schemaName.L, tableName.L, colName, pi.Definitions[index-1].LessThan[0])
paramList = append(paramList, schemaName.L, tableName.L, colName, trimQuotation(pi.Definitions[index-1].LessThan[0]))
return "select 1 from %n.%n where %n < %? limit 1", paramList
} else {
return fmt.Sprintf("select 1 from `%s`.`%s` where `%s` < %s or `%s` >= %s limit 1", schemaName.L, tableName.L, colName, pi.Definitions[index-1].LessThan[0], colName, pi.Definitions[index].LessThan[0])
paramList = append(paramList, schemaName.L, tableName.L, colName, trimQuotation(pi.Definitions[index-1].LessThan[0]), colName, trimQuotation(pi.Definitions[index].LessThan[0]))
return "select 1 from %n.%n where %n < %? or %n >= %? limit 1", paramList
}
}

func buildCheckSQLForListPartition(pi *model.PartitionInfo, index int, schemaName, tableName model.CIStr) string {
inValues := getInValues(pi, index)
sql := fmt.Sprintf("select 1 from `%s`.`%s` where %s not in (%s) limit 1", schemaName.L, tableName.L, pi.Expr, inValues)
return sql
func buildCheckSQLForListPartition(pi *model.PartitionInfo, index int, schemaName, tableName model.CIStr) (string, []interface{}) {
var buf strings.Builder
buf.WriteString("select 1 from %n.%n where ")
buf.WriteString(pi.Expr)
buf.WriteString(" not in (")
inValues := getInValues(&buf, pi, index)
AilinKid marked this conversation as resolved.
Show resolved Hide resolved
buf.WriteString(") limit 1")

paramList := make([]interface{}, 0, 2+len(inValues))
paramList = append(paramList, schemaName.L, tableName.L)
paramList = append(paramList, inValues...)
return buf.String(), paramList
}

func buildCheckSQLForListColumnsPartition(pi *model.PartitionInfo, index int, schemaName, tableName model.CIStr) string {
func buildCheckSQLForListColumnsPartition(pi *model.PartitionInfo, index int, schemaName, tableName model.CIStr) (string, []interface{}) {
colName := pi.Columns[0].L
inValues := getInValues(pi, index)
sql := fmt.Sprintf("select 1 from `%s`.`%s` where %s not in (%s) limit 1", schemaName.L, tableName.L, colName, inValues)
return sql
var buf strings.Builder
buf.WriteString("select 1 from %n.%n where %n not in (")
inValues := getInValues(&buf, pi, index)
buf.WriteString(") limit 1")

paramList := make([]interface{}, 0, 3+len(inValues))
paramList = append(paramList, schemaName.L, tableName.L, colName)
paramList = append(paramList, inValues...)
return buf.String(), paramList
}

func getInValues(pi *model.PartitionInfo, index int) string {
inValues := make([]string, 0, len(pi.Definitions[index].InValues))
func getInValues(buf *strings.Builder, pi *model.PartitionInfo, index int) []interface{} {
inValues := make([]interface{}, 0, len(pi.Definitions[index].InValues))
for _, inValue := range pi.Definitions[index].InValues {
inValues = append(inValues, inValue...)
for _, one := range inValue {
if len(inValues) == 0 {
buf.WriteString("%?")
} else {
buf.WriteString(", %?")
}
inValues = append(inValues, one)
}
}
return strings.Join(inValues, ",")
return inValues
}

func checkAddPartitionTooManyPartitions(piDefs uint64) error {
Expand Down
8 changes: 6 additions & 2 deletions ddl/reorg.go
Original file line number Diff line number Diff line change
Expand Up @@ -319,8 +319,12 @@ func getTableTotalCount(w *worker, tblInfo *model.TableInfo) int64 {
if !ok {
return statistics.PseudoRowCount
}
sql := fmt.Sprintf("select table_rows from information_schema.tables where tidb_table_id=%v;", tblInfo.ID)
rows, _, err := executor.ExecRestrictedSQL(sql)
sql := "select table_rows from information_schema.tables where tidb_table_id=%?;"
stmt, err := executor.ParseWithParams(context.Background(), sql, tblInfo.ID)
if err != nil {
return statistics.PseudoRowCount
}
rows, _, err := executor.ExecRestrictedStmt(context.Background(), stmt)
if err != nil {
return statistics.PseudoRowCount
}
Expand Down