github.com/cockroachdb/cockroachdb-parser@v0.23.3-0.20240213214944-911057d40c9a/pkg/sql/sem/tree/expr.go (about) 1 // Copyright 2015 The Cockroach Authors. 2 // 3 // Use of this software is governed by the Business Source License 4 // included in the file licenses/BSL.txt. 5 // 6 // As of the Change Date specified in that file, in accordance with 7 // the Business Source License, use of this software will be governed 8 // by the Apache License, Version 2.0, included in the file 9 // licenses/APL.txt. 10 11 package tree 12 13 import ( 14 "bytes" 15 "context" 16 "fmt" 17 "strconv" 18 19 "github.com/cockroachdb/cockroachdb-parser/pkg/sql/lex" 20 "github.com/cockroachdb/cockroachdb-parser/pkg/sql/pgwire/pgcode" 21 "github.com/cockroachdb/cockroachdb-parser/pkg/sql/pgwire/pgerror" 22 "github.com/cockroachdb/cockroachdb-parser/pkg/sql/sem/tree/treebin" 23 "github.com/cockroachdb/cockroachdb-parser/pkg/sql/sem/tree/treecmp" 24 "github.com/cockroachdb/cockroachdb-parser/pkg/sql/types" 25 "github.com/cockroachdb/cockroachdb-parser/pkg/util/iterutil" 26 "github.com/cockroachdb/errors" 27 "github.com/cockroachdb/redact" 28 ) 29 30 // Expr represents an expression. 31 type Expr interface { 32 fmt.Stringer 33 NodeFormatter 34 // Walk recursively walks all children using WalkExpr. If any children are changed, it returns a 35 // copy of this node updated to point to the new children. Otherwise the receiver is returned. 36 // For childless (leaf) Exprs, its implementation is empty. 37 Walk(Visitor) Expr 38 // TypeCheck transforms the Expr into a well-typed TypedExpr, which further permits 39 // evaluation and type introspection, or an error if the expression cannot be well-typed. 40 // When type checking is complete, if no error was reported, the expression and all 41 // sub-expressions will be guaranteed to be well-typed, meaning that the method effectively 42 // maps the Expr tree into a TypedExpr tree. 43 // 44 // The semaCtx parameter defines the context in which to perform type checking. 45 // The desired parameter hints the desired type that the method's caller wants from 46 // the resulting TypedExpr. It is not valid to call TypeCheck with a nil desired 47 // type. Instead, call it with wildcard type types.Any if no specific type is 48 // desired. This restriction is also true of most methods and functions related 49 // to type checking. 50 TypeCheck(ctx context.Context, semaCtx *SemaContext, desired *types.T) (TypedExpr, error) 51 } 52 53 // TypedExpr represents a well-typed expression. 54 type TypedExpr interface { 55 Expr 56 57 // ResolvedType provides the type of the TypedExpr, which is the type of Datum 58 // that the TypedExpr will return when evaluated. 59 ResolvedType() *types.T 60 61 // Eval evaluates an SQL expression. Expression evaluation is a 62 // mostly straightforward walk over the parse tree. The only 63 // significant complexity is the handling of types and implicit 64 // conversions. See binOps and cmpOps for more details. Note that 65 // expression evaluation returns an error if certain node types are 66 // encountered: Placeholder, VarName (and related UnqualifiedStar, 67 // UnresolvedName and AllColumnsSelector) or Subquery. These nodes 68 // should be replaced prior to expression evaluation by an 69 // appropriate WalkExpr. For example, Placeholder should be replaced 70 // by the argument passed from the client. 71 Eval(context.Context, ExprEvaluator) (Datum, error) 72 } 73 74 // VariableExpr is an Expr that may change per row. It is used to 75 // signal the evaluation/simplification machinery that the underlying 76 // Expr is not constant. 77 type VariableExpr interface { 78 Expr 79 Variable() 80 } 81 82 var _ VariableExpr = &IndexedVar{} 83 var _ VariableExpr = &Subquery{} 84 var _ VariableExpr = UnqualifiedStar{} 85 var _ VariableExpr = &UnresolvedName{} 86 var _ VariableExpr = &AllColumnsSelector{} 87 var _ VariableExpr = &ColumnItem{} 88 89 // operatorExpr is used to identify expression types that involve operators; 90 // used by exprStrWithParen. 91 type operatorExpr interface { 92 Expr 93 operatorExpr() 94 } 95 96 var _ operatorExpr = &AndExpr{} 97 var _ operatorExpr = &OrExpr{} 98 var _ operatorExpr = &NotExpr{} 99 var _ operatorExpr = &IsNullExpr{} 100 var _ operatorExpr = &IsNotNullExpr{} 101 var _ operatorExpr = &BinaryExpr{} 102 var _ operatorExpr = &UnaryExpr{} 103 var _ operatorExpr = &ComparisonExpr{} 104 var _ operatorExpr = &RangeCond{} 105 var _ operatorExpr = &IsOfTypeExpr{} 106 107 // Operator is used to identify Operators; used in sql.y. 108 type Operator interface { 109 Operator() 110 } 111 112 var _ Operator = (*UnaryOperator)(nil) 113 var _ Operator = (*treebin.BinaryOperator)(nil) 114 var _ Operator = (*treecmp.ComparisonOperator)(nil) 115 116 // SubqueryExpr is an interface used to identify an expression as a subquery. 117 // It is implemented by both tree.Subquery and optbuilder.subquery, and is 118 // used in TypeCheck. 119 type SubqueryExpr interface { 120 Expr 121 SubqueryExpr() 122 } 123 124 var _ SubqueryExpr = &Subquery{} 125 126 // exprFmtWithParen is a variant of Format() which adds a set of outer parens 127 // if the expression involves an operator. It is used internally when the 128 // expression is part of another expression and we know it is preceded or 129 // followed by an operator. 130 func exprFmtWithParen(ctx *FmtCtx, e Expr) { 131 if _, ok := e.(operatorExpr); ok { 132 ctx.WriteByte('(') 133 ctx.FormatNode(e) 134 ctx.WriteByte(')') 135 } else { 136 ctx.FormatNode(e) 137 } 138 } 139 140 // typeAnnotation is an embeddable struct to provide a TypedExpr with a dynamic 141 // type annotation. 142 type typeAnnotation struct { 143 typ *types.T 144 } 145 146 func (ta typeAnnotation) ResolvedType() *types.T { 147 ta.assertTyped() 148 return ta.typ 149 } 150 151 func (ta typeAnnotation) assertTyped() { 152 if ta.typ == nil { 153 panic(errors.AssertionFailedf( 154 "ReturnType called on TypedExpr with empty typeAnnotation. " + 155 "Was the underlying Expr type-checked before asserting a type of TypedExpr?")) 156 } 157 } 158 159 // AndExpr represents an AND expression. 160 type AndExpr struct { 161 Left, Right Expr 162 163 typeAnnotation 164 } 165 166 func (*AndExpr) operatorExpr() {} 167 168 func binExprFmtWithParen(ctx *FmtCtx, e1 Expr, op string, e2 Expr, pad bool) { 169 exprFmtWithParen(ctx, e1) 170 if pad { 171 ctx.WriteByte(' ') 172 } 173 ctx.WriteString(op) 174 if pad { 175 ctx.WriteByte(' ') 176 } 177 exprFmtWithParen(ctx, e2) 178 } 179 180 func binExprFmtWithParenAndSubOp(ctx *FmtCtx, e1 Expr, subOp, op string, e2 Expr) { 181 exprFmtWithParen(ctx, e1) 182 ctx.WriteByte(' ') 183 if subOp != "" { 184 ctx.WriteString(subOp) 185 ctx.WriteByte(' ') 186 } 187 ctx.WriteString(op) 188 ctx.WriteByte(' ') 189 exprFmtWithParen(ctx, e2) 190 } 191 192 // Format implements the NodeFormatter interface. 193 func (node *AndExpr) Format(ctx *FmtCtx) { 194 binExprFmtWithParen(ctx, node.Left, "AND", node.Right, true) 195 } 196 197 // NewTypedAndExpr returns a new AndExpr that is verified to be well-typed. 198 func NewTypedAndExpr(left, right TypedExpr) *AndExpr { 199 node := &AndExpr{Left: left, Right: right} 200 node.typ = types.Bool 201 return node 202 } 203 204 // TypedLeft returns the AndExpr's left expression as a TypedExpr. 205 func (node *AndExpr) TypedLeft() TypedExpr { 206 return node.Left.(TypedExpr) 207 } 208 209 // TypedRight returns the AndExpr's right expression as a TypedExpr. 210 func (node *AndExpr) TypedRight() TypedExpr { 211 return node.Right.(TypedExpr) 212 } 213 214 // OrExpr represents an OR expression. 215 type OrExpr struct { 216 Left, Right Expr 217 218 typeAnnotation 219 } 220 221 func (*OrExpr) operatorExpr() {} 222 223 // Format implements the NodeFormatter interface. 224 func (node *OrExpr) Format(ctx *FmtCtx) { 225 binExprFmtWithParen(ctx, node.Left, "OR", node.Right, true) 226 } 227 228 // NewTypedOrExpr returns a new OrExpr that is verified to be well-typed. 229 func NewTypedOrExpr(left, right TypedExpr) *OrExpr { 230 node := &OrExpr{Left: left, Right: right} 231 node.typ = types.Bool 232 return node 233 } 234 235 // TypedLeft returns the OrExpr's left expression as a TypedExpr. 236 func (node *OrExpr) TypedLeft() TypedExpr { 237 return node.Left.(TypedExpr) 238 } 239 240 // TypedRight returns the OrExpr's right expression as a TypedExpr. 241 func (node *OrExpr) TypedRight() TypedExpr { 242 return node.Right.(TypedExpr) 243 } 244 245 // NotExpr represents a NOT expression. 246 type NotExpr struct { 247 Expr Expr 248 249 typeAnnotation 250 } 251 252 func (*NotExpr) operatorExpr() {} 253 254 // Format implements the NodeFormatter interface. 255 func (node *NotExpr) Format(ctx *FmtCtx) { 256 ctx.WriteString("NOT ") 257 exprFmtWithParen(ctx, node.Expr) 258 } 259 260 // NewTypedNotExpr returns a new NotExpr that is verified to be well-typed. 261 func NewTypedNotExpr(expr TypedExpr) *NotExpr { 262 node := &NotExpr{Expr: expr} 263 node.typ = types.Bool 264 return node 265 } 266 267 // TypedInnerExpr returns the NotExpr's inner expression as a TypedExpr. 268 func (node *NotExpr) TypedInnerExpr() TypedExpr { 269 return node.Expr.(TypedExpr) 270 } 271 272 // IsNullExpr represents an IS NULL expression. This is equivalent to IS NOT 273 // DISTINCT FROM NULL, except when the input is a tuple. 274 type IsNullExpr struct { 275 Expr Expr 276 277 typeAnnotation 278 } 279 280 func (*IsNullExpr) operatorExpr() {} 281 282 // Format implements the NodeFormatter interface. 283 func (node *IsNullExpr) Format(ctx *FmtCtx) { 284 exprFmtWithParen(ctx, node.Expr) 285 ctx.WriteString(" IS NULL") 286 } 287 288 // NewTypedIsNullExpr returns a new IsNullExpr that is verified to be 289 // well-typed. 290 func NewTypedIsNullExpr(expr TypedExpr) *IsNullExpr { 291 node := &IsNullExpr{Expr: expr} 292 node.typ = types.Bool 293 return node 294 } 295 296 // TypedInnerExpr returns the IsNullExpr's inner expression as a TypedExpr. 297 func (node *IsNullExpr) TypedInnerExpr() TypedExpr { 298 return node.Expr.(TypedExpr) 299 } 300 301 // IsNotNullExpr represents an IS NOT NULL expression. This is equivalent to IS 302 // DISTINCT FROM NULL, except when the input is a tuple. 303 type IsNotNullExpr struct { 304 Expr Expr 305 306 typeAnnotation 307 } 308 309 func (*IsNotNullExpr) operatorExpr() {} 310 311 // Format implements the NodeFormatter interface. 312 func (node *IsNotNullExpr) Format(ctx *FmtCtx) { 313 exprFmtWithParen(ctx, node.Expr) 314 ctx.WriteString(" IS NOT NULL") 315 } 316 317 // NewTypedIsNotNullExpr returns a new IsNotNullExpr that is verified to be 318 // well-typed. 319 func NewTypedIsNotNullExpr(expr TypedExpr) *IsNotNullExpr { 320 node := &IsNotNullExpr{Expr: expr} 321 node.typ = types.Bool 322 return node 323 } 324 325 // TypedInnerExpr returns the IsNotNullExpr's inner expression as a TypedExpr. 326 func (node *IsNotNullExpr) TypedInnerExpr() TypedExpr { 327 return node.Expr.(TypedExpr) 328 } 329 330 // ParenExpr represents a parenthesized expression. 331 type ParenExpr struct { 332 Expr Expr 333 334 typeAnnotation 335 } 336 337 // Format implements the NodeFormatter interface. 338 func (node *ParenExpr) Format(ctx *FmtCtx) { 339 ctx.WriteByte('(') 340 ctx.FormatNode(node.Expr) 341 ctx.WriteByte(')') 342 } 343 344 // TypedInnerExpr returns the ParenExpr's inner expression as a TypedExpr. 345 func (node *ParenExpr) TypedInnerExpr() TypedExpr { 346 return node.Expr.(TypedExpr) 347 } 348 349 // StripParens strips any parentheses surrounding an expression and 350 // returns the inner expression. For instance: 351 // 352 // 1 -> 1 353 // (1) -> 1 354 // 355 // ((1)) -> 1 356 func StripParens(expr Expr) Expr { 357 if p, ok := expr.(*ParenExpr); ok { 358 return StripParens(p.Expr) 359 } 360 return expr 361 } 362 363 // ComparisonExpr represents a two-value comparison expression. 364 type ComparisonExpr struct { 365 Operator treecmp.ComparisonOperator 366 SubOperator treecmp.ComparisonOperator // used for array operators (when Operator is Any, Some, or All) 367 Left, Right Expr 368 369 typeAnnotation 370 Op *CmpOp 371 } 372 373 func (*ComparisonExpr) operatorExpr() {} 374 375 // Format implements the NodeFormatter interface. 376 func (node *ComparisonExpr) Format(ctx *FmtCtx) { 377 opStr := node.Operator.String() 378 // IS and IS NOT are equivalent to IS NOT DISTINCT FROM and IS DISTINCT 379 // FROM, respectively, when the RHS is true or false. We prefer the less 380 // verbose IS and IS NOT in those cases, unless we are in FmtHideConstants 381 // mode. In that mode we need the more verbose form in order to be able 382 // to re-parse the statement when reporting telemetry. 383 if !ctx.HasFlags(FmtHideConstants) { 384 if node.Operator.Symbol == treecmp.IsDistinctFrom && (node.Right == DBoolTrue || node.Right == DBoolFalse) { 385 opStr = "IS NOT" 386 } else if node.Operator.Symbol == treecmp.IsNotDistinctFrom && (node.Right == DBoolTrue || node.Right == DBoolFalse) { 387 opStr = "IS" 388 } 389 } 390 if node.Operator.Symbol.HasSubOperator() { 391 binExprFmtWithParenAndSubOp(ctx, node.Left, node.SubOperator.String(), opStr, node.Right) 392 } else { 393 binExprFmtWithParen(ctx, node.Left, opStr, node.Right, true) 394 } 395 } 396 397 // NewTypedComparisonExpr returns a new ComparisonExpr that is verified to be well-typed. 398 func NewTypedComparisonExpr(op treecmp.ComparisonOperator, left, right TypedExpr) *ComparisonExpr { 399 node := &ComparisonExpr{Operator: op, Left: left, Right: right} 400 node.typ = types.Bool 401 MemoizeComparisonExprOp(node) 402 return node 403 } 404 405 // NewTypedComparisonExprWithSubOp returns a new ComparisonExpr that is verified to be well-typed. 406 func NewTypedComparisonExprWithSubOp( 407 op, subOp treecmp.ComparisonOperator, left, right TypedExpr, 408 ) *ComparisonExpr { 409 node := &ComparisonExpr{Operator: op, SubOperator: subOp, Left: left, Right: right} 410 node.typ = types.Bool 411 MemoizeComparisonExprOp(node) 412 return node 413 } 414 415 // NewTypedIndirectionExpr returns a new IndirectionExpr that is verified to be well-typed. 416 func NewTypedIndirectionExpr(expr, index TypedExpr, typ *types.T) *IndirectionExpr { 417 node := &IndirectionExpr{ 418 Expr: expr, 419 Indirection: ArraySubscripts{&ArraySubscript{Begin: index}}, 420 } 421 node.typ = typ 422 return node 423 } 424 425 // NewTypedCollateExpr returns a new CollateExpr that is verified to be well-typed. 426 func NewTypedCollateExpr(expr TypedExpr, locale string) *CollateExpr { 427 node := &CollateExpr{ 428 Expr: expr, 429 Locale: locale, 430 } 431 node.typ = types.MakeCollatedString(types.String, locale) 432 return node 433 } 434 435 // NewTypedArrayFlattenExpr returns a new ArrayFlattenExpr that is verified to be well-typed. 436 func NewTypedArrayFlattenExpr(input Expr) *ArrayFlatten { 437 inputTyp := input.(TypedExpr).ResolvedType() 438 node := &ArrayFlatten{ 439 Subquery: input, 440 } 441 node.typ = types.MakeArray(inputTyp) 442 return node 443 } 444 445 // NewTypedIfErrExpr returns a new IfErrExpr that is verified to be well-typed. 446 func NewTypedIfErrExpr(cond, orElse, errCode TypedExpr) *IfErrExpr { 447 node := &IfErrExpr{ 448 Cond: cond, 449 Else: orElse, 450 ErrCode: errCode, 451 } 452 if orElse == nil { 453 node.typ = types.Bool 454 } else { 455 node.typ = cond.ResolvedType() 456 } 457 return node 458 } 459 460 // MemoizeComparisonExprOp populates the Op field of the ComparisonExpr. 461 // 462 // TODO(ajwerner): It feels dangerous to leave this to the caller to set. 463 // Should we rework the construction and access to the underlying Op to 464 // enforce safety? 465 func MemoizeComparisonExprOp(node *ComparisonExpr) { 466 fOp, fLeft, fRight, _, _ := FoldComparisonExpr(node.Operator, node.Left, node.Right) 467 leftRet, rightRet := fLeft.(TypedExpr).ResolvedType(), fRight.(TypedExpr).ResolvedType() 468 switch node.Operator.Symbol { 469 case treecmp.Any, treecmp.Some, treecmp.All: 470 // Array operators memoize the SubOperator's CmpOp. 471 fOp, _, _, _, _ = FoldComparisonExpr(node.SubOperator, nil, nil) 472 // The right operand is either an array or a tuple/subquery. 473 switch rightRet.Family() { 474 case types.ArrayFamily: 475 // For example: 476 // x = ANY(ARRAY[1,2]) 477 rightRet = rightRet.ArrayContents() 478 case types.TupleFamily: 479 // For example: 480 // x = ANY(SELECT y FROM t) 481 // x = ANY(1,2) 482 if len(rightRet.TupleContents()) > 0 { 483 rightRet = rightRet.TupleContents()[0] 484 } else { 485 rightRet = leftRet 486 } 487 } 488 } 489 490 fn, ok := CmpOps[fOp.Symbol].LookupImpl(leftRet, rightRet) 491 if !ok { 492 panic(errors.AssertionFailedf("lookup for ComparisonExpr %s's CmpOp failed (%s(%s,%s))", 493 AsStringWithFlags(node, FmtShowTypes), redact.Safe(fOp.String()), 494 leftRet.SQLStringForError(), rightRet.SQLStringForError(), 495 )) 496 } 497 node.Op = fn 498 } 499 500 // TypedLeft returns the ComparisonExpr's left expression as a TypedExpr. 501 func (node *ComparisonExpr) TypedLeft() TypedExpr { 502 return node.Left.(TypedExpr) 503 } 504 505 // TypedRight returns the ComparisonExpr's right expression as a TypedExpr. 506 func (node *ComparisonExpr) TypedRight() TypedExpr { 507 return node.Right.(TypedExpr) 508 } 509 510 // RangeCond represents a BETWEEN [SYMMETRIC] or a NOT BETWEEN [SYMMETRIC] 511 // expression. 512 type RangeCond struct { 513 Not bool 514 Symmetric bool 515 Left Expr 516 From, To Expr 517 518 // Typed version of Left for the comparison with To (where it may be 519 // type-checked differently). After type-checking, Left is set to the typed 520 // version for the comparison with From, and leftTo is set to the typed 521 // version for the comparison with To. 522 leftTo TypedExpr 523 524 typeAnnotation 525 } 526 527 func (*RangeCond) operatorExpr() {} 528 529 // Format implements the NodeFormatter interface. 530 func (node *RangeCond) Format(ctx *FmtCtx) { 531 notStr := " BETWEEN " 532 if node.Not { 533 notStr = " NOT BETWEEN " 534 } 535 exprFmtWithParen(ctx, node.Left) 536 ctx.WriteString(notStr) 537 if node.Symmetric { 538 ctx.WriteString("SYMMETRIC ") 539 } 540 binExprFmtWithParen(ctx, node.From, "AND", node.To, true) 541 } 542 543 // TypedLeftFrom returns the RangeCond's left expression as a TypedExpr, in the 544 // context of a comparison with TypedFrom(). 545 func (node *RangeCond) TypedLeftFrom() TypedExpr { 546 return node.Left.(TypedExpr) 547 } 548 549 // TypedFrom returns the RangeCond's from expression as a TypedExpr. 550 func (node *RangeCond) TypedFrom() TypedExpr { 551 return node.From.(TypedExpr) 552 } 553 554 // TypedLeftTo returns the RangeCond's left expression as a TypedExpr, in the 555 // context of a comparison with TypedTo(). 556 func (node *RangeCond) TypedLeftTo() TypedExpr { 557 return node.leftTo 558 } 559 560 // TypedTo returns the RangeCond's to expression as a TypedExpr. 561 func (node *RangeCond) TypedTo() TypedExpr { 562 return node.To.(TypedExpr) 563 } 564 565 // IsOfTypeExpr represents an IS {,NOT} OF (type_list) expression. 566 type IsOfTypeExpr struct { 567 Not bool 568 Expr Expr 569 Types []ResolvableTypeReference 570 571 resolvedTypes []*types.T 572 573 typeAnnotation 574 } 575 576 func (*IsOfTypeExpr) operatorExpr() {} 577 578 // ResolvedTypes returns a slice of resolved types corresponding 579 // to the Types slice of unresolved types. It may only be accessed 580 // after typechecking. 581 func (node *IsOfTypeExpr) ResolvedTypes() []*types.T { 582 if node.resolvedTypes == nil { 583 panic("ResolvedTypes called on an IsOfTypeExpr before typechecking") 584 } 585 return node.resolvedTypes 586 } 587 588 // Format implements the NodeFormatter interface. 589 func (node *IsOfTypeExpr) Format(ctx *FmtCtx) { 590 exprFmtWithParen(ctx, node.Expr) 591 ctx.WriteString(" IS") 592 if node.Not { 593 ctx.WriteString(" NOT") 594 } 595 ctx.WriteString(" OF (") 596 for i, t := range node.Types { 597 if i > 0 { 598 ctx.WriteString(", ") 599 } 600 ctx.FormatTypeReference(t) 601 } 602 ctx.WriteByte(')') 603 } 604 605 // IfErrExpr represents an IFERROR expression. 606 type IfErrExpr struct { 607 Cond Expr 608 Else Expr 609 ErrCode Expr 610 611 typeAnnotation 612 } 613 614 // Format implements the NodeFormatter interface. 615 func (node *IfErrExpr) Format(ctx *FmtCtx) { 616 if node.Else != nil { 617 ctx.WriteString("IFERROR(") 618 } else { 619 ctx.WriteString("ISERROR(") 620 } 621 ctx.FormatNode(node.Cond) 622 if node.Else != nil { 623 ctx.WriteString(", ") 624 ctx.FormatNode(node.Else) 625 } 626 if node.ErrCode != nil { 627 ctx.WriteString(", ") 628 ctx.FormatNode(node.ErrCode) 629 } 630 ctx.WriteByte(')') 631 } 632 633 // IfExpr represents an IF expression. 634 type IfExpr struct { 635 Cond Expr 636 True Expr 637 Else Expr 638 639 typeAnnotation 640 } 641 642 // TypedTrueExpr returns the IfExpr's True expression as a TypedExpr. 643 func (node *IfExpr) TypedTrueExpr() TypedExpr { 644 return node.True.(TypedExpr) 645 } 646 647 // TypedCondExpr returns the IfExpr's Cond expression as a TypedExpr. 648 func (node *IfExpr) TypedCondExpr() TypedExpr { 649 return node.Cond.(TypedExpr) 650 } 651 652 // TypedElseExpr returns the IfExpr's Else expression as a TypedExpr. 653 func (node *IfExpr) TypedElseExpr() TypedExpr { 654 return node.Else.(TypedExpr) 655 } 656 657 // Format implements the NodeFormatter interface. 658 func (node *IfExpr) Format(ctx *FmtCtx) { 659 ctx.WriteString("IF(") 660 ctx.FormatNode(node.Cond) 661 ctx.WriteString(", ") 662 ctx.FormatNode(node.True) 663 ctx.WriteString(", ") 664 ctx.FormatNode(node.Else) 665 ctx.WriteByte(')') 666 } 667 668 // NullIfExpr represents a NULLIF expression. 669 type NullIfExpr struct { 670 Expr1 Expr 671 Expr2 Expr 672 673 typeAnnotation 674 } 675 676 // Format implements the NodeFormatter interface. 677 func (node *NullIfExpr) Format(ctx *FmtCtx) { 678 ctx.WriteString("NULLIF(") 679 ctx.FormatNode(node.Expr1) 680 ctx.WriteString(", ") 681 ctx.FormatNode(node.Expr2) 682 ctx.WriteByte(')') 683 } 684 685 // CoalesceExpr represents a COALESCE or IFNULL expression. 686 type CoalesceExpr struct { 687 Name string 688 Exprs Exprs 689 690 typeAnnotation 691 } 692 693 // NewTypedCoalesceExpr returns a CoalesceExpr that is well-typed. 694 func NewTypedCoalesceExpr(typedExprs TypedExprs, typ *types.T) *CoalesceExpr { 695 c := &CoalesceExpr{ 696 Name: "COALESCE", 697 Exprs: make(Exprs, len(typedExprs)), 698 } 699 for i := range typedExprs { 700 c.Exprs[i] = typedExprs[i] 701 } 702 c.typ = typ 703 return c 704 } 705 706 // NewTypedArray returns an Array that is well-typed. 707 func NewTypedArray(typedExprs TypedExprs, typ *types.T) *Array { 708 c := &Array{ 709 Exprs: make(Exprs, len(typedExprs)), 710 } 711 for i := range typedExprs { 712 c.Exprs[i] = typedExprs[i] 713 } 714 c.typ = typ 715 return c 716 } 717 718 // TypedExprAt returns the expression at the specified index as a TypedExpr. 719 func (node *CoalesceExpr) TypedExprAt(idx int) TypedExpr { 720 return node.Exprs[idx].(TypedExpr) 721 } 722 723 // Format implements the NodeFormatter interface. 724 func (node *CoalesceExpr) Format(ctx *FmtCtx) { 725 ctx.WriteString(node.Name) 726 ctx.WriteByte('(') 727 ctx.FormatNode(&node.Exprs) 728 ctx.WriteByte(')') 729 } 730 731 // GetWhenCondition builds the WHEN condition to use for the ith expression 732 // inside the Coalesce. 733 func (node *CoalesceExpr) GetWhenCondition(i int) (whenCond Expr) { 734 leftExpr := node.Exprs[i].(TypedExpr) 735 rightExpr := DNull 736 // IsDistinctFrom is listed as IsNotDistinctFrom in CmpOps. 737 _, ok := 738 CmpOps[treecmp.IsNotDistinctFrom].LookupImpl(leftExpr.ResolvedType(), rightExpr.ResolvedType()) 739 // If the comparison is legal, use IS NOT DISTINCT FROM NULL. 740 // Otherwise, use IS NOT NULL. 741 if ok { 742 whenCond = NewTypedComparisonExpr( 743 treecmp.MakeComparisonOperator(treecmp.IsDistinctFrom), 744 leftExpr, 745 rightExpr, 746 ) 747 return whenCond 748 } 749 whenCond = NewTypedIsNotNullExpr(leftExpr) 750 return whenCond 751 } 752 753 // DefaultVal represents the DEFAULT expression. 754 type DefaultVal struct{} 755 756 // Format implements the NodeFormatter interface. 757 func (node DefaultVal) Format(ctx *FmtCtx) { 758 ctx.WriteString("DEFAULT") 759 } 760 761 // ResolvedType implements the TypedExpr interface. 762 func (DefaultVal) ResolvedType() *types.T { return nil } 763 764 // PartitionMaxVal represents the MAXVALUE expression. 765 type PartitionMaxVal struct{} 766 767 // Format implements the NodeFormatter interface. 768 func (node PartitionMaxVal) Format(ctx *FmtCtx) { 769 ctx.WriteString("MAXVALUE") 770 } 771 772 // PartitionMinVal represents the MINVALUE expression. 773 type PartitionMinVal struct{} 774 775 // Format implements the NodeFormatter interface. 776 func (node PartitionMinVal) Format(ctx *FmtCtx) { 777 ctx.WriteString("MINVALUE") 778 } 779 780 // Placeholder represents a named placeholder. 781 type Placeholder struct { 782 Idx PlaceholderIdx 783 784 typeAnnotation 785 } 786 787 // NewPlaceholder allocates a Placeholder. 788 func NewPlaceholder(name string) (*Placeholder, error) { 789 uval, err := strconv.ParseUint(name, 10, 64) 790 if err != nil { 791 return nil, err 792 } 793 // The string is the number that follows $ which is a 1-based index ($1, $2, 794 // etc), while PlaceholderIdx is 0-based. 795 if uval == 0 || uval > MaxPlaceholderIdx+1 { 796 return nil, pgerror.Newf( 797 pgcode.NumericValueOutOfRange, 798 "placeholder index must be between 1 and %d", MaxPlaceholderIdx+1, 799 ) 800 } 801 return &Placeholder{Idx: PlaceholderIdx(uval - 1)}, nil 802 } 803 804 // Format implements the NodeFormatter interface. 805 func (node *Placeholder) Format(ctx *FmtCtx) { 806 if ctx.HasFlags(FmtHideConstants) { 807 if ctx.placeholderFormat != nil { 808 ctx.placeholderFormat(ctx, node) 809 return 810 } 811 ctx.Printf("$%d", node.Idx+1) 812 } else { 813 if ctx.placeholderFormat != nil { 814 ctx.placeholderFormat(ctx, node) 815 return 816 } 817 ctx.Printf("$%d", node.Idx+1) 818 } 819 } 820 821 // ResolvedType implements the TypedExpr interface. 822 func (node *Placeholder) ResolvedType() *types.T { 823 if node.typ == nil { 824 return types.Any 825 } 826 return node.typ 827 } 828 829 // Tuple represents a parenthesized list of expressions. 830 type Tuple struct { 831 Exprs Exprs 832 Labels []string 833 834 // Row indicates whether `ROW` was used in the input syntax. This is 835 // used solely to generate column names automatically, see 836 // col_name.go. 837 Row bool 838 839 typ *types.T 840 } 841 842 // NewTypedTuple returns a new Tuple that is verified to be well-typed. 843 func NewTypedTuple(typ *types.T, typedExprs Exprs) *Tuple { 844 return &Tuple{ 845 Exprs: typedExprs, 846 Labels: typ.TupleLabels(), 847 typ: typ, 848 } 849 } 850 851 // Format implements the NodeFormatter interface. 852 func (node *Tuple) Format(ctx *FmtCtx) { 853 // If there are labels, extra parentheses are required surrounding the 854 // expression. 855 if len(node.Labels) > 0 { 856 ctx.WriteByte('(') 857 } 858 ctx.WriteByte('(') 859 ctx.FormatNode(&node.Exprs) 860 if len(node.Exprs) == 1 { 861 // Ensure the pretty-printed 1-value tuple is not ambiguous with 862 // the equivalent value enclosed in grouping parentheses. 863 ctx.WriteByte(',') 864 } 865 ctx.WriteByte(')') 866 if len(node.Labels) > 0 { 867 ctx.WriteString(" AS ") 868 comma := "" 869 for i := range node.Labels { 870 ctx.WriteString(comma) 871 ctx.FormatNode((*Name)(&node.Labels[i])) 872 comma = ", " 873 } 874 ctx.WriteByte(')') 875 } 876 } 877 878 // ResolvedType implements the TypedExpr interface. 879 func (node *Tuple) ResolvedType() *types.T { 880 return node.typ 881 } 882 883 // Array represents an array constructor. 884 type Array struct { 885 Exprs Exprs 886 887 typeAnnotation 888 } 889 890 // Format implements the NodeFormatter interface. 891 func (node *Array) Format(ctx *FmtCtx) { 892 ctx.WriteString("ARRAY[") 893 ctx.FormatNode(&node.Exprs) 894 ctx.WriteByte(']') 895 // If the array has a type, add an annotation. Don't add it if the type is 896 // UNKNOWN[], since that's not a valid annotation. 897 if ctx.HasFlags(FmtParsable) && node.typ != nil { 898 if node.typ.ArrayContents().Family() != types.UnknownFamily { 899 ctx.WriteString(":::") 900 ctx.FormatTypeReference(node.typ) 901 } 902 } 903 } 904 905 // ArrayFlatten represents a subquery array constructor. 906 type ArrayFlatten struct { 907 Subquery Expr 908 909 typeAnnotation 910 } 911 912 // Format implements the NodeFormatter interface. 913 func (node *ArrayFlatten) Format(ctx *FmtCtx) { 914 ctx.WriteString("ARRAY ") 915 exprFmtWithParen(ctx, node.Subquery) 916 if ctx.HasFlags(FmtParsable) { 917 if t, ok := node.Subquery.(*DTuple); ok { 918 if len(t.D) == 0 { 919 ctx.WriteString(":::") 920 ctx.Buffer.WriteString(node.typ.SQLString()) 921 } 922 } 923 } 924 } 925 926 // Exprs represents a list of value expressions. It's not a valid expression 927 // because it's not parenthesized. 928 type Exprs []Expr 929 930 // Format implements the NodeFormatter interface. 931 func (node *Exprs) Format(ctx *FmtCtx) { 932 for i, n := range *node { 933 if i > 0 { 934 ctx.WriteString(", ") 935 } 936 ctx.FormatNode(n) 937 } 938 } 939 940 // TypedExprs represents a list of well-typed value expressions. It's not a valid expression 941 // because it's not parenthesized. 942 type TypedExprs []TypedExpr 943 944 var _ NodeFormatter = &TypedExprs{} 945 946 // Format implements the NodeFormatter interface. 947 func (node *TypedExprs) Format(ctx *FmtCtx) { 948 for i, n := range *node { 949 if i > 0 { 950 ctx.WriteString(", ") 951 } 952 ctx.FormatNode(n) 953 } 954 } 955 956 func (node *TypedExprs) String() string { 957 var prefix string 958 var buf bytes.Buffer 959 for _, n := range *node { 960 fmt.Fprintf(&buf, "%s%s", prefix, n) 961 prefix = ", " 962 } 963 return buf.String() 964 } 965 966 // Subquery represents a subquery. 967 type Subquery struct { 968 Select SelectStatement 969 Exists bool 970 971 // Idx is a query-unique index for the subquery. 972 // Subqueries are 1-indexed to ensure that the default 973 // value 0 can be used to detect uninitialized subqueries. 974 Idx int 975 976 typeAnnotation 977 } 978 979 // ResolvedType implements the TypedExpr interface. 980 func (node *Subquery) ResolvedType() *types.T { 981 if node.typ == nil { 982 return types.Any 983 } 984 return node.typ 985 } 986 987 // SetType forces the type annotation on the Subquery node. 988 func (node *Subquery) SetType(t *types.T) { 989 node.typ = t 990 } 991 992 // Variable implements the VariableExpr interface. 993 func (*Subquery) Variable() {} 994 995 // SubqueryExpr implements the SubqueryExpr interface. 996 func (*Subquery) SubqueryExpr() {} 997 998 // Format implements the NodeFormatter interface. 999 func (node *Subquery) Format(ctx *FmtCtx) { 1000 if ctx.HasFlags(FmtSymbolicSubqueries) { 1001 ctx.Printf("@S%d", node.Idx) 1002 } else { 1003 // Ensure that type printing is disabled during the recursion, as 1004 // the type annotations are not available in subqueries. 1005 ctx.WithFlags(ctx.flags & ^FmtShowTypes, func() { 1006 if node.Exists { 1007 ctx.WriteString("EXISTS ") 1008 } 1009 if node.Select == nil { 1010 // If the subquery is generated by the optimizer, we 1011 // don't have an actual statement. 1012 ctx.WriteString("<unknown>") 1013 } else { 1014 ctx.FormatNode(node.Select) 1015 } 1016 }) 1017 } 1018 } 1019 1020 // TypedDummy is a dummy expression that represents a dummy value with 1021 // a specified type. It can be used in situations where TypedExprs of a 1022 // particular type are required for semantic analysis. 1023 type TypedDummy struct { 1024 Typ *types.T 1025 } 1026 1027 func (node *TypedDummy) String() string { 1028 return AsString(node) 1029 } 1030 1031 // Format implements the NodeFormatter interface. 1032 func (node *TypedDummy) Format(ctx *FmtCtx) { 1033 ctx.WriteString("dummyvalof(") 1034 ctx.FormatTypeReference(node.Typ) 1035 ctx.WriteString(")") 1036 } 1037 1038 // ResolvedType implements the TypedExpr interface. 1039 func (node *TypedDummy) ResolvedType() *types.T { 1040 return node.Typ 1041 } 1042 1043 // TypeCheck implements the Expr interface. 1044 func (node *TypedDummy) TypeCheck(context.Context, *SemaContext, *types.T) (TypedExpr, error) { 1045 return node, nil 1046 } 1047 1048 // Walk implements the Expr interface. 1049 func (node *TypedDummy) Walk(Visitor) Expr { return node } 1050 1051 // binaryOpPrio follows the precedence order in the grammar. Used for pretty-printing. 1052 var binaryOpPrio = [...]int{ 1053 treebin.Pow: 1, 1054 treebin.Mult: 2, treebin.Div: 2, treebin.FloorDiv: 2, treebin.Mod: 2, 1055 treebin.Plus: 3, treebin.Minus: 3, 1056 treebin.LShift: 4, treebin.RShift: 4, 1057 treebin.Bitand: 5, 1058 treebin.Bitxor: 6, 1059 treebin.Bitor: 7, 1060 treebin.Concat: 8, treebin.JSONFetchVal: 8, treebin.JSONFetchText: 8, treebin.JSONFetchValPath: 8, treebin.JSONFetchTextPath: 8, 1061 } 1062 1063 // binaryOpFullyAssoc indicates whether an operator is fully associative. 1064 // Reminder: an op R is fully associative if (a R b) R c == a R (b R c) 1065 var binaryOpFullyAssoc = [...]bool{ 1066 treebin.Pow: false, 1067 treebin.Mult: true, treebin.Div: false, treebin.FloorDiv: false, treebin.Mod: false, 1068 treebin.Plus: true, treebin.Minus: false, 1069 treebin.LShift: false, treebin.RShift: false, 1070 treebin.Bitand: true, 1071 treebin.Bitxor: true, 1072 treebin.Bitor: true, 1073 treebin.Concat: true, treebin.JSONFetchVal: false, treebin.JSONFetchText: false, treebin.JSONFetchValPath: false, treebin.JSONFetchTextPath: false, 1074 } 1075 1076 // BinaryExpr represents a binary value expression. 1077 type BinaryExpr struct { 1078 Operator treebin.BinaryOperator 1079 Left, Right Expr 1080 1081 typeAnnotation 1082 Op *BinOp 1083 } 1084 1085 // TypedLeft returns the BinaryExpr's left expression as a TypedExpr. 1086 func (node *BinaryExpr) TypedLeft() TypedExpr { 1087 return node.Left.(TypedExpr) 1088 } 1089 1090 // TypedRight returns the BinaryExpr's right expression as a TypedExpr. 1091 func (node *BinaryExpr) TypedRight() TypedExpr { 1092 return node.Right.(TypedExpr) 1093 } 1094 1095 // ResolvedBinOp returns the resolved binary op overload; can only be called 1096 // after Resolve (which happens during TypeCheck). 1097 func (node *BinaryExpr) ResolvedBinOp() *BinOp { 1098 return node.Op 1099 } 1100 1101 // NewTypedBinaryExpr returns a new BinaryExpr that is well-typed. 1102 func NewTypedBinaryExpr( 1103 op treebin.BinaryOperator, left, right TypedExpr, typ *types.T, 1104 ) *BinaryExpr { 1105 node := &BinaryExpr{Operator: op, Left: left, Right: right} 1106 node.typ = typ 1107 node.memoizeOp() 1108 return node 1109 } 1110 1111 func (*BinaryExpr) operatorExpr() {} 1112 1113 func (node *BinaryExpr) memoizeOp() { 1114 leftRet, rightRet := node.Left.(TypedExpr).ResolvedType(), node.Right.(TypedExpr).ResolvedType() 1115 fn, ok := BinOps[node.Operator.Symbol].LookupImpl(leftRet, rightRet) 1116 if !ok { 1117 panic(errors.AssertionFailedf("lookup for BinaryExpr %s's BinOp failed (%s(%s,%s))", 1118 AsStringWithFlags(node, FmtShowTypes), redact.Safe(node.Operator.String()), 1119 leftRet.SQLStringForError(), rightRet.SQLStringForError(), 1120 )) 1121 } 1122 node.Op = fn 1123 } 1124 1125 // NewBinExprIfValidOverload constructs a new BinaryExpr if and only 1126 // if the pair of arguments have a valid implementation for the given 1127 // BinaryOperator. 1128 func NewBinExprIfValidOverload( 1129 op treebin.BinaryOperator, left TypedExpr, right TypedExpr, 1130 ) *BinaryExpr { 1131 leftRet, rightRet := left.ResolvedType(), right.ResolvedType() 1132 fn, ok := BinOps[op.Symbol].LookupImpl(leftRet, rightRet) 1133 if ok { 1134 expr := &BinaryExpr{ 1135 Operator: op, 1136 Left: left, 1137 Right: right, 1138 Op: fn, 1139 } 1140 expr.typ = returnTypeToFixedType(fn.returnType(), []TypedExpr{left, right}) 1141 expr.memoizeOp() 1142 return expr 1143 } 1144 return nil 1145 } 1146 1147 // Format implements the NodeFormatter interface. 1148 func (node *BinaryExpr) Format(ctx *FmtCtx) { 1149 binExprFmtWithParen(ctx, node.Left, node.Operator.String(), node.Right, node.Operator.Symbol.IsPadded()) 1150 } 1151 1152 // UnaryOperator represents a unary operator used in a UnaryExpr. 1153 type UnaryOperator struct { 1154 Symbol UnaryOperatorSymbol 1155 // IsExplicitOperator is true if OPERATOR(symbol) is used. 1156 IsExplicitOperator bool 1157 } 1158 1159 // MakeUnaryOperator creates a UnaryOperator given a symbol. 1160 func MakeUnaryOperator(symbol UnaryOperatorSymbol) UnaryOperator { 1161 return UnaryOperator{Symbol: symbol} 1162 } 1163 1164 func (o UnaryOperator) String() string { 1165 if o.IsExplicitOperator { 1166 return fmt.Sprintf("OPERATOR(%s)", o.Symbol.String()) 1167 } 1168 return o.Symbol.String() 1169 } 1170 1171 // Operator implements tree.Operator. 1172 func (UnaryOperator) Operator() {} 1173 1174 // IsUnaryComplement returns whether op is a unary complement operator. 1175 func IsUnaryComplement(op Operator) bool { 1176 u, ok := op.(UnaryOperator) 1177 return ok && u.Symbol == UnaryComplement 1178 } 1179 1180 // UnaryOperatorSymbol represents a unary operator. 1181 type UnaryOperatorSymbol uint8 1182 1183 // UnaryExpr.Operator.Symbol 1184 const ( 1185 UnaryMinus UnaryOperatorSymbol = iota 1186 UnaryComplement 1187 UnarySqrt 1188 UnaryCbrt 1189 UnaryPlus 1190 1191 NumUnaryOperatorSymbols 1192 ) 1193 1194 var _ = NumUnaryOperatorSymbols 1195 1196 // UnaryOpName is the mapping of unary operators to names. 1197 var UnaryOpName = [...]string{ 1198 UnaryMinus: "-", 1199 UnaryPlus: "+", 1200 UnaryComplement: "~", 1201 UnarySqrt: "|/", 1202 UnaryCbrt: "||/", 1203 } 1204 1205 func (i UnaryOperatorSymbol) String() string { 1206 if i > UnaryOperatorSymbol(len(UnaryOpName)-1) { 1207 return fmt.Sprintf("UnaryOp(%d)", i) 1208 } 1209 return UnaryOpName[i] 1210 } 1211 1212 // UnaryExpr represents a unary value expression. 1213 type UnaryExpr struct { 1214 Operator UnaryOperator 1215 Expr Expr 1216 1217 typeAnnotation 1218 op *UnaryOp 1219 } 1220 1221 func (*UnaryExpr) operatorExpr() {} 1222 1223 // GetOp exposes the underlying UnaryOp. 1224 func (node *UnaryExpr) GetOp() *UnaryOp { 1225 return node.op 1226 } 1227 1228 // Format implements the NodeFormatter interface. 1229 func (node *UnaryExpr) Format(ctx *FmtCtx) { 1230 ctx.WriteString(node.Operator.String()) 1231 e := node.Expr 1232 _, isOp := e.(operatorExpr) 1233 _, isDatum := e.(Datum) 1234 _, isConstant := e.(Constant) 1235 if isOp || (node.Operator.Symbol == UnaryMinus && (isDatum || isConstant)) { 1236 ctx.WriteByte('(') 1237 ctx.FormatNode(e) 1238 ctx.WriteByte(')') 1239 } else { 1240 ctx.FormatNode(e) 1241 } 1242 } 1243 1244 // TypedInnerExpr returns the UnaryExpr's inner expression as a TypedExpr. 1245 func (node *UnaryExpr) TypedInnerExpr() TypedExpr { 1246 return node.Expr.(TypedExpr) 1247 } 1248 1249 // NewTypedUnaryExpr returns a new UnaryExpr that is well-typed. 1250 func NewTypedUnaryExpr(op UnaryOperator, expr TypedExpr, typ *types.T) *UnaryExpr { 1251 node := &UnaryExpr{Operator: op, Expr: expr} 1252 node.typ = typ 1253 innerType := expr.ResolvedType() 1254 1255 _ = UnaryOps[op.Symbol].ForEachUnaryOp(func(o *UnaryOp) error { 1256 if innerType.Equivalent(o.Typ) && node.typ.Equivalent(o.ReturnType) { 1257 node.op = o 1258 return iterutil.StopIteration() 1259 } 1260 return nil 1261 }) 1262 if node.op == nil { 1263 panic(errors.AssertionFailedf("invalid TypedExpr with unary op %d: %s", op.Symbol, expr)) 1264 } 1265 return node 1266 } 1267 1268 // FuncExpr represents a function call. 1269 type FuncExpr struct { 1270 Func ResolvableFunctionReference 1271 Type funcType 1272 Exprs Exprs 1273 // Filter is used for filters on aggregates: SUM(k) FILTER (WHERE k > 0) 1274 Filter Expr 1275 WindowDef *WindowDef 1276 1277 // AggType is used to specify the type of aggregation. 1278 AggType AggType 1279 // OrderBy is used for aggregations which specify an order. This same field 1280 // is used for any type of aggregation. 1281 OrderBy OrderBy 1282 1283 // InCall is true when the FuncExpr is part of a CALL statement. 1284 InCall bool 1285 1286 typeAnnotation 1287 fnProps *FunctionProperties 1288 fn *Overload 1289 } 1290 1291 // NewTypedFuncExpr returns a FuncExpr that is already well-typed and resolved. 1292 func NewTypedFuncExpr( 1293 ref ResolvableFunctionReference, 1294 aggQualifier funcType, 1295 exprs TypedExprs, 1296 filter TypedExpr, 1297 windowDef *WindowDef, 1298 typ *types.T, 1299 props *FunctionProperties, 1300 overload *Overload, 1301 ) *FuncExpr { 1302 f := &FuncExpr{ 1303 Func: ref, 1304 Type: aggQualifier, 1305 Exprs: make(Exprs, len(exprs)), 1306 Filter: filter, 1307 WindowDef: windowDef, 1308 typeAnnotation: typeAnnotation{typ: typ}, 1309 fn: overload, 1310 fnProps: props, 1311 } 1312 for i, e := range exprs { 1313 f.Exprs[i] = e 1314 } 1315 return f 1316 } 1317 1318 // ResolvedOverload returns the builtin definition; can only be called after 1319 // Resolve (which happens during TypeCheck). 1320 func (node *FuncExpr) ResolvedOverload() *Overload { 1321 return node.fn 1322 } 1323 1324 // IsGeneratorClass returns true if the resolved overload metadata is of 1325 // the GeneratorClass. 1326 func (node *FuncExpr) IsGeneratorClass() bool { 1327 return node.ResolvedOverload() != nil && node.ResolvedOverload().Class == GeneratorClass 1328 } 1329 1330 // IsWindowFunctionApplication returns true iff the function is being applied as a window function. 1331 func (node *FuncExpr) IsWindowFunctionApplication() bool { 1332 return node.WindowDef != nil 1333 } 1334 1335 // IsDistSQLBlocklist returns whether the function is not supported by DistSQL. 1336 func (node *FuncExpr) IsDistSQLBlocklist() bool { 1337 return (node.fn != nil && node.fn.DistsqlBlocklist) || (node.fnProps != nil && node.fnProps.DistsqlBlocklist) 1338 } 1339 1340 // IsVectorizeStreaming returns whether the function is of "streaming" nature 1341 // from the perspective of the vectorized execution engine. 1342 func (node *FuncExpr) IsVectorizeStreaming() bool { 1343 return node.fnProps != nil && node.fnProps.VectorizeStreaming 1344 } 1345 1346 func (node *FuncExpr) SetTypeAnnotation(t *types.T) { 1347 node.typ = t 1348 } 1349 1350 type funcType int 1351 1352 // FuncExpr.Type 1353 const ( 1354 _ funcType = iota 1355 DistinctFuncType 1356 AllFuncType 1357 ) 1358 1359 var funcTypeName = [...]string{ 1360 DistinctFuncType: "DISTINCT", 1361 AllFuncType: "ALL", 1362 } 1363 1364 // AggType specifies the type of aggregation. 1365 type AggType int 1366 1367 // FuncExpr.AggType 1368 const ( 1369 _ AggType = iota 1370 // GeneralAgg is used for general-purpose aggregate functions. 1371 // array_agg(col1 ORDER BY col2) 1372 GeneralAgg 1373 // OrderedSetAgg is used for ordered-set aggregate functions. 1374 // percentile_disc(fraction) WITHIN GROUP (ORDER BY col1) 1375 OrderedSetAgg 1376 ) 1377 1378 // Format implements the NodeFormatter interface. 1379 func (node *FuncExpr) Format(ctx *FmtCtx) { 1380 var typ string 1381 if node.Type != 0 { 1382 typ = funcTypeName[node.Type] + " " 1383 } 1384 1385 // We let anonymization and redaction flags pass through, which will cause 1386 // built-in functions to be redacted if we have not resolved them. This is 1387 // because we cannot distinguish between built-in functions and UDFs before 1388 // they are resolved. We conservatively redact function names if requested. 1389 // TODO(111385): Investigate ways to identify built-in functions before 1390 // type-checking. 1391 ctx.WithFlags(ctx.flags|FmtBareIdentifiers, func() { 1392 ctx.FormatNode(&node.Func) 1393 }) 1394 1395 ctx.WriteByte('(') 1396 ctx.WriteString(typ) 1397 ctx.FormatNode(&node.Exprs) 1398 if node.AggType == GeneralAgg && len(node.OrderBy) > 0 { 1399 ctx.WriteByte(' ') 1400 ctx.FormatNode(&node.OrderBy) 1401 } 1402 ctx.WriteByte(')') 1403 if ctx.HasFlags(FmtParsable) && node.typ != nil { 1404 if node.fnProps.AmbiguousReturnType { 1405 // There's no type annotation available for tuples. 1406 // TODO(jordan,knz): clean this up. AmbiguousReturnType should be set only 1407 // when we should and can put an annotation here. #28579 1408 if node.typ.Family() != types.TupleFamily { 1409 ctx.WriteString(":::") 1410 ctx.Buffer.WriteString(node.typ.SQLString()) 1411 } 1412 } 1413 } 1414 if node.AggType == OrderedSetAgg && len(node.OrderBy) > 0 { 1415 ctx.WriteString(" WITHIN GROUP (") 1416 ctx.FormatNode(&node.OrderBy) 1417 ctx.WriteString(")") 1418 } 1419 if node.Filter != nil { 1420 ctx.WriteString(" FILTER (WHERE ") 1421 ctx.FormatNode(node.Filter) 1422 ctx.WriteString(")") 1423 } 1424 if window := node.WindowDef; window != nil { 1425 ctx.WriteString(" OVER ") 1426 if window.Name != "" { 1427 ctx.FormatNode(&window.Name) 1428 } else { 1429 ctx.FormatNode(window) 1430 } 1431 } 1432 } 1433 1434 // CaseExpr represents a CASE expression. 1435 type CaseExpr struct { 1436 Expr Expr 1437 Whens []*When 1438 Else Expr 1439 1440 typeAnnotation 1441 } 1442 1443 // Format implements the NodeFormatter interface. 1444 func (node *CaseExpr) Format(ctx *FmtCtx) { 1445 ctx.WriteString("CASE ") 1446 if node.Expr != nil { 1447 ctx.FormatNode(node.Expr) 1448 ctx.WriteByte(' ') 1449 } 1450 for _, when := range node.Whens { 1451 ctx.FormatNode(when) 1452 ctx.WriteByte(' ') 1453 } 1454 if node.Else != nil { 1455 ctx.WriteString("ELSE ") 1456 ctx.FormatNode(node.Else) 1457 ctx.WriteByte(' ') 1458 } 1459 ctx.WriteString("END") 1460 } 1461 1462 // NewTypedCaseExpr returns a new CaseExpr that is verified to be well-typed. 1463 func NewTypedCaseExpr( 1464 expr TypedExpr, whens []*When, elseStmt TypedExpr, typ *types.T, 1465 ) (*CaseExpr, error) { 1466 node := &CaseExpr{Expr: expr, Whens: whens, Else: elseStmt} 1467 node.typ = typ 1468 return node, nil 1469 } 1470 1471 // When represents a WHEN sub-expression. 1472 type When struct { 1473 Cond Expr 1474 Val Expr 1475 } 1476 1477 // Format implements the NodeFormatter interface. 1478 func (node *When) Format(ctx *FmtCtx) { 1479 ctx.WriteString("WHEN ") 1480 ctx.FormatNode(node.Cond) 1481 ctx.WriteString(" THEN ") 1482 ctx.FormatNode(node.Val) 1483 } 1484 1485 type castSyntaxMode int 1486 1487 // These constants separate the syntax X::Y from CAST(X AS Y). 1488 const ( 1489 CastExplicit castSyntaxMode = iota 1490 CastShort 1491 CastPrepend 1492 ) 1493 1494 // CastExpr represents a CAST(expr AS type) expression. 1495 type CastExpr struct { 1496 Expr Expr 1497 Type ResolvableTypeReference 1498 1499 typeAnnotation 1500 SyntaxMode castSyntaxMode 1501 } 1502 1503 // Format implements the NodeFormatter interface. 1504 func (node *CastExpr) Format(ctx *FmtCtx) { 1505 switch node.SyntaxMode { 1506 case CastPrepend: 1507 // This is a special case for things like INTERVAL '1s'. These only work 1508 // with string constants; if the underlying expression was changed, we fall 1509 // back to the short syntax. 1510 if _, ok := node.Expr.(*StrVal); ok { 1511 ctx.FormatTypeReference(node.Type) 1512 ctx.WriteByte(' ') 1513 // We need to replace this with a quoted string constants in certain 1514 // cases because the grammar requires a string constant rather than an 1515 // expression for this form of casting in the typed_literal rule 1516 if ctx.HasFlags(FmtHideConstants) { 1517 ctx.WriteString("'_'") 1518 } else { 1519 ctx.FormatNode(node.Expr) 1520 } 1521 break 1522 } 1523 fallthrough 1524 case CastShort: 1525 exprFmtWithParen(ctx, node.Expr) 1526 ctx.WriteString("::") 1527 ctx.FormatTypeReference(node.Type) 1528 default: 1529 ctx.WriteString("CAST(") 1530 ctx.FormatNode(node.Expr) 1531 ctx.WriteString(" AS ") 1532 if typ, ok := GetStaticallyKnownType(node.Type); ok && typ.Family() == types.CollatedStringFamily { 1533 // Need to write closing parentheses before COLLATE clause, so create 1534 // equivalent string type without the locale. 1535 strTyp := types.MakeScalar( 1536 types.StringFamily, 1537 typ.Oid(), 1538 typ.Precision(), 1539 typ.Width(), 1540 "", /* locale */ 1541 ) 1542 ctx.WriteString(strTyp.SQLString()) 1543 ctx.WriteString(") COLLATE ") 1544 lex.EncodeLocaleName(&ctx.Buffer, typ.Locale()) 1545 } else { 1546 ctx.FormatTypeReference(node.Type) 1547 ctx.WriteByte(')') 1548 } 1549 } 1550 } 1551 1552 // NewTypedCastExpr returns a new CastExpr that is verified to be well-typed. 1553 func NewTypedCastExpr(expr TypedExpr, typ *types.T) *CastExpr { 1554 node := &CastExpr{Expr: expr, Type: typ, SyntaxMode: CastShort} 1555 node.typ = typ 1556 return node 1557 } 1558 1559 // ArraySubscripts represents a sequence of one or more array subscripts. 1560 type ArraySubscripts []*ArraySubscript 1561 1562 // Format implements the NodeFormatter interface. 1563 func (a *ArraySubscripts) Format(ctx *FmtCtx) { 1564 for _, s := range *a { 1565 ctx.FormatNode(s) 1566 } 1567 } 1568 1569 // IndirectionExpr represents a subscript expression. 1570 type IndirectionExpr struct { 1571 Expr Expr 1572 Indirection ArraySubscripts 1573 1574 typeAnnotation 1575 } 1576 1577 // Format implements the NodeFormatter interface. 1578 func (node *IndirectionExpr) Format(ctx *FmtCtx) { 1579 // If the sub expression is a CastExpr or an Array that has a type, 1580 // we need to wrap it in a ParenExpr, otherwise the indirection 1581 // will get interpreted as part of the type. 1582 // Ex. ('{a}'::_typ)[1] vs. '{a}'::_typ[1]. 1583 // Ex. (ARRAY['a'::typ]:::typ[])[1] vs. ARRAY['a'::typ]:::typ[][1]. 1584 var annotateArray bool 1585 if arr, ok := node.Expr.(*Array); ctx.HasFlags(FmtParsable) && ok && arr.typ != nil { 1586 if arr.typ.ArrayContents().Family() != types.UnknownFamily { 1587 annotateArray = true 1588 } 1589 } 1590 if _, isCast := node.Expr.(*CastExpr); isCast || annotateArray { 1591 withParens := ParenExpr{Expr: node.Expr} 1592 exprFmtWithParen(ctx, &withParens) 1593 } else { 1594 exprFmtWithParen(ctx, node.Expr) 1595 } 1596 ctx.FormatNode(&node.Indirection) 1597 } 1598 1599 type annotateSyntaxMode int 1600 1601 // These constants separate the syntax X:::Y from ANNOTATE_TYPE(X, Y) 1602 const ( 1603 AnnotateExplicit annotateSyntaxMode = iota 1604 AnnotateShort 1605 ) 1606 1607 // AnnotateTypeExpr represents a ANNOTATE_TYPE(expr, type) expression. 1608 type AnnotateTypeExpr struct { 1609 Expr Expr 1610 Type ResolvableTypeReference 1611 1612 SyntaxMode annotateSyntaxMode 1613 } 1614 1615 // Format implements the NodeFormatter interface. 1616 func (node *AnnotateTypeExpr) Format(ctx *FmtCtx) { 1617 switch node.SyntaxMode { 1618 case AnnotateShort: 1619 exprFmtWithParen(ctx, node.Expr) 1620 // The Array format function handles adding type annotations for this case. 1621 // We short circuit here to prevent double type annotation. 1622 if arrayExpr, ok := node.Expr.(*Array); ok { 1623 if ctx.HasFlags(FmtParsable) && arrayExpr.typ != nil { 1624 return 1625 } 1626 } 1627 ctx.WriteString(":::") 1628 ctx.FormatTypeReference(node.Type) 1629 1630 default: 1631 ctx.WriteString("ANNOTATE_TYPE(") 1632 ctx.FormatNode(node.Expr) 1633 ctx.WriteString(", ") 1634 ctx.FormatTypeReference(node.Type) 1635 ctx.WriteByte(')') 1636 } 1637 } 1638 1639 // TypedInnerExpr returns the AnnotateTypeExpr's inner expression as a TypedExpr. 1640 func (node *AnnotateTypeExpr) TypedInnerExpr() TypedExpr { 1641 return node.Expr.(TypedExpr) 1642 } 1643 1644 // CollateExpr represents an (expr COLLATE locale) expression. 1645 type CollateExpr struct { 1646 Expr Expr 1647 Locale string 1648 1649 typeAnnotation 1650 } 1651 1652 // Format implements the NodeFormatter interface. 1653 func (node *CollateExpr) Format(ctx *FmtCtx) { 1654 exprFmtWithParen(ctx, node.Expr) 1655 ctx.WriteString(" COLLATE ") 1656 lex.EncodeLocaleName(&ctx.Buffer, node.Locale) 1657 } 1658 1659 // TupleStar represents (E).* expressions. 1660 // It is meant to evaporate during star expansion. 1661 type TupleStar struct { 1662 Expr Expr 1663 } 1664 1665 // NormalizeVarName implements the VarName interface. 1666 func (node *TupleStar) NormalizeVarName() (VarName, error) { return node, nil } 1667 1668 // Format implements the NodeFormatter interface. 1669 func (node *TupleStar) Format(ctx *FmtCtx) { 1670 ctx.WriteByte('(') 1671 ctx.FormatNode(node.Expr) 1672 ctx.WriteString(").*") 1673 } 1674 1675 // ColumnAccessExpr represents (E).x expressions. Specifically, it 1676 // allows accessing the column(s) from a Set Returning Function. 1677 type ColumnAccessExpr struct { 1678 Expr Expr 1679 1680 // ByIndex, if set, indicates that the access is using a numeric 1681 // column reference and ColIndex below is already set. 1682 ByIndex bool 1683 1684 // ColName is the name of the column to access. Empty if ByIndex is 1685 // set. 1686 ColName Name 1687 1688 // ColIndex indicates the index of the column in the tuple. This is 1689 // either: 1690 // - set during type checking based on the label in ColName if 1691 // ByIndex is false, 1692 // - or checked for validity during type checking if ByIndex is true. 1693 // The first column in the tuple is at index 0. The input 1694 // syntax (E).@N populates N-1 in this field. 1695 ColIndex int 1696 1697 typeAnnotation 1698 } 1699 1700 // NewTypedColumnAccessExpr creates a pre-typed ColumnAccessExpr. 1701 // A by-index ColumnAccessExpr can be specified by passing an empty string as colName. 1702 func NewTypedColumnAccessExpr(expr TypedExpr, colName Name, colIdx int) *ColumnAccessExpr { 1703 return &ColumnAccessExpr{ 1704 Expr: expr, 1705 ColName: colName, 1706 ByIndex: colName == "", 1707 ColIndex: colIdx, 1708 typeAnnotation: typeAnnotation{typ: expr.ResolvedType().TupleContents()[colIdx]}, 1709 } 1710 } 1711 1712 // Format implements the NodeFormatter interface. 1713 func (node *ColumnAccessExpr) Format(ctx *FmtCtx) { 1714 ctx.WriteByte('(') 1715 ctx.FormatNode(node.Expr) 1716 ctx.WriteString(").") 1717 if node.ByIndex { 1718 fmt.Fprintf(ctx, "@%d", node.ColIndex+1) 1719 } else { 1720 ctx.FormatNode(&node.ColName) 1721 } 1722 } 1723 1724 func (node *AliasedTableExpr) String() string { return AsString(node) } 1725 func (node *ParenTableExpr) String() string { return AsString(node) } 1726 func (node *JoinTableExpr) String() string { return AsString(node) } 1727 func (node *AndExpr) String() string { return AsString(node) } 1728 func (node *Array) String() string { return AsString(node) } 1729 func (node *BinaryExpr) String() string { return AsString(node) } 1730 func (node *CaseExpr) String() string { return AsString(node) } 1731 func (node *CastExpr) String() string { return AsString(node) } 1732 func (node *CoalesceExpr) String() string { return AsString(node) } 1733 func (node *ColumnAccessExpr) String() string { return AsString(node) } 1734 func (node *CollateExpr) String() string { return AsString(node) } 1735 func (node *ComparisonExpr) String() string { return AsString(node) } 1736 func (node *Datums) String() string { return AsString(node) } 1737 func (node *DBitArray) String() string { return AsString(node) } 1738 func (node *DBool) String() string { return AsString(node) } 1739 func (node *DBytes) String() string { return AsString(node) } 1740 func (node *DEncodedKey) String() string { return AsString(node) } 1741 func (node *DDate) String() string { return AsString(node) } 1742 func (node *DTime) String() string { return AsString(node) } 1743 func (node *DTimeTZ) String() string { return AsString(node) } 1744 func (node *DDecimal) String() string { return AsString(node) } 1745 func (node *DFloat) String() string { return AsString(node) } 1746 func (node *DBox2D) String() string { return AsString(node) } 1747 func (node *DPGLSN) String() string { return AsString(node) } 1748 func (node *DGeography) String() string { return AsString(node) } 1749 func (node *DGeometry) String() string { return AsString(node) } 1750 func (node *DInt) String() string { return AsString(node) } 1751 func (node *DInterval) String() string { return AsString(node) } 1752 func (node *DJSON) String() string { return AsString(node) } 1753 func (node *DUuid) String() string { return AsString(node) } 1754 func (node *DIPAddr) String() string { return AsString(node) } 1755 func (node *DString) String() string { return AsString(node) } 1756 func (node *DCollatedString) String() string { return AsString(node) } 1757 func (node *DTimestamp) String() string { return AsString(node) } 1758 func (node *DTimestampTZ) String() string { return AsString(node) } 1759 func (node *DTuple) String() string { return AsString(node) } 1760 func (node *DArray) String() string { return AsString(node) } 1761 func (node *DOid) String() string { return AsString(node) } 1762 func (node *DOidWrapper) String() string { return AsString(node) } 1763 func (node *DVoid) String() string { return AsString(node) } 1764 func (node *Exprs) String() string { return AsString(node) } 1765 func (node *ArrayFlatten) String() string { return AsString(node) } 1766 func (node *FuncExpr) String() string { return AsString(node) } 1767 func (node *IfExpr) String() string { return AsString(node) } 1768 func (node *IfErrExpr) String() string { return AsString(node) } 1769 func (node *IndexedVar) String() string { return AsString(node) } 1770 func (node *IndirectionExpr) String() string { return AsString(node) } 1771 func (node *IsOfTypeExpr) String() string { return AsString(node) } 1772 func (node *Name) String() string { return AsString(node) } 1773 func (node *UnrestrictedName) String() string { return AsString(node) } 1774 func (node *NotExpr) String() string { return AsString(node) } 1775 func (node *IsNullExpr) String() string { return AsString(node) } 1776 func (node *IsNotNullExpr) String() string { return AsString(node) } 1777 func (node *NullIfExpr) String() string { return AsString(node) } 1778 func (node *NumVal) String() string { return AsString(node) } 1779 func (node *OrExpr) String() string { return AsString(node) } 1780 func (node *ParenExpr) String() string { return AsString(node) } 1781 func (node *RangeCond) String() string { return AsString(node) } 1782 func (node *StrVal) String() string { return AsString(node) } 1783 func (node *Subquery) String() string { return AsString(node) } 1784 func (node *RoutineExpr) String() string { return AsString(node) } 1785 func (node *Tuple) String() string { return AsString(node) } 1786 func (node *TupleStar) String() string { return AsString(node) } 1787 func (node *AnnotateTypeExpr) String() string { return AsString(node) } 1788 func (node *UnaryExpr) String() string { return AsString(node) } 1789 func (node DefaultVal) String() string { return AsString(node) } 1790 func (node PartitionMaxVal) String() string { return AsString(node) } 1791 func (node PartitionMinVal) String() string { return AsString(node) } 1792 func (node *Placeholder) String() string { return AsString(node) } 1793 func (node dNull) String() string { return AsString(node) } 1794 func (list *NameList) String() string { return AsString(list) }