Documentation
¶
Overview ¶
Package schemaexpr provides utilities for dealing with expressions with table schemas, such as check constraints, computed columns, and partial index predicates.
Index ¶
- func CannotWriteToComputedColError(colName string) error
- func DequalifyAndTypeCheckExpr(ctx context.Context, desc catalog.TableDescriptor, expr tree.Expr, ...) (tree.TypedExpr, error)
- func DequalifyAndValidateExpr(ctx context.Context, desc catalog.TableDescriptor, expr tree.Expr, ...) (string, *types.T, catalog.TableColSet, error)
- func DequalifyColumnRefs(ctx context.Context, source *colinfo.DataSourceInfo, expr tree.Expr) (string, error)
- func ExtractColumnIDs(desc catalog.TableDescriptor, rootExpr tree.Expr) (catalog.TableColSet, error)
- func FormatColumnForDisplay(ctx context.Context, tbl catalog.TableDescriptor, col catalog.Column, ...) (string, error)
- func FormatExprForDisplay(ctx context.Context, desc catalog.TableDescriptor, exprStr string, ...) (string, error)
- func FormatExprForExpressionIndexDisplay(ctx context.Context, desc catalog.TableDescriptor, exprStr string, ...) (string, error)
- func GetSeqIDFromExpr(expr tree.Expr) (int64, bool)
- func HasValidColumnReferences(desc catalog.TableDescriptor, rootExpr tree.Expr) (bool, error)
- func MakeComputedExprs(ctx context.Context, input, sourceColumns []catalog.Column, ...) (_ []tree.TypedExpr, refColIDs catalog.TableColSet, _ error)
- func MakeDefaultExprs(ctx context.Context, cols []catalog.Column, ...) ([]tree.TypedExpr, error)
- func MakeHashShardComputeExpr(colNames []string, buckets int) *string
- func MakePartialIndexExprs(ctx context.Context, indexes []catalog.Index, cols []catalog.Column, ...) (_ map[descpb.IndexID]tree.TypedExpr, refColIDs catalog.TableColSet, _ error)
- func MaybeRewriteComputedColumn(expr tree.Expr, sessionData *sessiondata.SessionData) tree.Expr
- func ProcessColumnSet(cols []catalog.Column, tableDesc catalog.TableDescriptor, ...) []catalog.Column
- func RenameColumn(expr string, from tree.Name, to tree.Name) (string, error)
- func ReplaceColumnVars(rootExpr tree.Expr, ...) (tree.Expr, catalog.TableColSet, error)
- func ReplaceIDsWithFQNames(ctx context.Context, rootExpr tree.Expr, semaCtx *tree.SemaContext) (tree.Expr, error)
- func ResolveNamesUsingVisitor(v *NameResolutionVisitor, expr tree.Expr, source *colinfo.DataSourceInfo, ...) (tree.Expr, error)
- func SanitizeVarFreeExpr(ctx context.Context, expr tree.Expr, expectedType *types.T, context string, ...) (tree.TypedExpr, error)
- func ValidateColumnHasNoDependents(desc catalog.TableDescriptor, col catalog.Column) error
- func ValidateComputedColumnExpression(ctx context.Context, desc catalog.TableDescriptor, d *tree.ColumnTableDef, ...) (serializedExpr string, _ *types.T, _ error)
- func ValidatePartialIndexPredicate(ctx context.Context, desc catalog.TableDescriptor, e tree.Expr, ...) (string, error)
- func ValidateUniqueWithoutIndexPredicate(ctx context.Context, tn tree.TableName, desc catalog.TableDescriptor, ...) (string, error)
- type CheckConstraintBuilder
- type ComputedColumnRewritesMap
- type NameResolutionVisitor
- type RowIndexedVarContainer
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CannotWriteToComputedColError ¶
CannotWriteToComputedColError constructs a write error for a computed column.
func DequalifyAndTypeCheckExpr ¶
func DequalifyAndTypeCheckExpr( ctx context.Context, desc catalog.TableDescriptor, expr tree.Expr, semaCtx *tree.SemaContext, tn *tree.TableName, ) (tree.TypedExpr, error)
DequalifyAndTypeCheckExpr type checks the given expression and returns the type-checked expression disregarding volatility. The typed expression, which contains dummyColumns, does not support evaluation.
func DequalifyAndValidateExpr ¶
func DequalifyAndValidateExpr( ctx context.Context, desc catalog.TableDescriptor, expr tree.Expr, typ *types.T, context string, semaCtx *tree.SemaContext, maxVolatility tree.Volatility, tn *tree.TableName, ) (string, *types.T, catalog.TableColSet, error)
DequalifyAndValidateExpr validates that an expression has the given type and contains no functions with a volatility greater than maxVolatility. The type-checked and constant-folded expression, the type of the expression, and the set of column IDs within the expression are returned, if valid.
The serialized expression is returned because returning the created tree.TypedExpr would be dangerous. It contains dummyColumns which do not support evaluation and are not useful outside the context of type-checking the expression.
func DequalifyColumnRefs ¶
func DequalifyColumnRefs( ctx context.Context, source *colinfo.DataSourceInfo, expr tree.Expr, ) (string, error)
DequalifyColumnRefs returns a serialized expression with database and table names stripped from qualified column names.
For example:
tab.a > 0 AND db.tab.b = 'foo' => a > 0 AND b = 'foo'
This dequalification is necessary when CHECK constraints, computed columns, or partial index predicates are created. If the table name was not stripped, these expressions would become invalid if the table is renamed.
func ExtractColumnIDs ¶
func ExtractColumnIDs( desc catalog.TableDescriptor, rootExpr tree.Expr, ) (catalog.TableColSet, error)
ExtractColumnIDs returns the set of column IDs within the given expression.
func FormatColumnForDisplay ¶
func FormatColumnForDisplay( ctx context.Context, tbl catalog.TableDescriptor, col catalog.Column, semaCtx *tree.SemaContext, sessionData *sessiondata.SessionData, ) (string, error)
FormatColumnForDisplay formats a column descriptor as a SQL string. It converts user defined types in default and computed expressions to a human-readable form.
func FormatExprForDisplay ¶
func FormatExprForDisplay( ctx context.Context, desc catalog.TableDescriptor, exprStr string, semaCtx *tree.SemaContext, sessionData *sessiondata.SessionData, fmtFlags tree.FmtFlags, ) (string, error)
FormatExprForDisplay formats a schema expression string for display. It accepts formatting flags to control things like showing type annotations or type casts.
func FormatExprForExpressionIndexDisplay ¶
func FormatExprForExpressionIndexDisplay( ctx context.Context, desc catalog.TableDescriptor, exprStr string, semaCtx *tree.SemaContext, sessionData *sessiondata.SessionData, fmtFlags tree.FmtFlags, ) (string, error)
FormatExprForExpressionIndexDisplay formats an expression index's expression element string for display. It is similar to FormatExprForDisplay. The only difference is that non-function expressions will be wrapped in parentheses to match the parsing requirements for expression indexes.
func GetSeqIDFromExpr ¶
GetSeqIDFromExpr takes an expr and looks for a sequence ID in this expr. If it finds one, it will return that ID.
func HasValidColumnReferences ¶
HasValidColumnReferences returns true if all columns referenced in rootExpr exist in desc.
func MakeComputedExprs ¶
func MakeComputedExprs( ctx context.Context, input, sourceColumns []catalog.Column, tableDesc catalog.TableDescriptor, tn *tree.TableName, evalCtx *tree.EvalContext, semaCtx *tree.SemaContext, ) (_ []tree.TypedExpr, refColIDs catalog.TableColSet, _ error)
MakeComputedExprs returns a slice of the computed expressions for the slice of input column descriptors, or nil if none of the input column descriptors have computed expressions. The caller provides the set of sourceColumns to which the expr may refer.
The length of the result slice matches the length of the input column descriptors. For every column that has no computed expression, a NULL expression is reported.
Note that the order of input is critical. Expressions cannot reference columns that come after them in input.
func MakeDefaultExprs ¶
func MakeDefaultExprs( ctx context.Context, cols []catalog.Column, txCtx *transform.ExprTransformContext, evalCtx *tree.EvalContext, semaCtx *tree.SemaContext, ) ([]tree.TypedExpr, error)
MakeDefaultExprs returns a slice of the default expressions for the slice of input column descriptors, or nil if none of the input column descriptors have default expressions. The length of the result slice matches the length of the input column descriptors. For every column that has no default expression, a NULL expression is reported as default.
func MakeHashShardComputeExpr ¶
MakeHashShardComputeExpr creates the serialized computed expression for a hash shard column based on the column names and the number of buckets. The expression will be of the form:
mod(fnv32(crdb_internal.datums_to_bytes(...)),buckets)
func MakePartialIndexExprs ¶
func MakePartialIndexExprs( ctx context.Context, indexes []catalog.Index, cols []catalog.Column, tableDesc catalog.TableDescriptor, evalCtx *tree.EvalContext, semaCtx *tree.SemaContext, ) (_ map[descpb.IndexID]tree.TypedExpr, refColIDs catalog.TableColSet, _ error)
MakePartialIndexExprs returns a map of predicate expressions for each partial index in the input list of indexes, or nil if none of the indexes are partial indexes. It also returns a set of all column IDs referenced in the expressions.
If the expressions are being built within the context of an index add mutation in a transaction, the cols argument must include mutation columns that are added previously in the same transaction.
func MaybeRewriteComputedColumn ¶
func MaybeRewriteComputedColumn(expr tree.Expr, sessionData *sessiondata.SessionData) tree.Expr
MaybeRewriteComputedColumn consults the experimental_computed_column_rewrites session setting; if the given expression matches a "before expression" in the setting, it is replaced to the corresponding "after expression". Otherwise, the given expression is returned unchanged.
func ProcessColumnSet ¶
func ProcessColumnSet( cols []catalog.Column, tableDesc catalog.TableDescriptor, inSet func(column catalog.Column) bool, ) []catalog.Column
ProcessColumnSet returns columns in cols, and other writable columns in tableDesc that fulfills a given criteria in inSet.
func RenameColumn ¶
RenameColumn replaces any occurrence of the column from in expr with to, and returns a string representation of the new expression.
func ReplaceColumnVars ¶
func ReplaceColumnVars( rootExpr tree.Expr, columnLookupFn func(columnName tree.Name) (exists bool, accessible bool, id catid.ColumnID, typ *types.T), ) (tree.Expr, catalog.TableColSet, error)
ReplaceColumnVars replaces the occurrences of column names in an expression with dummyColumns containing their type, so that they may be type-checked. It returns this new expression tree alongside a set containing the ColumnID of each column seen in the expression.
If the expression references a column that does not exist in the table descriptor, replaceColumnVars errs with pgcode.UndefinedColumn.
The column lookup function allows looking up columns both in the descriptor or in declarative schema changer elements.
func ReplaceIDsWithFQNames ¶
func ReplaceIDsWithFQNames( ctx context.Context, rootExpr tree.Expr, semaCtx *tree.SemaContext, ) (tree.Expr, error)
ReplaceIDsWithFQNames walks the given expr and replaces occurrences of regclass IDs in the expr with the descriptor's fully qualified name. For example, nextval(12345::REGCLASS) => nextval('foo.public.seq').
func ResolveNamesUsingVisitor ¶
func ResolveNamesUsingVisitor( v *NameResolutionVisitor, expr tree.Expr, source *colinfo.DataSourceInfo, ivarHelper tree.IndexedVarHelper, searchPath sessiondata.SearchPath, ) (tree.Expr, error)
ResolveNamesUsingVisitor resolves the names in the given expression.
func SanitizeVarFreeExpr ¶
func SanitizeVarFreeExpr( ctx context.Context, expr tree.Expr, expectedType *types.T, context string, semaCtx *tree.SemaContext, maxVolatility tree.Volatility, ) (tree.TypedExpr, error)
SanitizeVarFreeExpr verifies that an expression is valid, has the correct type and contains no variable expressions. It returns the type-checked and constant-folded expression.
func ValidateColumnHasNoDependents ¶
func ValidateColumnHasNoDependents(desc catalog.TableDescriptor, col catalog.Column) error
ValidateColumnHasNoDependents verifies that the input column has no dependent computed columns. It returns an error if any existing or ADD mutation computed columns reference the given column. TODO(mgartner): Add unit tests.
func ValidateComputedColumnExpression ¶
func ValidateComputedColumnExpression( ctx context.Context, desc catalog.TableDescriptor, d *tree.ColumnTableDef, tn *tree.TableName, context string, semaCtx *tree.SemaContext, ) (serializedExpr string, _ *types.T, _ error)
ValidateComputedColumnExpression verifies that an expression is a valid computed column expression. It returns the serialized expression and its type if valid, and an error otherwise. The returned type is only useful if d has type Any which indicates the expression's type is unknown and does not have to match a specific type.
A computed column expression is valid if all of the following are true:
- It does not have a default value.
- It does not reference other computed columns.
TODO(mgartner): Add unit tests for Validate.
func ValidatePartialIndexPredicate ¶
func ValidatePartialIndexPredicate( ctx context.Context, desc catalog.TableDescriptor, e tree.Expr, tn *tree.TableName, semaCtx *tree.SemaContext, ) (string, error)
ValidatePartialIndexPredicate verifies that an expression is a valid partial index predicate. If the expression is valid, it returns the serialized expression with the columns dequalified.
A predicate expression is valid if all of the following are true:
- It results in a boolean.
- It refers only to columns in the table.
- It does not include subqueries.
- It does not include non-immutable, aggregate, window, or set returning functions.
func ValidateUniqueWithoutIndexPredicate ¶
func ValidateUniqueWithoutIndexPredicate( ctx context.Context, tn tree.TableName, desc catalog.TableDescriptor, pred tree.Expr, semaCtx *tree.SemaContext, ) (string, error)
ValidateUniqueWithoutIndexPredicate verifies that an expression is a valid unique without index predicate. If the expression is valid, it returns the serialized expression with the columns dequalified.
A predicate expression is valid if all of the following are true:
- It results in a boolean.
- It refers only to columns in the table.
- It does not include subqueries.
- It does not include non-immutable, aggregate, window, or set returning functions.
Types ¶
type CheckConstraintBuilder ¶
type CheckConstraintBuilder struct {
// contains filtered or unexported fields
}
CheckConstraintBuilder creates descpb.TableDescriptor_CheckConstraints from tree.CheckConstraintTableDefs. See Build for more details.
func MakeCheckConstraintBuilder ¶
func MakeCheckConstraintBuilder( ctx context.Context, tableName tree.TableName, desc catalog.TableDescriptor, semaCtx *tree.SemaContext, ) CheckConstraintBuilder
MakeCheckConstraintBuilder returns a CheckConstraintBuilder struct that can be used to build descpb.TableDescriptor_CheckConstraints. See Build for more details.
func (*CheckConstraintBuilder) Build ¶
func (b *CheckConstraintBuilder) Build( c *tree.CheckConstraintTableDef, ) (*descpb.TableDescriptor_CheckConstraint, error)
Build validates the input tree.CheckConstraintTableDef and, if valid, returns a descpb.TableDescriptor_CheckConstraint. If the input constraint does not have a name, Build generates a name based on the variables referenced in the check expression.
A check constraint expression is valid if the following are true:
- It results in a boolean.
- It refers only to columns in the table.
- It does not include subqueries.
- It does not include aggregate, window, or set returning functions.
Note that mutable functions are currently allowed, unlike in partial index predicates, but using them can lead to unexpected behavior.
func (*CheckConstraintBuilder) DefaultName ¶
func (b *CheckConstraintBuilder) DefaultName(expr tree.Expr) (string, error)
DefaultName creates a check constraint name based on the columns referenced in the check expression. The format is "check_col1_col2...". If columns are duplicated in the expression, they will be duplicated in the name.
For example:
CHECK (a < 0) => check_a CHECK (a < 0 AND b = 'foo') => check_a_b CHECK (a < 0 AND b = 'foo' AND a < 10) => check_a_b_a
Note that the generated name is not guaranteed to be unique among the other constraints of the table.
func (*CheckConstraintBuilder) MarkNameInUse ¶
func (b *CheckConstraintBuilder) MarkNameInUse(name string)
MarkNameInUse marks a name as in-use, preventing subsequent calls to Build from generating a check constraint with the same name.
type ComputedColumnRewritesMap ¶
ComputedColumnRewritesMap stores a map of computed column expression rewrites. The key is a formatted AST (using tree.Serialize()).
func ParseComputedColumnRewrites ¶
func ParseComputedColumnRewrites(val string) (ComputedColumnRewritesMap, error)
ParseComputedColumnRewrites parses a string of the form:
(before expression) -> (after expression) [, (before expression) -> (after expression) ...]
into a ComputedColumnRewritesMap.
Used to implement the experimental_computed_column_rewrites session setting.
type NameResolutionVisitor ¶
type NameResolutionVisitor struct {
// contains filtered or unexported fields
}
NameResolutionVisitor is a tree.Visitor implementation used to resolve the column names in an expression.
type RowIndexedVarContainer ¶
type RowIndexedVarContainer struct {
CurSourceRow tree.Datums
Cols []catalog.Column
Mapping catalog.TableColMap
}
RowIndexedVarContainer is used to evaluate expressions over various rows.
func (*RowIndexedVarContainer) IndexedVarEval ¶
func (r *RowIndexedVarContainer) IndexedVarEval( idx int, ctx *tree.EvalContext, ) (tree.Datum, error)
IndexedVarEval implements tree.IndexedVarContainer.
func (*RowIndexedVarContainer) IndexedVarNodeFormatter ¶
func (*RowIndexedVarContainer) IndexedVarNodeFormatter(idx int) tree.NodeFormatter
IndexedVarNodeFormatter implements tree.IndexedVarContainer.
func (*RowIndexedVarContainer) IndexedVarResolvedType ¶
func (*RowIndexedVarContainer) IndexedVarResolvedType(idx int) *types.T
IndexedVarResolvedType implements tree.IndexedVarContainer.