github.com/pingcap/tidb/parser@v0.0.0-20231013125129-93a834a6bf8d/ast/functions.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 ast
    15  
    16  import (
    17  	"fmt"
    18  	"io"
    19  	"strings"
    20  	"time"
    21  
    22  	"github.com/pingcap/errors"
    23  	"github.com/pingcap/tidb/parser/format"
    24  	"github.com/pingcap/tidb/parser/model"
    25  	"github.com/pingcap/tidb/parser/types"
    26  )
    27  
    28  var (
    29  	_ FuncNode = &AggregateFuncExpr{}
    30  	_ FuncNode = &FuncCallExpr{}
    31  	_ FuncNode = &FuncCastExpr{}
    32  	_ FuncNode = &WindowFuncExpr{}
    33  )
    34  
    35  // List scalar function names.
    36  const (
    37  	LogicAnd           = "and"
    38  	Cast               = "cast"
    39  	LeftShift          = "leftshift"
    40  	RightShift         = "rightshift"
    41  	LogicOr            = "or"
    42  	GE                 = "ge"
    43  	LE                 = "le"
    44  	EQ                 = "eq"
    45  	NE                 = "ne"
    46  	LT                 = "lt"
    47  	GT                 = "gt"
    48  	Plus               = "plus"
    49  	Minus              = "minus"
    50  	And                = "bitand"
    51  	Or                 = "bitor"
    52  	Mod                = "mod"
    53  	Xor                = "bitxor"
    54  	Div                = "div"
    55  	Mul                = "mul"
    56  	UnaryNot           = "not" // Avoid name conflict with Not in github/pingcap/check.
    57  	BitNeg             = "bitneg"
    58  	IntDiv             = "intdiv"
    59  	LogicXor           = "xor"
    60  	NullEQ             = "nulleq"
    61  	UnaryPlus          = "unaryplus"
    62  	UnaryMinus         = "unaryminus"
    63  	In                 = "in"
    64  	Like               = "like"
    65  	Ilike              = "ilike"
    66  	Case               = "case"
    67  	Regexp             = "regexp"
    68  	RegexpLike         = "regexp_like"
    69  	RegexpSubstr       = "regexp_substr"
    70  	RegexpInStr        = "regexp_instr"
    71  	RegexpReplace      = "regexp_replace"
    72  	IsNull             = "isnull"
    73  	IsTruthWithoutNull = "istrue" // Avoid name conflict with IsTrue in github/pingcap/check.
    74  	IsTruthWithNull    = "istrue_with_null"
    75  	IsFalsity          = "isfalse" // Avoid name conflict with IsFalse in github/pingcap/check.
    76  	RowFunc            = "row"
    77  	SetVar             = "setvar"
    78  	GetVar             = "getvar"
    79  	Values             = "values"
    80  	BitCount           = "bit_count"
    81  	GetParam           = "getparam"
    82  
    83  	// common functions
    84  	Coalesce = "coalesce"
    85  	Greatest = "greatest"
    86  	Least    = "least"
    87  	Interval = "interval"
    88  
    89  	// math functions
    90  	Abs      = "abs"
    91  	Acos     = "acos"
    92  	Asin     = "asin"
    93  	Atan     = "atan"
    94  	Atan2    = "atan2"
    95  	Ceil     = "ceil"
    96  	Ceiling  = "ceiling"
    97  	Conv     = "conv"
    98  	Cos      = "cos"
    99  	Cot      = "cot"
   100  	CRC32    = "crc32"
   101  	Degrees  = "degrees"
   102  	Exp      = "exp"
   103  	Floor    = "floor"
   104  	Ln       = "ln"
   105  	Log      = "log"
   106  	Log2     = "log2"
   107  	Log10    = "log10"
   108  	PI       = "pi"
   109  	Pow      = "pow"
   110  	Power    = "power"
   111  	Radians  = "radians"
   112  	Rand     = "rand"
   113  	Round    = "round"
   114  	Sign     = "sign"
   115  	Sin      = "sin"
   116  	Sqrt     = "sqrt"
   117  	Tan      = "tan"
   118  	Truncate = "truncate"
   119  
   120  	// time functions
   121  	AddDate          = "adddate"
   122  	AddTime          = "addtime"
   123  	ConvertTz        = "convert_tz"
   124  	Curdate          = "curdate"
   125  	CurrentDate      = "current_date"
   126  	CurrentTime      = "current_time"
   127  	CurrentTimestamp = "current_timestamp"
   128  	Curtime          = "curtime"
   129  	Date             = "date"
   130  	DateLiteral      = "'tidb`.(dateliteral"
   131  	DateAdd          = "date_add"
   132  	DateFormat       = "date_format"
   133  	DateSub          = "date_sub"
   134  	DateDiff         = "datediff"
   135  	Day              = "day"
   136  	DayName          = "dayname"
   137  	DayOfMonth       = "dayofmonth"
   138  	DayOfWeek        = "dayofweek"
   139  	DayOfYear        = "dayofyear"
   140  	Extract          = "extract"
   141  	FromDays         = "from_days"
   142  	FromUnixTime     = "from_unixtime"
   143  	GetFormat        = "get_format"
   144  	Hour             = "hour"
   145  	LocalTime        = "localtime"
   146  	LocalTimestamp   = "localtimestamp"
   147  	MakeDate         = "makedate"
   148  	MakeTime         = "maketime"
   149  	MicroSecond      = "microsecond"
   150  	Minute           = "minute"
   151  	Month            = "month"
   152  	MonthName        = "monthname"
   153  	Now              = "now"
   154  	PeriodAdd        = "period_add"
   155  	PeriodDiff       = "period_diff"
   156  	Quarter          = "quarter"
   157  	SecToTime        = "sec_to_time"
   158  	Second           = "second"
   159  	StrToDate        = "str_to_date"
   160  	SubDate          = "subdate"
   161  	SubTime          = "subtime"
   162  	Sysdate          = "sysdate"
   163  	Time             = "time"
   164  	TimeLiteral      = "'tidb`.(timeliteral"
   165  	TimeFormat       = "time_format"
   166  	TimeToSec        = "time_to_sec"
   167  	TimeDiff         = "timediff"
   168  	Timestamp        = "timestamp"
   169  	TimestampLiteral = "'tidb`.(timestampliteral"
   170  	TimestampAdd     = "timestampadd"
   171  	TimestampDiff    = "timestampdiff"
   172  	ToDays           = "to_days"
   173  	ToSeconds        = "to_seconds"
   174  	UnixTimestamp    = "unix_timestamp"
   175  	UTCDate          = "utc_date"
   176  	UTCTime          = "utc_time"
   177  	UTCTimestamp     = "utc_timestamp"
   178  	Week             = "week"
   179  	Weekday          = "weekday"
   180  	WeekOfYear       = "weekofyear"
   181  	Year             = "year"
   182  	YearWeek         = "yearweek"
   183  	LastDay          = "last_day"
   184  	// TSO functions
   185  	// TiDBBoundedStaleness is used to determine the TS for a read only request with the given bounded staleness.
   186  	// It will be used in the Stale Read feature.
   187  	// For more info, please see AsOfClause.
   188  	TiDBBoundedStaleness = "tidb_bounded_staleness"
   189  	TiDBParseTso         = "tidb_parse_tso"
   190  	TiDBParseTsoLogical  = "tidb_parse_tso_logical"
   191  	TiDBCurrentTso       = "tidb_current_tso"
   192  
   193  	// string functions
   194  	ASCII           = "ascii"
   195  	Bin             = "bin"
   196  	Concat          = "concat"
   197  	ConcatWS        = "concat_ws"
   198  	Convert         = "convert"
   199  	Elt             = "elt"
   200  	ExportSet       = "export_set"
   201  	Field           = "field"
   202  	Format          = "format"
   203  	FromBase64      = "from_base64"
   204  	InsertFunc      = "insert_func"
   205  	Instr           = "instr"
   206  	Lcase           = "lcase"
   207  	Left            = "left"
   208  	Length          = "length"
   209  	LoadFile        = "load_file"
   210  	Locate          = "locate"
   211  	Lower           = "lower"
   212  	Lpad            = "lpad"
   213  	LTrim           = "ltrim"
   214  	MakeSet         = "make_set"
   215  	Mid             = "mid"
   216  	Oct             = "oct"
   217  	OctetLength     = "octet_length"
   218  	Ord             = "ord"
   219  	Position        = "position"
   220  	Quote           = "quote"
   221  	Repeat          = "repeat"
   222  	Replace         = "replace"
   223  	Reverse         = "reverse"
   224  	Right           = "right"
   225  	RTrim           = "rtrim"
   226  	Space           = "space"
   227  	Strcmp          = "strcmp"
   228  	Substring       = "substring"
   229  	Substr          = "substr"
   230  	SubstringIndex  = "substring_index"
   231  	ToBase64        = "to_base64"
   232  	Trim            = "trim"
   233  	Translate       = "translate"
   234  	Upper           = "upper"
   235  	Ucase           = "ucase"
   236  	Hex             = "hex"
   237  	Unhex           = "unhex"
   238  	Rpad            = "rpad"
   239  	BitLength       = "bit_length"
   240  	CharFunc        = "char_func"
   241  	CharLength      = "char_length"
   242  	CharacterLength = "character_length"
   243  	FindInSet       = "find_in_set"
   244  	WeightString    = "weight_string"
   245  	Soundex         = "soundex"
   246  
   247  	// information functions
   248  	Benchmark            = "benchmark"
   249  	Charset              = "charset"
   250  	Coercibility         = "coercibility"
   251  	Collation            = "collation"
   252  	ConnectionID         = "connection_id"
   253  	CurrentUser          = "current_user"
   254  	CurrentRole          = "current_role"
   255  	Database             = "database"
   256  	FoundRows            = "found_rows"
   257  	LastInsertId         = "last_insert_id"
   258  	RowCount             = "row_count"
   259  	Schema               = "schema"
   260  	SessionUser          = "session_user"
   261  	SystemUser           = "system_user"
   262  	User                 = "user"
   263  	Version              = "version"
   264  	TiDBVersion          = "tidb_version"
   265  	TiDBIsDDLOwner       = "tidb_is_ddl_owner"
   266  	TiDBDecodePlan       = "tidb_decode_plan"
   267  	TiDBDecodeBinaryPlan = "tidb_decode_binary_plan"
   268  	TiDBDecodeSQLDigests = "tidb_decode_sql_digests"
   269  	TiDBEncodeSQLDigest  = "tidb_encode_sql_digest"
   270  	FormatBytes          = "format_bytes"
   271  	FormatNanoTime       = "format_nano_time"
   272  	CurrentResourceGroup = "current_resource_group"
   273  
   274  	// control functions
   275  	If     = "if"
   276  	Ifnull = "ifnull"
   277  	Nullif = "nullif"
   278  
   279  	// miscellaneous functions
   280  	AnyValue        = "any_value"
   281  	DefaultFunc     = "default_func"
   282  	InetAton        = "inet_aton"
   283  	InetNtoa        = "inet_ntoa"
   284  	Inet6Aton       = "inet6_aton"
   285  	Inet6Ntoa       = "inet6_ntoa"
   286  	IsFreeLock      = "is_free_lock"
   287  	IsIPv4          = "is_ipv4"
   288  	IsIPv4Compat    = "is_ipv4_compat"
   289  	IsIPv4Mapped    = "is_ipv4_mapped"
   290  	IsIPv6          = "is_ipv6"
   291  	IsUsedLock      = "is_used_lock"
   292  	IsUUID          = "is_uuid"
   293  	MasterPosWait   = "master_pos_wait"
   294  	NameConst       = "name_const"
   295  	ReleaseAllLocks = "release_all_locks"
   296  	Sleep           = "sleep"
   297  	UUID            = "uuid"
   298  	UUIDShort       = "uuid_short"
   299  	UUIDToBin       = "uuid_to_bin"
   300  	BinToUUID       = "bin_to_uuid"
   301  	VitessHash      = "vitess_hash"
   302  	TiDBShard       = "tidb_shard"
   303  	TiDBRowChecksum = "tidb_row_checksum"
   304  	GetLock         = "get_lock"
   305  	ReleaseLock     = "release_lock"
   306  	Grouping        = "grouping"
   307  
   308  	// encryption and compression functions
   309  	AesDecrypt               = "aes_decrypt"
   310  	AesEncrypt               = "aes_encrypt"
   311  	Compress                 = "compress"
   312  	Decode                   = "decode"
   313  	DesDecrypt               = "des_decrypt"
   314  	DesEncrypt               = "des_encrypt"
   315  	Encode                   = "encode"
   316  	Encrypt                  = "encrypt"
   317  	MD5                      = "md5"
   318  	OldPassword              = "old_password"
   319  	PasswordFunc             = "password_func"
   320  	RandomBytes              = "random_bytes"
   321  	SHA1                     = "sha1"
   322  	SHA                      = "sha"
   323  	SHA2                     = "sha2"
   324  	SM3                      = "sm3"
   325  	Uncompress               = "uncompress"
   326  	UncompressedLength       = "uncompressed_length"
   327  	ValidatePasswordStrength = "validate_password_strength"
   328  
   329  	// json functions
   330  	JSONType          = "json_type"
   331  	JSONExtract       = "json_extract"
   332  	JSONUnquote       = "json_unquote"
   333  	JSONArray         = "json_array"
   334  	JSONObject        = "json_object"
   335  	JSONMerge         = "json_merge"
   336  	JSONSet           = "json_set"
   337  	JSONInsert        = "json_insert"
   338  	JSONReplace       = "json_replace"
   339  	JSONRemove        = "json_remove"
   340  	JSONOverlaps      = "json_overlaps"
   341  	JSONContains      = "json_contains"
   342  	JSONMemberOf      = "json_memberof"
   343  	JSONContainsPath  = "json_contains_path"
   344  	JSONValid         = "json_valid"
   345  	JSONArrayAppend   = "json_array_append"
   346  	JSONArrayInsert   = "json_array_insert"
   347  	JSONMergePatch    = "json_merge_patch"
   348  	JSONMergePreserve = "json_merge_preserve"
   349  	JSONPretty        = "json_pretty"
   350  	JSONQuote         = "json_quote"
   351  	JSONSearch        = "json_search"
   352  	JSONStorageFree   = "json_storage_free"
   353  	JSONStorageSize   = "json_storage_size"
   354  	JSONDepth         = "json_depth"
   355  	JSONKeys          = "json_keys"
   356  	JSONLength        = "json_length"
   357  
   358  	// TiDB internal function.
   359  	TiDBDecodeKey       = "tidb_decode_key"
   360  	TiDBDecodeBase64Key = "tidb_decode_base64_key"
   361  
   362  	// MVCC information fetching function.
   363  	GetMvccInfo = "get_mvcc_info"
   364  
   365  	// Sequence function.
   366  	NextVal = "nextval"
   367  	LastVal = "lastval"
   368  	SetVal  = "setval"
   369  )
   370  
   371  type FuncCallExprType int8
   372  
   373  const (
   374  	FuncCallExprTypeKeyword FuncCallExprType = iota
   375  	FuncCallExprTypeGeneric
   376  )
   377  
   378  // FuncCallExpr is for function expression.
   379  type FuncCallExpr struct {
   380  	funcNode
   381  	Tp     FuncCallExprType
   382  	Schema model.CIStr
   383  	// FnName is the function name.
   384  	FnName model.CIStr
   385  	// Args is the function args.
   386  	Args []ExprNode
   387  }
   388  
   389  // Restore implements Node interface.
   390  func (n *FuncCallExpr) Restore(ctx *format.RestoreCtx) error {
   391  	done, err := n.customRestore(ctx)
   392  	if done {
   393  		return err
   394  	}
   395  
   396  	if len(n.Schema.String()) != 0 {
   397  		ctx.WriteName(n.Schema.O)
   398  		ctx.WritePlain(".")
   399  	}
   400  	if n.Tp == FuncCallExprTypeGeneric {
   401  		ctx.WriteName(n.FnName.O)
   402  	} else {
   403  		ctx.WriteKeyWord(n.FnName.O)
   404  	}
   405  
   406  	ctx.WritePlain("(")
   407  	switch n.FnName.L {
   408  	case "convert":
   409  		if err := n.Args[0].Restore(ctx); err != nil {
   410  			return errors.Annotatef(err, "An error occurred while restore FuncCastExpr.Expr")
   411  		}
   412  		ctx.WriteKeyWord(" USING ")
   413  		if err := n.Args[1].Restore(ctx); err != nil {
   414  			return errors.Annotatef(err, "An error occurred while restore FuncCastExpr.Expr")
   415  		}
   416  	case "adddate", "subdate", "date_add", "date_sub":
   417  		if err := n.Args[0].Restore(ctx); err != nil {
   418  			return errors.Annotatef(err, "An error occurred while restore FuncCallExpr.Args[0]")
   419  		}
   420  		ctx.WritePlain(", ")
   421  		ctx.WriteKeyWord("INTERVAL ")
   422  		if err := n.Args[1].Restore(ctx); err != nil {
   423  			return errors.Annotatef(err, "An error occurred while restore FuncCallExpr.Args[1]")
   424  		}
   425  		ctx.WritePlain(" ")
   426  		if err := n.Args[2].Restore(ctx); err != nil {
   427  			return errors.Annotatef(err, "An error occurred while restore FuncCallExpr.Args[2]")
   428  		}
   429  	case "extract":
   430  		if err := n.Args[0].Restore(ctx); err != nil {
   431  			return errors.Annotatef(err, "An error occurred while restore FuncCallExpr.Args[0]")
   432  		}
   433  		ctx.WriteKeyWord(" FROM ")
   434  		if err := n.Args[1].Restore(ctx); err != nil {
   435  			return errors.Annotatef(err, "An error occurred while restore FuncCallExpr.Args[1]")
   436  		}
   437  	case "position":
   438  		if err := n.Args[0].Restore(ctx); err != nil {
   439  			return errors.Annotatef(err, "An error occurred while restore FuncCallExpr")
   440  		}
   441  		ctx.WriteKeyWord(" IN ")
   442  		if err := n.Args[1].Restore(ctx); err != nil {
   443  			return errors.Annotatef(err, "An error occurred while restore FuncCallExpr")
   444  		}
   445  	case "trim":
   446  		switch len(n.Args) {
   447  		case 3:
   448  			if err := n.Args[2].Restore(ctx); err != nil {
   449  				return errors.Annotatef(err, "An error occurred while restore FuncCallExpr.Args[2]")
   450  			}
   451  			ctx.WritePlain(" ")
   452  			fallthrough
   453  		case 2:
   454  			if expr, isValue := n.Args[1].(ValueExpr); !isValue || expr.GetValue() != nil {
   455  				if err := n.Args[1].Restore(ctx); err != nil {
   456  					return errors.Annotatef(err, "An error occurred while restore FuncCallExpr.Args[1]")
   457  				}
   458  				ctx.WritePlain(" ")
   459  			}
   460  			ctx.WriteKeyWord("FROM ")
   461  			fallthrough
   462  		case 1:
   463  			if err := n.Args[0].Restore(ctx); err != nil {
   464  				return errors.Annotatef(err, "An error occurred while restore FuncCallExpr.Args[0]")
   465  			}
   466  		}
   467  	case WeightString:
   468  		if err := n.Args[0].Restore(ctx); err != nil {
   469  			return errors.Annotatef(err, "An error occurred while restore FuncCallExpr.(WEIGHT_STRING).Args[0]")
   470  		}
   471  		if len(n.Args) == 3 {
   472  			ctx.WriteKeyWord(" AS ")
   473  			ctx.WriteKeyWord(n.Args[1].(ValueExpr).GetValue().(string))
   474  			ctx.WritePlain("(")
   475  			if err := n.Args[2].Restore(ctx); err != nil {
   476  				return errors.Annotatef(err, "An error occurred while restore FuncCallExpr.(WEIGHT_STRING).Args[2]")
   477  			}
   478  			ctx.WritePlain(")")
   479  		}
   480  	default:
   481  		for i, argv := range n.Args {
   482  			if i != 0 {
   483  				ctx.WritePlain(", ")
   484  			}
   485  			if err := argv.Restore(ctx); err != nil {
   486  				return errors.Annotatef(err, "An error occurred while restore FuncCallExpr.Args %d", i)
   487  			}
   488  		}
   489  	}
   490  	ctx.WritePlain(")")
   491  	return nil
   492  }
   493  
   494  func (n *FuncCallExpr) customRestore(ctx *format.RestoreCtx) (bool, error) {
   495  	var specialLiteral string
   496  	switch n.FnName.L {
   497  	case DateLiteral:
   498  		specialLiteral = "DATE "
   499  	case TimeLiteral:
   500  		specialLiteral = "TIME "
   501  	case TimestampLiteral:
   502  		specialLiteral = "TIMESTAMP "
   503  	}
   504  	if specialLiteral != "" {
   505  		ctx.WritePlain(specialLiteral)
   506  		if err := n.Args[0].Restore(ctx); err != nil {
   507  			return true, errors.Annotatef(err, "An error occurred while restore FuncCallExpr.Expr")
   508  		}
   509  		return true, nil
   510  	}
   511  	if n.FnName.L == JSONMemberOf {
   512  		if err := n.Args[0].Restore(ctx); err != nil {
   513  			return true, errors.Annotatef(err, "An error occurred while restore FuncCallExpr.(MEMBER OF).Args[0]")
   514  		}
   515  		ctx.WriteKeyWord(" MEMBER OF ")
   516  		ctx.WritePlain("(")
   517  		if err := n.Args[1].Restore(ctx); err != nil {
   518  			return true, errors.Annotatef(err, "An error occurred while restore FuncCallExpr.(MEMBER OF).Args[1]")
   519  		}
   520  		ctx.WritePlain(")")
   521  		return true, nil
   522  	}
   523  	return false, nil
   524  }
   525  
   526  // Format the ExprNode into a Writer.
   527  func (n *FuncCallExpr) Format(w io.Writer) {
   528  	if !n.specialFormatArgs(w) {
   529  		fmt.Fprintf(w, "%s(", n.FnName.L)
   530  		for i, arg := range n.Args {
   531  			arg.Format(w)
   532  			if i != len(n.Args)-1 {
   533  				fmt.Fprint(w, ", ")
   534  			}
   535  		}
   536  		fmt.Fprint(w, ")")
   537  	}
   538  }
   539  
   540  // specialFormatArgs formats argument list for some special functions.
   541  func (n *FuncCallExpr) specialFormatArgs(w io.Writer) bool {
   542  	switch n.FnName.L {
   543  	case DateAdd, DateSub, AddDate, SubDate:
   544  		fmt.Fprintf(w, "%s(", n.FnName.L)
   545  		n.Args[0].Format(w)
   546  		fmt.Fprint(w, ", INTERVAL ")
   547  		n.Args[1].Format(w)
   548  		fmt.Fprint(w, " ")
   549  		n.Args[2].Format(w)
   550  		fmt.Fprint(w, ")")
   551  		return true
   552  	case JSONMemberOf:
   553  		n.Args[0].Format(w)
   554  		fmt.Fprint(w, " MEMBER OF ")
   555  		fmt.Fprint(w, " (")
   556  		n.Args[1].Format(w)
   557  		fmt.Fprint(w, ")")
   558  		return true
   559  	case Extract:
   560  		fmt.Fprintf(w, "%s(", n.FnName.L)
   561  		n.Args[0].Format(w)
   562  		fmt.Fprint(w, " FROM ")
   563  		n.Args[1].Format(w)
   564  		fmt.Fprint(w, ")")
   565  		return true
   566  	}
   567  	return false
   568  }
   569  
   570  // Accept implements Node interface.
   571  func (n *FuncCallExpr) Accept(v Visitor) (Node, bool) {
   572  	newNode, skipChildren := v.Enter(n)
   573  	if skipChildren {
   574  		return v.Leave(newNode)
   575  	}
   576  	n = newNode.(*FuncCallExpr)
   577  	for i, val := range n.Args {
   578  		node, ok := val.Accept(v)
   579  		if !ok {
   580  			return n, false
   581  		}
   582  		n.Args[i] = node.(ExprNode)
   583  	}
   584  	return v.Leave(n)
   585  }
   586  
   587  // CastFunctionType is the type for cast function.
   588  type CastFunctionType int
   589  
   590  // CastFunction types
   591  const (
   592  	CastFunction CastFunctionType = iota + 1
   593  	CastConvertFunction
   594  	CastBinaryOperator
   595  )
   596  
   597  // FuncCastExpr is the cast function converting value to another type, e.g, cast(expr AS signed).
   598  // See https://dev.mysql.com/doc/refman/5.7/en/cast-functions.html
   599  type FuncCastExpr struct {
   600  	funcNode
   601  	// Expr is the expression to be converted.
   602  	Expr ExprNode
   603  	// Tp is the conversion type.
   604  	Tp *types.FieldType
   605  	// FunctionType is either Cast, Convert or Binary.
   606  	FunctionType CastFunctionType
   607  	// ExplicitCharSet is true when charset is explicit indicated.
   608  	ExplicitCharSet bool
   609  }
   610  
   611  // Restore implements Node interface.
   612  func (n *FuncCastExpr) Restore(ctx *format.RestoreCtx) error {
   613  	switch n.FunctionType {
   614  	case CastFunction:
   615  		ctx.WriteKeyWord("CAST")
   616  		ctx.WritePlain("(")
   617  		if err := n.Expr.Restore(ctx); err != nil {
   618  			return errors.Annotatef(err, "An error occurred while restore FuncCastExpr.Expr")
   619  		}
   620  		ctx.WriteKeyWord(" AS ")
   621  		n.Tp.RestoreAsCastType(ctx, n.ExplicitCharSet)
   622  		ctx.WritePlain(")")
   623  	case CastConvertFunction:
   624  		ctx.WriteKeyWord("CONVERT")
   625  		ctx.WritePlain("(")
   626  		if err := n.Expr.Restore(ctx); err != nil {
   627  			return errors.Annotatef(err, "An error occurred while restore FuncCastExpr.Expr")
   628  		}
   629  		ctx.WritePlain(", ")
   630  		n.Tp.RestoreAsCastType(ctx, n.ExplicitCharSet)
   631  		ctx.WritePlain(")")
   632  	case CastBinaryOperator:
   633  		ctx.WriteKeyWord("BINARY ")
   634  		if err := n.Expr.Restore(ctx); err != nil {
   635  			return errors.Annotatef(err, "An error occurred while restore FuncCastExpr.Expr")
   636  		}
   637  	}
   638  	return nil
   639  }
   640  
   641  // Format the ExprNode into a Writer.
   642  func (n *FuncCastExpr) Format(w io.Writer) {
   643  	switch n.FunctionType {
   644  	case CastFunction:
   645  		fmt.Fprint(w, "CAST(")
   646  		n.Expr.Format(w)
   647  		fmt.Fprint(w, " AS ")
   648  		n.Tp.FormatAsCastType(w, n.ExplicitCharSet)
   649  		fmt.Fprint(w, ")")
   650  	case CastConvertFunction:
   651  		fmt.Fprint(w, "CONVERT(")
   652  		n.Expr.Format(w)
   653  		fmt.Fprint(w, ", ")
   654  		n.Tp.FormatAsCastType(w, n.ExplicitCharSet)
   655  		fmt.Fprint(w, ")")
   656  	case CastBinaryOperator:
   657  		fmt.Fprint(w, "BINARY ")
   658  		n.Expr.Format(w)
   659  	}
   660  }
   661  
   662  // Accept implements Node Accept interface.
   663  func (n *FuncCastExpr) Accept(v Visitor) (Node, bool) {
   664  	newNode, skipChildren := v.Enter(n)
   665  	if skipChildren {
   666  		return v.Leave(newNode)
   667  	}
   668  	n = newNode.(*FuncCastExpr)
   669  	node, ok := n.Expr.Accept(v)
   670  	if !ok {
   671  		return n, false
   672  	}
   673  	n.Expr = node.(ExprNode)
   674  	return v.Leave(n)
   675  }
   676  
   677  // TrimDirectionType is the type for trim direction.
   678  type TrimDirectionType int
   679  
   680  const (
   681  	// TrimBothDefault trims from both direction by default.
   682  	TrimBothDefault TrimDirectionType = iota
   683  	// TrimBoth trims from both direction with explicit notation.
   684  	TrimBoth
   685  	// TrimLeading trims from left.
   686  	TrimLeading
   687  	// TrimTrailing trims from right.
   688  	TrimTrailing
   689  )
   690  
   691  // String implements fmt.Stringer interface.
   692  func (direction TrimDirectionType) String() string {
   693  	switch direction {
   694  	case TrimBoth, TrimBothDefault:
   695  		return "BOTH"
   696  	case TrimLeading:
   697  		return "LEADING"
   698  	case TrimTrailing:
   699  		return "TRAILING"
   700  	default:
   701  		return ""
   702  	}
   703  }
   704  
   705  // TrimDirectionExpr is an expression representing the trim direction used in the TRIM() function.
   706  type TrimDirectionExpr struct {
   707  	exprNode
   708  	// Direction is the trim direction
   709  	Direction TrimDirectionType
   710  }
   711  
   712  // Restore implements Node interface.
   713  func (n *TrimDirectionExpr) Restore(ctx *format.RestoreCtx) error {
   714  	ctx.WriteKeyWord(n.Direction.String())
   715  	return nil
   716  }
   717  
   718  // Format the ExprNode into a Writer.
   719  func (n *TrimDirectionExpr) Format(w io.Writer) {
   720  	fmt.Fprint(w, n.Direction.String())
   721  }
   722  
   723  // Accept implements Node Accept interface.
   724  func (n *TrimDirectionExpr) Accept(v Visitor) (Node, bool) {
   725  	newNode, skipChildren := v.Enter(n)
   726  	if skipChildren {
   727  		return v.Leave(newNode)
   728  	}
   729  	return v.Leave(n)
   730  }
   731  
   732  // DateArithType is type for DateArith type.
   733  type DateArithType byte
   734  
   735  const (
   736  	// DateArithAdd is to run adddate or date_add function option.
   737  	// See https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_adddate
   738  	// See https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_date-add
   739  	DateArithAdd DateArithType = iota + 1
   740  	// DateArithSub is to run subdate or date_sub function option.
   741  	// See https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_subdate
   742  	// See https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_date-sub
   743  	DateArithSub
   744  )
   745  
   746  const (
   747  	// AggFuncCount is the name of Count function.
   748  	AggFuncCount = "count"
   749  	// AggFuncSum is the name of Sum function.
   750  	AggFuncSum = "sum"
   751  	// AggFuncAvg is the name of Avg function.
   752  	AggFuncAvg = "avg"
   753  	// AggFuncFirstRow is the name of FirstRowColumn function.
   754  	AggFuncFirstRow = "firstrow"
   755  	// AggFuncMax is the name of max function.
   756  	AggFuncMax = "max"
   757  	// AggFuncMin is the name of min function.
   758  	AggFuncMin = "min"
   759  	// AggFuncGroupConcat is the name of group_concat function.
   760  	AggFuncGroupConcat = "group_concat"
   761  	// AggFuncBitOr is the name of bit_or function.
   762  	AggFuncBitOr = "bit_or"
   763  	// AggFuncBitXor is the name of bit_xor function.
   764  	AggFuncBitXor = "bit_xor"
   765  	// AggFuncBitAnd is the name of bit_and function.
   766  	AggFuncBitAnd = "bit_and"
   767  	// AggFuncVarPop is the name of var_pop function
   768  	AggFuncVarPop = "var_pop"
   769  	// AggFuncVarSamp is the name of var_samp function
   770  	AggFuncVarSamp = "var_samp"
   771  	// AggFuncStddevPop is the name of stddev_pop/std/stddev function
   772  	AggFuncStddevPop = "stddev_pop"
   773  	// AggFuncStddevSamp is the name of stddev_samp function
   774  	AggFuncStddevSamp = "stddev_samp"
   775  	// AggFuncJsonArrayagg is the name of json_arrayagg function
   776  	AggFuncJsonArrayagg = "json_arrayagg"
   777  	// AggFuncJsonObjectAgg is the name of json_objectagg function
   778  	AggFuncJsonObjectAgg = "json_objectagg"
   779  	// AggFuncApproxCountDistinct is the name of approx_count_distinct function.
   780  	AggFuncApproxCountDistinct = "approx_count_distinct"
   781  	// AggFuncApproxPercentile is the name of approx_percentile function.
   782  	AggFuncApproxPercentile = "approx_percentile"
   783  )
   784  
   785  // AggregateFuncExpr represents aggregate function expression.
   786  type AggregateFuncExpr struct {
   787  	funcNode
   788  	// F is the function name.
   789  	F string
   790  	// Args is the function args.
   791  	Args []ExprNode
   792  	// Distinct is true, function hence only aggregate distinct values.
   793  	// For example, column c1 values are "1", "2", "2",  "sum(c1)" is "5",
   794  	// but "sum(distinct c1)" is "3".
   795  	Distinct bool
   796  	// Order is only used in GROUP_CONCAT
   797  	Order *OrderByClause
   798  }
   799  
   800  // Restore implements Node interface.
   801  func (n *AggregateFuncExpr) Restore(ctx *format.RestoreCtx) error {
   802  	ctx.WriteKeyWord(n.F)
   803  	ctx.WritePlain("(")
   804  	if n.Distinct {
   805  		ctx.WriteKeyWord("DISTINCT ")
   806  	}
   807  	switch strings.ToLower(n.F) {
   808  	case "group_concat":
   809  		for i := 0; i < len(n.Args)-1; i++ {
   810  			if i != 0 {
   811  				ctx.WritePlain(", ")
   812  			}
   813  			if err := n.Args[i].Restore(ctx); err != nil {
   814  				return errors.Annotatef(err, "An error occurred while restore AggregateFuncExpr.Args[%d]", i)
   815  			}
   816  		}
   817  		if n.Order != nil {
   818  			ctx.WritePlain(" ")
   819  			if err := n.Order.Restore(ctx); err != nil {
   820  				return errors.Annotate(err, "An error occur while restore AggregateFuncExpr.Args Order")
   821  			}
   822  		}
   823  		ctx.WriteKeyWord(" SEPARATOR ")
   824  		if err := n.Args[len(n.Args)-1].Restore(ctx); err != nil {
   825  			return errors.Annotate(err, "An error occurred while restore AggregateFuncExpr.Args SEPARATOR")
   826  		}
   827  	default:
   828  		for i, argv := range n.Args {
   829  			if i != 0 {
   830  				ctx.WritePlain(", ")
   831  			}
   832  			if err := argv.Restore(ctx); err != nil {
   833  				return errors.Annotatef(err, "An error occurred while restore AggregateFuncExpr.Args[%d]", i)
   834  			}
   835  		}
   836  	}
   837  	ctx.WritePlain(")")
   838  	return nil
   839  }
   840  
   841  // Format the ExprNode into a Writer.
   842  func (n *AggregateFuncExpr) Format(w io.Writer) {
   843  	panic("Not implemented")
   844  }
   845  
   846  // Accept implements Node Accept interface.
   847  func (n *AggregateFuncExpr) Accept(v Visitor) (Node, bool) {
   848  	newNode, skipChildren := v.Enter(n)
   849  	if skipChildren {
   850  		return v.Leave(newNode)
   851  	}
   852  	n = newNode.(*AggregateFuncExpr)
   853  	for i, val := range n.Args {
   854  		node, ok := val.Accept(v)
   855  		if !ok {
   856  			return n, false
   857  		}
   858  		n.Args[i] = node.(ExprNode)
   859  	}
   860  	if n.Order != nil {
   861  		node, ok := n.Order.Accept(v)
   862  		if !ok {
   863  			return n, false
   864  		}
   865  		n.Order = node.(*OrderByClause)
   866  	}
   867  	return v.Leave(n)
   868  }
   869  
   870  const (
   871  	// WindowFuncRowNumber is the name of row_number function.
   872  	WindowFuncRowNumber = "row_number"
   873  	// WindowFuncRank is the name of rank function.
   874  	WindowFuncRank = "rank"
   875  	// WindowFuncDenseRank is the name of dense_rank function.
   876  	WindowFuncDenseRank = "dense_rank"
   877  	// WindowFuncCumeDist is the name of cume_dist function.
   878  	WindowFuncCumeDist = "cume_dist"
   879  	// WindowFuncPercentRank is the name of percent_rank function.
   880  	WindowFuncPercentRank = "percent_rank"
   881  	// WindowFuncNtile is the name of ntile function.
   882  	WindowFuncNtile = "ntile"
   883  	// WindowFuncLead is the name of lead function.
   884  	WindowFuncLead = "lead"
   885  	// WindowFuncLag is the name of lag function.
   886  	WindowFuncLag = "lag"
   887  	// WindowFuncFirstValue is the name of first_value function.
   888  	WindowFuncFirstValue = "first_value"
   889  	// WindowFuncLastValue is the name of last_value function.
   890  	WindowFuncLastValue = "last_value"
   891  	// WindowFuncNthValue is the name of nth_value function.
   892  	WindowFuncNthValue = "nth_value"
   893  )
   894  
   895  // WindowFuncExpr represents window function expression.
   896  type WindowFuncExpr struct {
   897  	funcNode
   898  
   899  	// Name is the function name.
   900  	Name string
   901  	// Args is the function args.
   902  	Args []ExprNode
   903  	// Distinct cannot be true for most window functions, except `max` and `min`.
   904  	// We need to raise error if it is not allowed to be true.
   905  	Distinct bool
   906  	// IgnoreNull indicates how to handle null value.
   907  	// MySQL only supports `RESPECT NULLS`, so we need to raise error if it is true.
   908  	IgnoreNull bool
   909  	// FromLast indicates the calculation direction of this window function.
   910  	// MySQL only supports calculation from first, so we need to raise error if it is true.
   911  	FromLast bool
   912  	// Spec is the specification of this window.
   913  	Spec WindowSpec
   914  }
   915  
   916  // Restore implements Node interface.
   917  func (n *WindowFuncExpr) Restore(ctx *format.RestoreCtx) error {
   918  	ctx.WriteKeyWord(n.Name)
   919  	ctx.WritePlain("(")
   920  	for i, v := range n.Args {
   921  		if i != 0 {
   922  			ctx.WritePlain(", ")
   923  		} else if n.Distinct {
   924  			ctx.WriteKeyWord("DISTINCT ")
   925  		}
   926  		if err := v.Restore(ctx); err != nil {
   927  			return errors.Annotatef(err, "An error occurred while restore WindowFuncExpr.Args[%d]", i)
   928  		}
   929  	}
   930  	ctx.WritePlain(")")
   931  	if n.FromLast {
   932  		ctx.WriteKeyWord(" FROM LAST")
   933  	}
   934  	if n.IgnoreNull {
   935  		ctx.WriteKeyWord(" IGNORE NULLS")
   936  	}
   937  	ctx.WriteKeyWord(" OVER ")
   938  	if err := n.Spec.Restore(ctx); err != nil {
   939  		return errors.Annotate(err, "An error occurred while restore WindowFuncExpr.Spec")
   940  	}
   941  
   942  	return nil
   943  }
   944  
   945  // Format formats the window function expression into a Writer.
   946  func (n *WindowFuncExpr) Format(w io.Writer) {
   947  	panic("Not implemented")
   948  }
   949  
   950  // Accept implements Node Accept interface.
   951  func (n *WindowFuncExpr) Accept(v Visitor) (Node, bool) {
   952  	newNode, skipChildren := v.Enter(n)
   953  	if skipChildren {
   954  		return v.Leave(newNode)
   955  	}
   956  	n = newNode.(*WindowFuncExpr)
   957  	for i, val := range n.Args {
   958  		node, ok := val.Accept(v)
   959  		if !ok {
   960  			return n, false
   961  		}
   962  		n.Args[i] = node.(ExprNode)
   963  	}
   964  	node, ok := n.Spec.Accept(v)
   965  	if !ok {
   966  		return n, false
   967  	}
   968  	n.Spec = *node.(*WindowSpec)
   969  	return v.Leave(n)
   970  }
   971  
   972  // TimeUnitType is the type for time and timestamp units.
   973  type TimeUnitType int
   974  
   975  const (
   976  	// TimeUnitInvalid is a placeholder for an invalid time or timestamp unit
   977  	TimeUnitInvalid TimeUnitType = iota
   978  	// TimeUnitMicrosecond is the time or timestamp unit MICROSECOND.
   979  	TimeUnitMicrosecond
   980  	// TimeUnitSecond is the time or timestamp unit SECOND.
   981  	TimeUnitSecond
   982  	// TimeUnitMinute is the time or timestamp unit MINUTE.
   983  	TimeUnitMinute
   984  	// TimeUnitHour is the time or timestamp unit HOUR.
   985  	TimeUnitHour
   986  	// TimeUnitDay is the time or timestamp unit DAY.
   987  	TimeUnitDay
   988  	// TimeUnitWeek is the time or timestamp unit WEEK.
   989  	TimeUnitWeek
   990  	// TimeUnitMonth is the time or timestamp unit MONTH.
   991  	TimeUnitMonth
   992  	// TimeUnitQuarter is the time or timestamp unit QUARTER.
   993  	TimeUnitQuarter
   994  	// TimeUnitYear is the time or timestamp unit YEAR.
   995  	TimeUnitYear
   996  	// TimeUnitSecondMicrosecond is the time unit SECOND_MICROSECOND.
   997  	TimeUnitSecondMicrosecond
   998  	// TimeUnitMinuteMicrosecond is the time unit MINUTE_MICROSECOND.
   999  	TimeUnitMinuteMicrosecond
  1000  	// TimeUnitMinuteSecond is the time unit MINUTE_SECOND.
  1001  	TimeUnitMinuteSecond
  1002  	// TimeUnitHourMicrosecond is the time unit HOUR_MICROSECOND.
  1003  	TimeUnitHourMicrosecond
  1004  	// TimeUnitHourSecond is the time unit HOUR_SECOND.
  1005  	TimeUnitHourSecond
  1006  	// TimeUnitHourMinute is the time unit HOUR_MINUTE.
  1007  	TimeUnitHourMinute
  1008  	// TimeUnitDayMicrosecond is the time unit DAY_MICROSECOND.
  1009  	TimeUnitDayMicrosecond
  1010  	// TimeUnitDaySecond is the time unit DAY_SECOND.
  1011  	TimeUnitDaySecond
  1012  	// TimeUnitDayMinute is the time unit DAY_MINUTE.
  1013  	TimeUnitDayMinute
  1014  	// TimeUnitDayHour is the time unit DAY_HOUR.
  1015  	TimeUnitDayHour
  1016  	// TimeUnitYearMonth is the time unit YEAR_MONTH.
  1017  	TimeUnitYearMonth
  1018  )
  1019  
  1020  // String implements fmt.Stringer interface.
  1021  func (unit TimeUnitType) String() string {
  1022  	switch unit {
  1023  	case TimeUnitMicrosecond:
  1024  		return "MICROSECOND"
  1025  	case TimeUnitSecond:
  1026  		return "SECOND"
  1027  	case TimeUnitMinute:
  1028  		return "MINUTE"
  1029  	case TimeUnitHour:
  1030  		return "HOUR"
  1031  	case TimeUnitDay:
  1032  		return "DAY"
  1033  	case TimeUnitWeek:
  1034  		return "WEEK"
  1035  	case TimeUnitMonth:
  1036  		return "MONTH"
  1037  	case TimeUnitQuarter:
  1038  		return "QUARTER"
  1039  	case TimeUnitYear:
  1040  		return "YEAR"
  1041  	case TimeUnitSecondMicrosecond:
  1042  		return "SECOND_MICROSECOND"
  1043  	case TimeUnitMinuteMicrosecond:
  1044  		return "MINUTE_MICROSECOND"
  1045  	case TimeUnitMinuteSecond:
  1046  		return "MINUTE_SECOND"
  1047  	case TimeUnitHourMicrosecond:
  1048  		return "HOUR_MICROSECOND"
  1049  	case TimeUnitHourSecond:
  1050  		return "HOUR_SECOND"
  1051  	case TimeUnitHourMinute:
  1052  		return "HOUR_MINUTE"
  1053  	case TimeUnitDayMicrosecond:
  1054  		return "DAY_MICROSECOND"
  1055  	case TimeUnitDaySecond:
  1056  		return "DAY_SECOND"
  1057  	case TimeUnitDayMinute:
  1058  		return "DAY_MINUTE"
  1059  	case TimeUnitDayHour:
  1060  		return "DAY_HOUR"
  1061  	case TimeUnitYearMonth:
  1062  		return "YEAR_MONTH"
  1063  	default:
  1064  		return ""
  1065  	}
  1066  }
  1067  
  1068  // Duration represented by this unit.
  1069  // Returns error if the time unit is not a fixed time interval (such as MONTH)
  1070  // or a composite unit (such as MINUTE_SECOND).
  1071  func (unit TimeUnitType) Duration() (time.Duration, error) {
  1072  	switch unit {
  1073  	case TimeUnitMicrosecond:
  1074  		return time.Microsecond, nil
  1075  	case TimeUnitSecond:
  1076  		return time.Second, nil
  1077  	case TimeUnitMinute:
  1078  		return time.Minute, nil
  1079  	case TimeUnitHour:
  1080  		return time.Hour, nil
  1081  	case TimeUnitDay:
  1082  		return time.Hour * 24, nil
  1083  	case TimeUnitWeek:
  1084  		return time.Hour * 24 * 7, nil
  1085  	case TimeUnitMonth, TimeUnitQuarter, TimeUnitYear:
  1086  		return 0, errors.Errorf("%s is not a constant time interval and cannot be used here", unit)
  1087  	default:
  1088  		return 0, errors.Errorf("%s is a composite time unit and is not supported yet", unit)
  1089  	}
  1090  }
  1091  
  1092  // TimeUnitExpr is an expression representing a time or timestamp unit.
  1093  type TimeUnitExpr struct {
  1094  	exprNode
  1095  	// Unit is the time or timestamp unit.
  1096  	Unit TimeUnitType
  1097  }
  1098  
  1099  // Restore implements Node interface.
  1100  func (n *TimeUnitExpr) Restore(ctx *format.RestoreCtx) error {
  1101  	ctx.WriteKeyWord(n.Unit.String())
  1102  	return nil
  1103  }
  1104  
  1105  // Format the ExprNode into a Writer.
  1106  func (n *TimeUnitExpr) Format(w io.Writer) {
  1107  	fmt.Fprint(w, n.Unit.String())
  1108  }
  1109  
  1110  // Accept implements Node Accept interface.
  1111  func (n *TimeUnitExpr) Accept(v Visitor) (Node, bool) {
  1112  	newNode, skipChildren := v.Enter(n)
  1113  	if skipChildren {
  1114  		return v.Leave(newNode)
  1115  	}
  1116  	return v.Leave(n)
  1117  }
  1118  
  1119  // GetFormatSelectorType is the type for the first argument of GET_FORMAT() function.
  1120  type GetFormatSelectorType int
  1121  
  1122  const (
  1123  	// GetFormatSelectorDate is the GET_FORMAT selector DATE.
  1124  	GetFormatSelectorDate GetFormatSelectorType = iota + 1
  1125  	// GetFormatSelectorTime is the GET_FORMAT selector TIME.
  1126  	GetFormatSelectorTime
  1127  	// GetFormatSelectorDatetime is the GET_FORMAT selector DATETIME and TIMESTAMP.
  1128  	GetFormatSelectorDatetime
  1129  )
  1130  
  1131  // GetFormatSelectorExpr is an expression used as the first argument of GET_FORMAT() function.
  1132  type GetFormatSelectorExpr struct {
  1133  	exprNode
  1134  	// Selector is the GET_FORMAT() selector.
  1135  	Selector GetFormatSelectorType
  1136  }
  1137  
  1138  // String implements fmt.Stringer interface.
  1139  func (selector GetFormatSelectorType) String() string {
  1140  	switch selector {
  1141  	case GetFormatSelectorDate:
  1142  		return "DATE"
  1143  	case GetFormatSelectorTime:
  1144  		return "TIME"
  1145  	case GetFormatSelectorDatetime:
  1146  		return "DATETIME"
  1147  	default:
  1148  		return ""
  1149  	}
  1150  }
  1151  
  1152  // Restore implements Node interface.
  1153  func (n *GetFormatSelectorExpr) Restore(ctx *format.RestoreCtx) error {
  1154  	ctx.WriteKeyWord(n.Selector.String())
  1155  	return nil
  1156  }
  1157  
  1158  // Format the ExprNode into a Writer.
  1159  func (n *GetFormatSelectorExpr) Format(w io.Writer) {
  1160  	fmt.Fprint(w, n.Selector.String())
  1161  }
  1162  
  1163  // Accept implements Node Accept interface.
  1164  func (n *GetFormatSelectorExpr) Accept(v Visitor) (Node, bool) {
  1165  	newNode, skipChildren := v.Enter(n)
  1166  	if skipChildren {
  1167  		return v.Leave(newNode)
  1168  	}
  1169  	return v.Leave(n)
  1170  }