pingcap / pingcap/tidb

Resolve the chaos usage of `Constant`

Open
#53,485 4 comments 0 reactions 1 assignee Claimed by @YangKeao View on GitHub
type/enhancement
Dominant language
Go
Stars
40.5k
Forks
6.2k
PR merge metrics
PR metrics pending

Description

The `Constant` struct has the following definition:

```go
// Constant stands for a constant value.
type Constant struct {
Value types.Datum
RetType *types.FieldType
// DeferredExpr holds deferred function in PlanCache cached plan.
// it's only used to represent non-deterministic functions(see expression.DeferredFunctions)
// in PlanCache cached plan, so let them can be evaluated until cached item be used.
DeferredExpr Expression
// ParamMarker holds param index inside sessionVars.PreparedParams.
// It's only used to reference a user variable provided in the `EXECUTE` statement or `COM_EXECUTE` binary protocol.
ParamMarker *ParamMarker
hashcode []byte

collationInfo
}
```

It can represent three different things:
1. A constant literal in SQL, which is simply represented as a `Datum` in the `Value`.
2. A function which needs to be evaluated when the plan cache is finally used. For example, the `NOW()` in `SELECT NOW()`.
3. A parameter (`?`) in the SQL. It's a constant during the execution of a single statement, and is actually stored in session context.

There are two problems:
1. `*ParamMarker` includes a full session context and uses the `SessionVars` in it, which will be reset and is not safe to read when the session is about to execute the next statement.
2. Many codes use the `Constant.Value` directly to read the value. It actually depends on the logic of `SetParameterValuesIntoSCtx` to set the `param.Datum = val`, and the `expressionRewriter.Leave` to create a `ParamMarker` based on the value. The whole dependency is quite fragile. If the statement uses plan cache, I'm not sure whether it's still correct.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.