github.com/cockroachdb/cockroachdb-parser@v0.23.3-0.20240213214944-911057d40c9a/pkg/sql/sem/tree/constant_eval.go (about)

     1  // Copyright 2018 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  	"github.com/cockroachdb/cockroachdb-parser/pkg/sql/sem/cast"
    15  	"github.com/cockroachdb/cockroachdb-parser/pkg/sql/sem/volatility"
    16  )
    17  
    18  // OperatorIsImmutable returns true if the given expression corresponds to a
    19  // constant operator. Note importantly that this will return true for all
    20  // expr types other than FuncExpr, CastExpr, UnaryExpr, BinaryExpr, and
    21  // ComparisonExpr. It does not do any recursive searching.
    22  func OperatorIsImmutable(expr Expr) bool {
    23  	switch t := expr.(type) {
    24  	case *FuncExpr:
    25  		return t.ResolvedOverload().Class == NormalClass && t.fn.Volatility <= volatility.Immutable
    26  
    27  	case *CastExpr:
    28  		v, ok := cast.LookupCastVolatility(t.Expr.(TypedExpr).ResolvedType(), t.typ)
    29  		return ok && v <= volatility.Immutable
    30  
    31  	case *UnaryExpr:
    32  		return t.op.Volatility <= volatility.Immutable
    33  
    34  	case *BinaryExpr:
    35  		return t.Op.Volatility <= volatility.Immutable
    36  
    37  	case *ComparisonExpr:
    38  		return t.Op.Volatility <= volatility.Immutable
    39  
    40  	default:
    41  		return true
    42  	}
    43  }