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

json: implement json unary not with comparing to json(0) #40684

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
8 changes: 8 additions & 0 deletions cmd/explaintest/r/select.result
Original file line number Diff line number Diff line change
Expand Up @@ -658,3 +658,11 @@ insert into t3 values ('a');
select * from t3 where a > 0x80;
Error 1105 (HY000): Cannot convert string '\x80' from binary to utf8mb4
set @@tidb_enable_outer_join_reorder=false;
drop table if exists t1;
create table t1(j json);
insert into t1 values ('{"a":"b"}');
explain format = 'brief' select * from t1 WHERE NOT t1.j;
id estRows task access object operator info
Selection 8000.00 root eq(test.t1.j, "0")
└─TableReader 10000.00 root data:TableFullScan
└─TableFullScan 10000.00 cop[tikv] table:t1 keep order:false, stats:pseudo
5 changes: 5 additions & 0 deletions cmd/explaintest/t/select.test
Original file line number Diff line number Diff line change
Expand Up @@ -283,3 +283,8 @@ insert into t3 values ('a');
--error 1105
select * from t3 where a > 0x80;
set @@tidb_enable_outer_join_reorder=false;

drop table if exists t1;
create table t1(j json);
insert into t1 values ('{"a":"b"}');
explain format = 'brief' select * from t1 WHERE NOT t1.j;
1 change: 1 addition & 0 deletions errno/errcode.go
Original file line number Diff line number Diff line change
Expand Up @@ -922,6 +922,7 @@ const (
ErrFunctionalIndexNotApplicable = 3909
ErrDynamicPrivilegeNotRegistered = 3929
ErUserAccessDeniedForUserAccountBlockedByPasswordLock = 3955
ErrJSONInBooleanContext = 3986
ErrTableWithoutPrimaryKey = 3750
// MariaDB errors.
ErrOnlyOneDefaultPartionAllowed = 4030
Expand Down
1 change: 1 addition & 0 deletions errno/errname.go
Original file line number Diff line number Diff line change
Expand Up @@ -924,6 +924,7 @@ var MySQLErrName = map[uint16]*mysql.ErrMessage{
ErrInvalidRequiresSingleReference: mysql.Message("In recursive query block of Recursive Common Table Expression '%s', the recursive table must be referenced only once, and not in any subquery", nil),
ErrCTEMaxRecursionDepth: mysql.Message("Recursive query aborted after %d iterations. Try increasing @@cte_max_recursion_depth to a larger value", nil),
ErrTableWithoutPrimaryKey: mysql.Message("Unable to create or change a table without a primary key, when the system variable 'sql_require_primary_key' is set. Add a primary key to the table or unset this variable to avoid this message. Note that tables without a primary key can cause performance problems in row-based replication, so please consult your DBA before changing this setting.", nil),
ErrJSONInBooleanContext: mysql.Message("Evaluating a JSON value in SQL boolean context does an implicit comparison against JSON integer 0; if this is not what you want, consider converting JSON to a SQL numeric type with JSON_VALUE RETURNING", nil),
// MariaDB errors.
ErrOnlyOneDefaultPartionAllowed: mysql.Message("Only one DEFAULT partition allowed", nil),
ErrWrongPartitionTypeExpectedSystemTime: mysql.Message("Wrong partitioning type, expected type: `SYSTEM_TIME`", nil),
Expand Down
14 changes: 13 additions & 1 deletion expression/builtin_op.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"strings"

"github.com/pingcap/errors"
"github.com/pingcap/tidb/parser/ast"
"github.com/pingcap/tidb/parser/mysql"
"github.com/pingcap/tidb/parser/opcode"
"github.com/pingcap/tidb/sessionctx"
Expand Down Expand Up @@ -718,7 +719,7 @@ func (c *unaryNotFunctionClass) getFunction(ctx sessionctx.Context, args []Expre
argTp := args[0].GetType().EvalType()
if argTp == types.ETTimestamp || argTp == types.ETDatetime || argTp == types.ETDuration {
argTp = types.ETInt
} else if argTp == types.ETJson || argTp == types.ETString {
} else if argTp == types.ETString {
argTp = types.ETReal
}

Expand All @@ -739,6 +740,17 @@ func (c *unaryNotFunctionClass) getFunction(ctx sessionctx.Context, args []Expre
case types.ETInt:
sig = &builtinUnaryNotIntSig{bf}
sig.setPbCode(tipb.ScalarFuncSig_UnaryNotInt)
case types.ETJson:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why not like the other type, add a new sig builtinUnaryNotJSONSig

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good. I also agree add a new sig builtinUnaryNotJSONSig is better 🤝

// not(json) is to compare the json with json integer 0
zeroJSON := &Constant{
Value: types.NewJSONDatum(types.CreateBinaryJSON(int64(0))),
RetType: types.NewFieldType(mysql.TypeJSON),
}
sig, err = funcs[ast.EQ].getFunction(ctx, []Expression{args[0], zeroJSON})
if err != nil {
return nil, err
}
ctx.GetSessionVars().StmtCtx.AppendWarning(errJSONInBooleanContext)
default:
return nil, errors.Errorf("unexpected types.EvalType %v", argTp)
}
Expand Down
2 changes: 2 additions & 0 deletions expression/builtin_op_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -462,6 +462,8 @@ func TestUnaryNot(t *testing.T) {
{[]interface{}{"0.3"}, 0, false, false},
{[]interface{}{types.NewDecFromFloatForTest(0.3)}, 0, false, false},
{[]interface{}{nil}, 0, true, false},
{[]interface{}{types.CreateBinaryJSON(int64(0))}, 1, false, false},
{[]interface{}{types.CreateBinaryJSON(map[string]interface{}{"test": "test"})}, 0, false, false},

{[]interface{}{errors.New("must error")}, 0, false, true},
}
Expand Down
1 change: 1 addition & 0 deletions expression/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ var (
errSpecificAccessDenied = dbterror.ClassExpression.NewStd(mysql.ErrSpecificAccessDenied)
errUserLockDeadlock = dbterror.ClassExpression.NewStd(mysql.ErrUserLockDeadlock)
errUserLockWrongName = dbterror.ClassExpression.NewStd(mysql.ErrUserLockWrongName)
errJSONInBooleanContext = dbterror.ClassExpression.NewStd(mysql.ErrJSONInBooleanContext)

// Sequence usage privilege check.
errSequenceAccessDenied = dbterror.ClassExpression.NewStd(mysql.ErrTableaccessDenied)
Expand Down
6 changes: 6 additions & 0 deletions expression/scalar_function.go
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,12 @@ func newFunctionImpl(ctx sessionctx.Context, fold int, funcName string, retType
if builtinRetTp := f.getRetTp(); builtinRetTp.GetType() != mysql.TypeUnspecified || retType.GetType() == mysql.TypeUnspecified {
retType = builtinRetTp
}
// TODO: add a method for functions to get a name, or use other ways to replace this special case
// not(json) is implemented with comparing json with json 0. If we don't overwrite the funcName,
// the explain information will be `not(json, "0")`. We prefer to make it `eq(json, "0")`
if funcName == ast.UnaryNot && funcArgs[0].GetType().GetType() == mysql.TypeJSON {
funcName = ast.EQ
}
sf := &ScalarFunction{
FuncName: model.NewCIStr(funcName),
RetType: retType,
Expand Down