github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/pingcap/tidb/evaluator/builtin_control.go (about)

     1  // Copyright 2015 PingCAP, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package evaluator
    15  
    16  import (
    17  	"github.com/insionng/yougam/libraries/juju/errors"
    18  	"github.com/insionng/yougam/libraries/pingcap/tidb/context"
    19  	"github.com/insionng/yougam/libraries/pingcap/tidb/util/types"
    20  )
    21  
    22  // See https://dev.mysql.com/doc/refman/5.7/en/control-flow-functions.html#function_if
    23  func builtinIf(args []types.Datum, _ context.Context) (d types.Datum, err error) {
    24  	// if(expr1, expr2, expr3)
    25  	// if expr1 is true, return expr2, otherwise, return expr3
    26  	v1 := args[0]
    27  	v2 := args[1]
    28  	v3 := args[2]
    29  
    30  	if v1.Kind() == types.KindNull {
    31  		return v3, nil
    32  	}
    33  
    34  	b, err := v1.ToBool()
    35  	if err != nil {
    36  		d := types.Datum{}
    37  		return d, errors.Trace(err)
    38  	}
    39  
    40  	// TODO: check return type, must be numeric or string
    41  	if b == 1 {
    42  		return v2, nil
    43  	}
    44  
    45  	return v3, nil
    46  }
    47  
    48  // See https://dev.mysql.com/doc/refman/5.7/en/control-flow-functions.html#function_ifnull
    49  func builtinIfNull(args []types.Datum, _ context.Context) (d types.Datum, err error) {
    50  	// ifnull(expr1, expr2)
    51  	// if expr1 is not null, return expr1, otherwise, return expr2
    52  	v1 := args[0]
    53  	v2 := args[1]
    54  
    55  	if v1.Kind() != types.KindNull {
    56  		return v1, nil
    57  	}
    58  
    59  	return v2, nil
    60  }
    61  
    62  // See https://dev.mysql.com/doc/refman/5.7/en/control-flow-functions.html#function_nullif
    63  func builtinNullIf(args []types.Datum, _ context.Context) (d types.Datum, err error) {
    64  	// nullif(expr1, expr2)
    65  	// returns null if expr1 = expr2 is true, otherwise returns expr1
    66  	v1 := args[0]
    67  	v2 := args[1]
    68  
    69  	if v1.Kind() == types.KindNull || v2.Kind() == types.KindNull {
    70  		return v1, nil
    71  	}
    72  
    73  	if n, err1 := v1.CompareDatum(v2); err1 != nil || n == 0 {
    74  		d := types.Datum{}
    75  		return d, errors.Trace(err1)
    76  	}
    77  
    78  	return v1, nil
    79  }