81 lines
2.6 KiB
Go
81 lines
2.6 KiB
Go
// Copyright 2025 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,
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
// See the License for the specific language governing permissions and
|
|
// limitations under the License.
|
|
|
|
package bindinfo
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/pingcap/errors"
|
|
"github.com/pingcap/tidb/pkg/kv"
|
|
"github.com/pingcap/tidb/pkg/parser/terror"
|
|
"github.com/pingcap/tidb/pkg/planner/core/resolve"
|
|
"github.com/pingcap/tidb/pkg/sessionctx"
|
|
"github.com/pingcap/tidb/pkg/util"
|
|
"github.com/pingcap/tidb/pkg/util/chunk"
|
|
"github.com/pingcap/tidb/pkg/util/logutil"
|
|
"github.com/pingcap/tidb/pkg/util/sqlexec"
|
|
"go.uber.org/zap"
|
|
)
|
|
|
|
func callWithSCtx(sPool util.DestroyableSessionPool, wrapTxn bool, f func(sctx sessionctx.Context) error) (err error) {
|
|
resource, err := sPool.Get()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer func() {
|
|
if err == nil { // only recycle when no error
|
|
sPool.Put(resource)
|
|
} else {
|
|
// Note: Otherwise, the session will be leaked.
|
|
sPool.Destroy(resource)
|
|
}
|
|
}()
|
|
sctx := resource.(sessionctx.Context)
|
|
if wrapTxn {
|
|
if _, err = exec(sctx, "BEGIN PESSIMISTIC"); err != nil {
|
|
return
|
|
}
|
|
defer func() {
|
|
if err == nil {
|
|
_, err = exec(sctx, "COMMIT")
|
|
} else {
|
|
_, err1 := exec(sctx, "ROLLBACK")
|
|
terror.Log(errors.Trace(err1))
|
|
}
|
|
}()
|
|
}
|
|
|
|
err = f(sctx)
|
|
return
|
|
}
|
|
|
|
// exec is a helper function to execute sql and return RecordSet.
|
|
func exec(sctx sessionctx.Context, sql string, args ...any) (sqlexec.RecordSet, error) {
|
|
sqlExec := sctx.GetSQLExecutor()
|
|
return sqlExec.ExecuteInternal(kv.WithInternalSourceType(context.Background(), kv.InternalTxnBindInfo), sql, args...)
|
|
}
|
|
|
|
// execRows is a helper function to execute sql and return rows and fields.
|
|
func execRows(sctx sessionctx.Context, sql string, args ...any) (rows []chunk.Row, fields []*resolve.ResultField, err error) {
|
|
sqlExec := sctx.GetRestrictedSQLExecutor()
|
|
return sqlExec.ExecRestrictedSQL(kv.WithInternalSourceType(context.Background(), kv.InternalTxnBindInfo),
|
|
[]sqlexec.OptionFuncAlias{sqlexec.ExecOptionUseCurSession}, sql, args...)
|
|
}
|
|
|
|
// bindingLogger with category "sql-bind" is used to log statistic related messages.
|
|
func bindingLogger() *zap.Logger {
|
|
return logutil.BgLogger().With(zap.String("category", "sql-bind"))
|
|
}
|