vitess.io/vitess@v0.16.2/go/vt/vtgate/semantics/typer.go (about)

     1  /*
     2  Copyright 2021 The Vitess Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package semantics
    18  
    19  import (
    20  	"strings"
    21  
    22  	"vitess.io/vitess/go/mysql/collations"
    23  	"vitess.io/vitess/go/sqltypes"
    24  	querypb "vitess.io/vitess/go/vt/proto/query"
    25  	"vitess.io/vitess/go/vt/sqlparser"
    26  	"vitess.io/vitess/go/vt/vtgate/engine"
    27  )
    28  
    29  // typer is responsible for setting the type for expressions
    30  // it does it's work after visiting the children (up), since the children types is often needed to type a node.
    31  type typer struct {
    32  	exprTypes map[sqlparser.Expr]Type
    33  }
    34  
    35  // Type is the normal querypb.Type with collation
    36  type Type struct {
    37  	Type      querypb.Type
    38  	Collation collations.ID
    39  }
    40  
    41  func newTyper() *typer {
    42  	return &typer{
    43  		exprTypes: map[sqlparser.Expr]Type{},
    44  	}
    45  }
    46  
    47  var typeInt32 = Type{Type: sqltypes.Int32}
    48  var decimal = Type{Type: sqltypes.Decimal}
    49  var floatval = Type{Type: sqltypes.Float64}
    50  
    51  func (t *typer) up(cursor *sqlparser.Cursor) error {
    52  	switch node := cursor.Node().(type) {
    53  	case *sqlparser.Literal:
    54  		switch node.Type {
    55  		case sqlparser.IntVal:
    56  			t.exprTypes[node] = typeInt32
    57  		case sqlparser.StrVal:
    58  			t.exprTypes[node] = Type{Type: sqltypes.VarChar} // TODO - add system default collation name
    59  		case sqlparser.DecimalVal:
    60  			t.exprTypes[node] = decimal
    61  		case sqlparser.FloatVal:
    62  			t.exprTypes[node] = floatval
    63  		}
    64  	case sqlparser.AggrFunc:
    65  		code, ok := engine.SupportedAggregates[strings.ToLower(node.AggrName())]
    66  		if ok {
    67  			typ, ok := engine.OpcodeType[code]
    68  			if ok {
    69  				t.exprTypes[node] = Type{Type: typ}
    70  			}
    71  		}
    72  	}
    73  	return nil
    74  }
    75  
    76  func (t *typer) setTypeFor(node *sqlparser.ColName, typ Type) {
    77  	t.exprTypes[node] = typ
    78  }