github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/pingcap/tidb/optimizer/logic.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 optimizer
    15  
    16  import (
    17  	"github.com/insionng/yougam/libraries/pingcap/tidb/ast"
    18  	"github.com/insionng/yougam/libraries/pingcap/tidb/context"
    19  	"github.com/insionng/yougam/libraries/pingcap/tidb/evaluator"
    20  )
    21  
    22  // logicOptimize does logic optimization works on AST.
    23  func logicOptimize(ctx context.Context, node ast.Node) error {
    24  	return preEvaluate(ctx, node)
    25  }
    26  
    27  // preEvaluate evaluates preEvaluable expression and rewrites constant expression to value expression.
    28  func preEvaluate(ctx context.Context, node ast.Node) error {
    29  	pe := preEvaluator{ctx: ctx}
    30  	node.Accept(&pe)
    31  	return pe.err
    32  }
    33  
    34  type preEvaluator struct {
    35  	ctx context.Context
    36  	err error
    37  }
    38  
    39  func (r *preEvaluator) Enter(in ast.Node) (ast.Node, bool) {
    40  	return in, false
    41  }
    42  
    43  func (r *preEvaluator) Leave(in ast.Node) (ast.Node, bool) {
    44  	if expr, ok := in.(ast.ExprNode); ok {
    45  		if _, ok = expr.(*ast.ValueExpr); ok {
    46  			return in, true
    47  		} else if ast.IsPreEvaluable(expr) {
    48  			val, err := evaluator.Eval(r.ctx, expr)
    49  			if err != nil {
    50  				r.err = err
    51  				return in, false
    52  			}
    53  			if ast.IsConstant(expr) {
    54  				// The expression is constant, rewrite the expression to value expression.
    55  				valExpr := &ast.ValueExpr{}
    56  				valExpr.SetText(expr.Text())
    57  				valExpr.SetType(expr.GetType())
    58  				valExpr.SetDatum(val)
    59  				return valExpr, true
    60  			}
    61  			expr.SetDatum(val)
    62  		}
    63  	}
    64  	return in, true
    65  }