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

*: using EscapeSQL to enhance SQL formatting in dumping & lightning #33951

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all 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
66 changes: 40 additions & 26 deletions br/pkg/lightning/checkpoints/checkpoints.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import (
verify "github.com/pingcap/tidb/br/pkg/lightning/verification"
"github.com/pingcap/tidb/br/pkg/storage"
"github.com/pingcap/tidb/br/pkg/version/build"
"github.com/pingcap/tidb/util/sqlexec"
"go.uber.org/zap"
"modernc.org/mathutil"
)
Expand Down Expand Up @@ -1440,15 +1441,19 @@ func (cpdb *MySQLCheckpointsDB) IgnoreErrorCheckpoint(ctx context.Context, table
colName = columnTableName
}

// nolint:gosec
engineQuery := fmt.Sprintf(`
UPDATE %s.%s SET status = %d WHERE %s = ? AND status <= %d;
`, cpdb.schema, CheckpointTableNameEngine, CheckpointStatusLoaded, colName, CheckpointStatusMaxInvalid)
engineQuery, escapeErr := sqlexec.EscapeSQL(fmt.Sprintf(`
UPDATE %s.%%n SET status = %d WHERE %s = ? AND status <= %d;
`, cpdb.schema, CheckpointStatusLoaded, colName, CheckpointStatusMaxInvalid), CheckpointTableNameEngine)
if escapeErr != nil {
return errors.Trace(escapeErr)
}

// nolint:gosec
tableQuery := fmt.Sprintf(`
UPDATE %s.%s SET status = %d WHERE %s = ? AND status <= %d;
`, cpdb.schema, CheckpointTableNameTable, CheckpointStatusLoaded, colName, CheckpointStatusMaxInvalid)
tableQuery, escapeErr := sqlexec.EscapeSQL(fmt.Sprintf(`
UPDATE %s.%%n SET status = %d WHERE %s = ? AND status <= %d;
`, cpdb.schema, CheckpointStatusLoaded, colName, CheckpointStatusMaxInvalid), CheckpointTableNameTable)
if escapeErr != nil {
return errors.Trace(escapeErr)
}

s := common.SQLWithRetry{
DB: cpdb.db,
Expand Down Expand Up @@ -1479,31 +1484,40 @@ func (cpdb *MySQLCheckpointsDB) DestroyErrorCheckpoint(ctx context.Context, tabl
aliasedColName = "t.table_name"
}

selectQuery := fmt.Sprintf(`
selectQuery, escapeErr := sqlexec.EscapeSQL(fmt.Sprintf(`
SELECT
t.table_name,
COALESCE(MIN(e.engine_id), 0),
COALESCE(MAX(e.engine_id), -1)
FROM %[1]s.%[4]s t
LEFT JOIN %[1]s.%[5]s e ON t.table_name = e.table_name
WHERE %[2]s = ? AND t.status <= %[3]d
FROM %[1]s.%%n t
LEFT JOIN %[1]s.%%n e ON t.table_name = e.table_name
WHERE %s = ? AND t.status <= %d
GROUP BY t.table_name;
`, cpdb.schema, aliasedColName, CheckpointStatusMaxInvalid, CheckpointTableNameTable, CheckpointTableNameEngine)
`, cpdb.schema, aliasedColName, CheckpointStatusMaxInvalid), CheckpointTableNameTable, CheckpointTableNameEngine)
if escapeErr != nil {
return nil, errors.Trace(escapeErr)
}

// nolint:gosec
deleteChunkQuery := fmt.Sprintf(`
DELETE FROM %[1]s.%[4]s WHERE table_name IN (SELECT table_name FROM %[1]s.%[5]s WHERE %[2]s = ? AND status <= %[3]d)
`, cpdb.schema, colName, CheckpointStatusMaxInvalid, CheckpointTableNameChunk, CheckpointTableNameTable)
deleteChunkQuery, escapeErr := sqlexec.EscapeSQL(fmt.Sprintf(`
DELETE FROM %[1]s.%%n WHERE table_name IN (SELECT table_name FROM %[1]s.%%n WHERE %s = ? AND status <= %d)
`, cpdb.schema, colName, CheckpointStatusMaxInvalid), CheckpointTableNameChunk, CheckpointTableNameTable)
if escapeErr != nil {
return nil, errors.Trace(escapeErr)
}

// nolint:gosec
deleteEngineQuery := fmt.Sprintf(`
DELETE FROM %[1]s.%[4]s WHERE table_name IN (SELECT table_name FROM %[1]s.%[5]s WHERE %[2]s = ? AND status <= %[3]d)
`, cpdb.schema, colName, CheckpointStatusMaxInvalid, CheckpointTableNameEngine, CheckpointTableNameTable)
deleteEngineQuery, escapeErr := sqlexec.EscapeSQL(fmt.Sprintf(`
DELETE FROM %[1]s.%%n WHERE table_name IN (SELECT table_name FROM %[1]s.%%n WHERE %s = ? AND status <= %d)
`, cpdb.schema, colName, CheckpointStatusMaxInvalid), CheckpointTableNameEngine, CheckpointTableNameTable)
if escapeErr != nil {
return nil, errors.Trace(escapeErr)
}

// nolint:gosec
deleteTableQuery := fmt.Sprintf(`
DELETE FROM %s.%s WHERE %s = ? AND status <= %d
`, cpdb.schema, CheckpointTableNameTable, colName, CheckpointStatusMaxInvalid)
deleteTableQuery, escapeErr := sqlexec.EscapeSQL(fmt.Sprintf(`
DELETE FROM %s.%%n WHERE %s = ? AND status <= %d
`, cpdb.schema, colName, CheckpointStatusMaxInvalid), CheckpointTableNameTable)
if escapeErr != nil {
return nil, errors.Trace(escapeErr)
}

var targetTables []DestroyedTableCheckpoint

Expand All @@ -1514,7 +1528,7 @@ func (cpdb *MySQLCheckpointsDB) DestroyErrorCheckpoint(ctx context.Context, tabl
err := s.Transact(ctx, "destroy error checkpoints", func(c context.Context, tx *sql.Tx) error {
// Obtain the list of tables
targetTables = nil
rows, e := tx.QueryContext(c, selectQuery, tableName) // #nosec G201
rows, e := tx.QueryContext(c, selectQuery, tableName)
if e != nil {
return errors.Trace(e)
}
Expand Down
20 changes: 10 additions & 10 deletions br/pkg/lightning/checkpoints/checkpoints_sql_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -362,11 +362,11 @@ func TestIgnoreAllErrorCheckpoints_SQL(t *testing.T) {

s.mock.ExpectBegin()
s.mock.
ExpectExec("UPDATE `mock-schema`\\.engine_v\\d+ SET status = 30 WHERE 'all' = \\? AND status <= 25").
ExpectExec("UPDATE `mock-schema`\\.`engine_v\\d+` SET status = 30 WHERE 'all' = \\? AND status <= 25").
WithArgs(sqlmock.AnyArg()).
WillReturnResult(sqlmock.NewResult(5, 3))
s.mock.
ExpectExec("UPDATE `mock-schema`\\.table_v\\d+ SET status = 30 WHERE 'all' = \\? AND status <= 25").
ExpectExec("UPDATE `mock-schema`\\.`table_v\\d+` SET status = 30 WHERE 'all' = \\? AND status <= 25").
WithArgs(sqlmock.AnyArg()).
WillReturnResult(sqlmock.NewResult(6, 2))
s.mock.ExpectCommit()
Expand All @@ -381,11 +381,11 @@ func TestIgnoreOneErrorCheckpoint(t *testing.T) {

s.mock.ExpectBegin()
s.mock.
ExpectExec("UPDATE `mock-schema`\\.engine_v\\d+ SET status = 30 WHERE table_name = \\? AND status <= 25").
ExpectExec("UPDATE `mock-schema`\\.`engine_v\\d+` SET status = 30 WHERE table_name = \\? AND status <= 25").
WithArgs("`db1`.`t2`").
WillReturnResult(sqlmock.NewResult(5, 2))
s.mock.
ExpectExec("UPDATE `mock-schema`\\.table_v\\d+ SET status = 30 WHERE table_name = \\? AND status <= 25").
ExpectExec("UPDATE `mock-schema`\\.`table_v\\d+` SET status = 30 WHERE table_name = \\? AND status <= 25").
WithArgs("`db1`.`t2`").
WillReturnResult(sqlmock.NewResult(6, 1))
s.mock.ExpectCommit()
Expand All @@ -407,15 +407,15 @@ func TestDestroyAllErrorCheckpoints_SQL(t *testing.T) {
AddRow("`db1`.`t2`", -1, 0),
)
s.mock.
ExpectExec("DELETE FROM `mock-schema`\\.chunk_v\\d+ WHERE table_name IN .+ 'all' = \\?").
ExpectExec("DELETE FROM `mock-schema`\\.`chunk_v\\d+` WHERE table_name IN .+ 'all' = \\?").
WithArgs(sqlmock.AnyArg()).
WillReturnResult(sqlmock.NewResult(0, 5))
s.mock.
ExpectExec("DELETE FROM `mock-schema`\\.engine_v\\d+ WHERE table_name IN .+ 'all' = \\?").
ExpectExec("DELETE FROM `mock-schema`\\.`engine_v\\d+` WHERE table_name IN .+ 'all' = \\?").
WithArgs(sqlmock.AnyArg()).
WillReturnResult(sqlmock.NewResult(0, 3))
s.mock.
ExpectExec("DELETE FROM `mock-schema`\\.table_v\\d+ WHERE 'all' = \\?").
ExpectExec("DELETE FROM `mock-schema`\\.`table_v\\d+` WHERE 'all' = \\?").
WithArgs(sqlmock.AnyArg()).
WillReturnResult(sqlmock.NewResult(0, 2))
s.mock.ExpectCommit()
Expand All @@ -442,15 +442,15 @@ func TestDestroyOneErrorCheckpoints(t *testing.T) {
AddRow("`db1`.`t2`", -1, 0),
)
s.mock.
ExpectExec("DELETE FROM `mock-schema`\\.chunk_v\\d+ WHERE .+table_name = \\?").
ExpectExec("DELETE FROM `mock-schema`\\.`chunk_v\\d+` WHERE .+table_name = \\?").
WithArgs("`db1`.`t2`").
WillReturnResult(sqlmock.NewResult(0, 4))
s.mock.
ExpectExec("DELETE FROM `mock-schema`\\.engine_v\\d+ WHERE .+table_name = \\?").
ExpectExec("DELETE FROM `mock-schema`\\.`engine_v\\d+` WHERE .+table_name = \\?").
WithArgs("`db1`.`t2`").
WillReturnResult(sqlmock.NewResult(0, 2))
s.mock.
ExpectExec("DELETE FROM `mock-schema`\\.table_v\\d+ WHERE table_name = \\?").
ExpectExec("DELETE FROM `mock-schema`\\.`table_v\\d+` WHERE table_name = \\?").
WithArgs("`db1`.`t2`").
WillReturnResult(sqlmock.NewResult(0, 1))
s.mock.ExpectCommit()
Expand Down
20 changes: 5 additions & 15 deletions br/pkg/lightning/restore/meta_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -286,9 +286,7 @@ func (m *dbTableMetaMgr) AllocTableRowIDs(ctx context.Context, rawRowIDMax int64
newStatus = metaStatusRestoreStarted
}

// nolint:gosec
query := fmt.Sprintf("update %s set row_id_base = ?, row_id_max = ?, status = ? where table_id = ? and task_id = ?", m.tableName)
_, err := tx.ExecContext(ctx, query, newRowIDBase, newRowIDMax, newStatus.String(), m.tr.tableInfo.ID, m.taskID)
_, err := tx.ExecContext(ctx, fmt.Sprintf("update %s set row_id_base = ?, row_id_max = ?, status = ? where table_id = ? and task_id = ?", m.tableName), newRowIDBase, newRowIDMax, newStatus.String(), m.tr.tableInfo.ID, m.taskID)
if err != nil {
return errors.Trace(err)
}
Expand Down Expand Up @@ -456,9 +454,7 @@ func (m *dbTableMetaMgr) CheckAndUpdateLocalChecksum(ctx context.Context, checks
return errors.Trace(rows.Err())
}

// nolint:gosec
query := fmt.Sprintf("update %s set total_kvs = ?, total_bytes = ?, checksum = ?, status = ?, has_duplicates = ? where table_id = ? and task_id = ?", m.tableName)
_, err = tx.ExecContext(ctx, query, checksum.SumKVS(), checksum.SumSize(), checksum.Sum(), newStatus.String(), hasLocalDupes, m.tr.tableInfo.ID, m.taskID)
_, err = tx.ExecContext(ctx, fmt.Sprintf("update %s set total_kvs = ?, total_bytes = ?, checksum = ?, status = ?, has_duplicates = ? where table_id = ? and task_id = ?", m.tableName), checksum.SumKVS(), checksum.SumSize(), checksum.Sum(), newStatus.String(), hasLocalDupes, m.tr.tableInfo.ID, m.taskID)
return errors.Annotate(err, "update local checksum failed")
})
if err != nil {
Expand Down Expand Up @@ -677,9 +673,7 @@ func (m *dbTaskMetaMgr) CheckTasksExclusively(ctx context.Context, action func(t
return errors.Trace(err)
}
for _, task := range newTasks {
// nolint:gosec
query := fmt.Sprintf("REPLACE INTO %s (task_id, pd_cfgs, status, state, source_bytes, cluster_avail) VALUES(?, ?, ?, ?, ?, ?)", m.tableName)
if _, err = tx.ExecContext(ctx, query, task.taskID, task.pdCfgs, task.status.String(), task.state, task.sourceBytes, task.clusterAvail); err != nil {
if _, err = tx.ExecContext(ctx, fmt.Sprintf("REPLACE INTO %s (task_id, pd_cfgs, status, state, source_bytes, cluster_avail) VALUES(?, ?, ?, ?, ?, ?)", m.tableName), task.taskID, task.pdCfgs, task.status.String(), task.state, task.sourceBytes, task.clusterAvail); err != nil {
return errors.Trace(err)
}
}
Expand Down Expand Up @@ -785,9 +779,7 @@ func (m *dbTaskMetaMgr) CheckAndPausePdSchedulers(ctx context.Context) (pdutil.U
return errors.Trace(err)
}

// nolint:gosec
query := fmt.Sprintf("update %s set pd_cfgs = ?, status = ? where task_id = ?", m.tableName)
_, err = tx.ExecContext(ctx, query, string(jsonByts), taskMetaStatusScheduleSet.String(), m.taskID)
_, err = tx.ExecContext(ctx, fmt.Sprintf("update %s set pd_cfgs = ?, status = ? where task_id = ?", m.tableName), string(jsonByts), taskMetaStatusScheduleSet.String(), m.taskID)

return errors.Annotate(err, "update task pd configs failed")
})
Expand Down Expand Up @@ -898,9 +890,7 @@ func (m *dbTaskMetaMgr) CheckAndFinishRestore(ctx context.Context, finished bool
newStatus = taskMetaStatusSwitchSkipped
}

// nolint:gosec
query := fmt.Sprintf("update %s set status = ?, state = ? where task_id = ?", m.tableName)
if _, err = tx.ExecContext(ctx, query, newStatus.String(), newState, m.taskID); err != nil {
if _, err = tx.ExecContext(ctx, fmt.Sprintf("update %s set status = ?, state = ? where task_id = ?", m.tableName), newStatus.String(), newState, m.taskID); err != nil {
return errors.Trace(err)
}
}
Expand Down
1 change: 1 addition & 0 deletions br/pkg/mock/mock_cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@ func waitUntilServerOnline(addr string, statusPort uint) string {
// connect http status
statusURL := fmt.Sprintf("http://127.0.0.1:%d/status", statusPort)
for retry = 0; retry < retryTime; retry++ {
// #nosec G107
resp, err := http.Get(statusURL) // nolint:noctx,gosec
if err == nil {
// Ignore errors.
Expand Down
2 changes: 1 addition & 1 deletion cmd/pluginpkg/pluginpkg.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ func main() {
}

genFileName := filepath.Join(pkgDir, filepath.Base(pkgDir)+".gen.go")
genFile, err := os.OpenFile(genFileName, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0700) // # nosec G302
genFile, err := os.OpenFile(genFileName, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0700) // #nosec G302
if err != nil {
log.Printf("generate code failure during prepare output file, %+v\n", err)
os.Exit(1)
Expand Down
8 changes: 7 additions & 1 deletion dumpling/tests/s3/import.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (

_ "github.com/go-sql-driver/mysql"
"github.com/pingcap/errors"
"github.com/pingcap/tidb/util/sqlexec"
"github.com/spf13/cobra"
"golang.org/x/sync/errgroup"
)
Expand Down Expand Up @@ -62,7 +63,12 @@ func main() {
return errors.Trace(err)
}

query := fmt.Sprintf("insert into %s values('aaaaaaaaaa')", table) // nolint:gosec
query, escapeErr := sqlexec.EscapeSQL("insert into %n values('aaaaaaaaaa')", table)
if escapeErr != nil {
fmt.Printf("fail to import data, err: %v", escapeErr)
os.Exit(2)
}

for i := 1; i < 10000; i++ {
query += ",('aaaaaaaaaa')"
}
Expand Down
2 changes: 1 addition & 1 deletion executor/select_into.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ func (s *SelectIntoExec) Open(ctx context.Context) error {
}

// MySQL-compatible behavior: allow files to be group-readable
f, err := os.OpenFile(s.intoOpt.FileName, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0640) // # nosec G302
f, err := os.OpenFile(s.intoOpt.FileName, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0640) // #nosec G302
if err != nil {
return errors.Trace(err)
}
Expand Down
4 changes: 2 additions & 2 deletions util/security.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ func ToTLSConfigWithVerify(caPath, certPath, keyPath string, verifyCN []string)
}
//nolint:gosec
tlsCfg := &tls.Config{
MinVersion: tls.VersionTLS10,
MinVersion: tls.VersionTLS12,
Certificates: certificates,
RootCAs: certPool,
ClientCAs: certPool,
Expand Down Expand Up @@ -125,7 +125,7 @@ func ToTLSConfigWithVerifyByRawbytes(caData, certData, keyData []byte, verifyCN
}
//nolint:gosec
tlsCfg := &tls.Config{
MinVersion: tls.VersionTLS10,
MinVersion: tls.VersionTLS12,
Certificates: certificates,
RootCAs: certPool,
ClientCAs: certPool,
Expand Down