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