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

planner: Adjust the log level and returned value when cacheableChecker check *ast.TableName nodes #46831

Merged
merged 11 commits into from
Sep 11, 2023
Merged
Show file tree
Hide file tree
Changes from 8 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
2 changes: 2 additions & 0 deletions planner/core/plan_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ import (
var (
// PlanCacheKeyTestIssue43667 is only for test.
PlanCacheKeyTestIssue43667 struct{}
// PlanCacheKeyTestIssue46760 is only for test.
PlanCacheKeyTestIssue46760 struct{}
)

// SetParameterValuesIntoSCtx sets these parameters into session context.
Expand Down
2 changes: 1 addition & 1 deletion planner/core/plan_cache_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ func GeneratePlanCacheStmtWithAST(ctx context.Context, sctx sessionctx.Context,
reason = "plan cache is disabled"
} else {
if isPrepStmt {
cacheable, reason = CacheableWithCtx(sctx, paramStmt, ret.InfoSchema)
cacheable, reason = IsASTCacheable(ctx, sctx, paramStmt, ret.InfoSchema)
} else {
cacheable = true // it is already checked here
}
Expand Down
157 changes: 64 additions & 93 deletions planner/core/plan_cacheable_checker.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
package core

import (
"context"
"errors"
"fmt"
"math"
"sync"
Expand All @@ -31,20 +33,28 @@ import (
"github.com/pingcap/tidb/types"
driver "github.com/pingcap/tidb/types/parser_driver"
"github.com/pingcap/tidb/util/filter"
"github.com/pingcap/tidb/util/intest"
"github.com/pingcap/tidb/util/logutil"
"go.uber.org/zap"
)

// Cacheable checks whether the input ast(query) is cacheable with empty session context, which is mainly for testing.
// TODO: only for test, remove this function later on.
func Cacheable(node ast.Node, is infoschema.InfoSchema) bool {
c, _ := CacheableWithCtx(nil, node, is)
c, _ := IsASTCacheable(nil, nil, node, is)
return c
}

// CacheableWithCtx checks whether the input ast(query) is cacheable.
// TODO: only for test, remove this function later on.
func CacheableWithCtx(sctx sessionctx.Context, node ast.Node, is infoschema.InfoSchema) (bool, string) {
return IsASTCacheable(nil, sctx, node, is)
}

// IsASTCacheable checks whether the input ast(query) is cacheable.
// Handle "ignore_plan_cache()" hint
// If there are multiple hints, only one will take effect
func CacheableWithCtx(sctx sessionctx.Context, node ast.Node, is infoschema.InfoSchema) (bool, string) {
func IsASTCacheable(ctx context.Context, sctx sessionctx.Context, node ast.Node, is infoschema.InfoSchema) (bool, string) {
_, isSelect := node.(*ast.SelectStmt)
_, isUpdate := node.(*ast.UpdateStmt)
_, isInsert := node.(*ast.InsertStmt)
Expand All @@ -54,6 +64,7 @@ func CacheableWithCtx(sctx sessionctx.Context, node ast.Node, is infoschema.Info
return false, "not a SELECT/UPDATE/INSERT/DELETE/SET statement"
}
checker := cacheableChecker{
ctx: ctx,
sctx: sctx,
cacheable: true,
schema: is,
Expand All @@ -66,6 +77,7 @@ func CacheableWithCtx(sctx sessionctx.Context, node ast.Node, is infoschema.Info

// cacheableChecker checks whether a query can be cached:
type cacheableChecker struct {
ctx context.Context
sctx sessionctx.Context
cacheable bool
schema infoschema.InfoSchema
Expand Down Expand Up @@ -185,26 +197,8 @@ func (checker *cacheableChecker) Enter(in ast.Node) (out ast.Node, skipChildren
}
case *ast.TableName:
if checker.schema != nil {
if isPartitionTable(checker.schema, node) {
// Temporary disable prepared plan cache until https://github.com/pingcap/tidb/issues/33031
// is fixed and additional tests with dynamic partition prune mode has been added.
/*
if checker.sctx != nil && checker.sctx.GetSessionVars().UseDynamicPartitionPrune() {
return in, false // dynamic-mode for partition tables can use plan-cache
}
*/
checker.cacheable = false
checker.reason = "query accesses partitioned tables is un-cacheable"
return in, true
}
if hasGeneratedCol(checker.schema, node) {
checker.cacheable = false
checker.reason = "query accesses generated columns is un-cacheable"
return in, true
}
if isTempTable(checker.schema, node) {
checker.cacheable = false
checker.reason = "query accesses temporary tables is un-cacheable"
checker.cacheable, checker.reason = checkTableCacheable(checker.ctx, checker.sctx, checker.schema, node, false)
if !checker.cacheable {
return in, true
}
}
Expand Down Expand Up @@ -496,39 +490,7 @@ func (checker *nonPreparedPlanCacheableChecker) Enter(in ast.Node) (out ast.Node
return in, !checker.cacheable
}
if checker.schema != nil {
tb, err := checker.schema.TableByName(node.Schema, node.Name)
if err != nil {
checker.cacheable = false
checker.reason = "table cannot be found in schema"
return in, !checker.cacheable
}
if tb.Meta().GetPartitionInfo() != nil {
checker.cacheable = false
checker.reason = "queries that access partitioning table are not supported"
return in, !checker.cacheable
}
for _, col := range tb.Cols() {
if col.IsGenerated() {
checker.cacheable = false
checker.reason = "queries that have generated columns are not supported"
return in, !checker.cacheable
}
}
if tb.Meta().TempTableType != model.TempTableNone {
checker.cacheable = false
checker.reason = "queries that access temporary tables are not supported"
return in, !checker.cacheable
}
if tb.Meta().IsView() {
checker.cacheable = false
checker.reason = "queries that access views are not supported"
return in, !checker.cacheable
}
if !tb.Type().IsNormalTable() {
checker.cacheable = false
checker.reason = "queries that access in-memory tables"
return in, !checker.cacheable
}
checker.cacheable, checker.reason = checkTableCacheable(nil, checker.sctx, checker.schema, node, true)
}
return in, !checker.cacheable
}
Expand All @@ -554,20 +516,6 @@ func (*nonPreparedPlanCacheableChecker) isFilterNode(node ast.Node) bool {
return false
}

func hasGeneratedCol(schema infoschema.InfoSchema, tn *ast.TableName) bool {
tb, err := schema.TableByName(tn.Schema, tn.Name)
if err != nil {
logutil.BgLogger().Error("Error occur in checking cacheable", zap.Error(err))
return false
}
for _, col := range tb.Cols() {
if col.IsGenerated() {
return true
}
}
return false
}

func getColType(schema infoschema.InfoSchema, tbl *ast.TableName, col *ast.ColumnName) (colType byte, found bool) {
if tbl == nil {
return 0, false
Expand All @@ -584,30 +532,6 @@ func getColType(schema infoschema.InfoSchema, tbl *ast.TableName, col *ast.Colum
return 0, false
}

func isTempTable(schema infoschema.InfoSchema, tn *ast.TableName) bool {
tb, err := schema.TableByName(tn.Schema, tn.Name)
if err != nil {
logutil.BgLogger().Error("Error occur in checking cacheable", zap.Error(err))
return false
}
if tb.Meta().TempTableType != model.TempTableNone {
return true
}
return false
}

func isPartitionTable(schema infoschema.InfoSchema, tn *ast.TableName) bool {
tb, err := schema.TableByName(tn.Schema, tn.Name)
if err != nil {
logutil.BgLogger().Error("Error occur in checking cacheable", zap.Error(err))
return false
}
if tb.Meta().GetPartitionInfo() != nil {
return true
}
return false
}

// isPlanCacheable returns whether this plan is cacheable and the reason if not.
func isPlanCacheable(sctx sessionctx.Context, p Plan, paramNum, limitParamNum int, hasSubQuery bool) (cacheable bool, reason string) {
var pp PhysicalPlan
Expand Down Expand Up @@ -696,3 +620,50 @@ func getMaxParamLimit(sctx sessionctx.Context) int {

return v
}

// checkTableCacheable checks whether a query accessing this table is cacheable.
func checkTableCacheable(ctx context.Context, sctx sessionctx.Context, schema infoschema.InfoSchema, node *ast.TableName, isNonPrep bool) (cacheable bool, reason string) {
tb, err := schema.TableByName(node.Schema, node.Name)
if intest.InTest && ctx != nil && ctx.Value(PlanCacheKeyTestIssue46760) != nil {
err = errors.New("mock error")
}
if err != nil {
sql := sctx.GetSessionVars().StmtCtx.OriginalSQL
if len(sql) > 256 {
sql = sql[:256]
}
logutil.BgLogger().Warn("find table failed", zap.Error(err), zap.String("sql", sql),
zap.String("table_schema", node.Schema.O), zap.String("table_name", node.Name.O))
return false, fmt.Sprintf("find table %s.%s failed: %s", node.Schema, node.Name, err.Error())
}

if tb.Meta().GetPartitionInfo() != nil {
// Temporary disable prepared plan cache until https://github.com/pingcap/tidb/issues/33031
// is fixed and additional tests with dynamic partition prune mode has been added.
/*
if checker.sctx != nil && checker.sctx.GetSessionVars().UseDynamicPartitionPrune() {
return in, false // dynamic-mode for partition tables can use plan-cache
}
*/
return false, "query accesses partitioned tables is un-cacheable"
}
for _, col := range tb.Cols() {
if col.IsGenerated() {
return false, "query accesses generated columns is un-cacheable"
}
}
if tb.Meta().TempTableType != model.TempTableNone {
return false, "query accesses temporary tables is un-cacheable"
}

if isNonPrep { // non-prep plan cache is stricter
if tb.Meta().IsView() {
return false, "queries that access views are not supported"
}
if !tb.Type().IsNormalTable() {
return false, "queries that access in-memory tables"
}
}

return true, ""
}
21 changes: 21 additions & 0 deletions planner/core/plan_cacheable_checker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package core_test

import (
"context"
"fmt"
"strings"
"testing"
Expand Down Expand Up @@ -89,6 +90,26 @@ func TestFixControl44823(t *testing.T) {
tk.MustQuery(`select @@last_plan_from_cache`).Check(testkit.Rows("1"))
}

func TestIssue46760(t *testing.T) {
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec("use test")
tk.MustExec(`create table t (a int)`)
tk.MustExec(`prepare st from 'select * from t where a<?'`)
tk.MustExec(`set @a=1`)
tk.MustQuery(`execute st using @a`).Check(testkit.Rows())
tk.MustQuery(`execute st using @a`).Check(testkit.Rows())
tk.MustQuery(`select @@last_plan_from_cache`).Check(testkit.Rows("1"))

ctx := context.WithValue(context.Background(), core.PlanCacheKeyTestIssue46760, struct{}{})
tk.MustExecWithContext(ctx, `prepare st from 'select * from t where a<?'`)
tk.MustQuery(`show warnings`).Check(testkit.Rows("Warning 1105 skip prepared plan-cache: find table test.t failed: mock error"))
tk.MustExec(`set @a=1`)
tk.MustQuery(`execute st using @a`).Check(testkit.Rows())
tk.MustQuery(`execute st using @a`).Check(testkit.Rows())
tk.MustQuery(`select @@last_plan_from_cache`).Check(testkit.Rows("0"))
}

func TestCacheable(t *testing.T) {
store := testkit.CreateMockStore(t)
mockCtx := mock.NewContext()
Expand Down