package analysis
Provides a logical query plan Analyzer and supporting classes for performing analysis. Analysis consists of translating UnresolvedAttributes and UnresolvedRelations into fully typed objects using information in a schema Catalog.
- Alphabetic
- By Inheritance
- analysis
- AnyRef
- Any
- Hide All
- Show All
- Public
- All
Type Members
-
case class
AnalysisContext(catalogAndNamespace: Seq[String] = Nil, nestedViewDepth: Int = 0, maxNestedViewDepth: Int = -1, relationCache: Map[(Seq[String], Option[TimeTravelSpec]), LogicalPlan] = mutable.Map.empty, referredTempViewNames: Seq[Seq[String]] = Seq.empty, referredTempFunctionNames: Set[String] = mutable.Set.empty, outerPlan: Option[LogicalPlan] = None) extends Product with Serializable
Provides a way to keep state during the analysis, mostly for resolving views and subqueries.
Provides a way to keep state during the analysis, mostly for resolving views and subqueries. This enables us to decouple the concerns of analysis environment from the catalog and resolve star expressions in subqueries that reference the outer query plans. The state that is kept here is per-query.
Note this is thread local.
- catalogAndNamespace
The catalog and namespace used in the view resolution. This overrides the current catalog and namespace when resolving relations inside views.
- nestedViewDepth
The nested depth in the view resolution, this enables us to limit the depth of nested views.
- maxNestedViewDepth
The maximum allowed depth of nested view resolution.
- relationCache
A mapping from qualified table names and time travel spec to resolved relations. This can ensure that the table is resolved only once if a table is used multiple times in a query.
- referredTempViewNames
All the temp view names referred by the current view we are resolving. It's used to make sure the relation resolution is consistent between view creation and view resolution. For example, if
twas a permanent table when the current view was created, it should still be a permanent table when resolving the current view, even if a temp viewthas been created.- outerPlan
The query plan from the outer query that can be used to resolve star expressions in a subquery.
- implicit class AnalysisErrorAt extends AnyRef
-
class
Analyzer extends RuleExecutor[LogicalPlan] with CheckAnalysis with SQLConfHelper
Provides a logical query plan analyzer, which translates UnresolvedAttributes and UnresolvedRelations into fully typed objects using information in a SessionCatalog.
- case class AsOfTimestamp(timestamp: Long) extends TimeTravelSpec with Product with Serializable
- case class AsOfVersion(version: String) extends TimeTravelSpec with Product with Serializable
- class CannotReplaceMissingTableException extends AnalysisException
-
trait
CastSupport extends AnyRef
Mix-in trait for constructing valid Cast expressions.
-
trait
CheckAnalysis extends PredicateHelper with LookupCatalog
Throws user facing errors when passed invalid queries that fail to analyze.
-
class
DatabaseAlreadyExistsException extends NamespaceAlreadyExistsException
Thrown by a catalog when an item already exists.
Thrown by a catalog when an item already exists. The analyzer will rethrow the exception as an org.apache.spark.sql.AnalysisException with the correct position information.
-
trait
EmptyFunctionRegistryBase[T] extends FunctionRegistryBase[T]
A trivial catalog that returns an error when a function is requested.
A trivial catalog that returns an error when a function is requested. Used for testing when all functions are already filled in and the analyzer needs only to resolve attribute references.
- trait ExpressionBuilder extends AnyRef
- sealed trait FieldName extends LeafExpression with Unevaluable
- sealed trait FieldPosition extends LeafExpression with Unevaluable
- class FunctionAlreadyExistsException extends AnalysisException
- trait FunctionRegistry extends FunctionRegistryBase[Expression]
-
trait
FunctionRegistryBase[T] extends AnyRef
A catalog for looking up user defined functions, used by an Analyzer.
A catalog for looking up user defined functions, used by an Analyzer.
Note: 1) The implementation should be thread-safe to allow concurrent access. 2) the database name is always case-sensitive here, callers are responsible to format the database name w.r.t. case-sensitive config.
- case class GetColumnByOrdinal(ordinal: Int, dataType: DataType) extends LeafExpression with Unevaluable with NonSQLExpression with Product with Serializable
- case class GetViewColumnByNameAndOrdinal(viewName: String, colName: String, ordinal: Int, expectedNumCandidates: Int, viewDDL: Option[String]) extends LeafExpression with Unevaluable with NonSQLExpression with Product with Serializable
- class IndexAlreadyExistsException extends AnalysisException
-
trait
LeafNodeWithoutStats extends LogicalPlan with LeafNode
A resolved leaf node whose statistics has no meaning.
-
case class
MultiAlias(child: Expression, names: Seq[String]) extends UnaryExpression with NamedExpression with Unevaluable with Product with Serializable
Used to assign new names to Generator's output, such as hive udtf.
Used to assign new names to Generator's output, such as hive udtf. For example the SQL expression "stack(2, key, value, key, value) as (a, b)" could be represented as follows: MultiAlias(stack_function, Seq(a, b))
- child
the computation being performed
- names
the names to be associated with each output of computing child.
-
trait
MultiInstanceRelation extends AnyRef
A trait that should be mixed into query operators where a single instance might appear multiple times in a logical query plan.
A trait that should be mixed into query operators where a single instance might appear multiple times in a logical query plan. It is invalid to have multiple copies of the same attribute produced by distinct operators in a query tree as this breaks the guarantee that expression ids, which are used to differentiate attributes, are unique.
During analysis, operators that include this trait may be asked to produce a new version of itself with globally unique expression ids.
- trait NamedRelation extends LogicalPlan
- class NamespaceAlreadyExistsException extends AnalysisException
-
case class
NoSuchDatabaseException(db: String) extends AnalysisException with Product with Serializable
Thrown by a catalog when an item cannot be found.
Thrown by a catalog when an item cannot be found. The analyzer will rethrow the exception as an org.apache.spark.sql.AnalysisException with the correct position information.
- case class NoSuchFunctionException(message: String, cause: Option[Throwable]) extends AnalysisException with Product with Serializable
- class NoSuchIndexException extends AnalysisException
- case class NoSuchNamespaceException(message: String, cause: Option[Throwable] = None) extends AnalysisException with Product with Serializable
- case class NoSuchPartitionException(message: String) extends AnalysisException with Product with Serializable
- case class NoSuchPartitionsException(message: String) extends AnalysisException with Product with Serializable
- case class NoSuchPermanentFunctionException(db: String, func: String) extends AnalysisException with Product with Serializable
- case class NoSuchTableException(message: String, cause: Option[Throwable] = None) extends AnalysisException with Product with Serializable
- case class NoSuchTempFunctionException(func: String) extends AnalysisException with Product with Serializable
-
case class
NonEmptyNamespaceException(message: String, cause: Option[Throwable] = None) extends AnalysisException with Product with Serializable
Thrown by a catalog when an item already exists.
Thrown by a catalog when an item already exists. The analyzer will rethrow the exception as an org.apache.spark.sql.AnalysisException with the correct position information.
- class PartitionAlreadyExistsException extends AnalysisException
- sealed trait PartitionSpec extends LeafExpression with Unevaluable
- class PartitionsAlreadyExistException extends AnalysisException
-
case class
ReferenceEqualPlanWrapper(plan: LogicalPlan) extends Product with Serializable
A helper class used to detect duplicate relations fast in
DeduplicateRelations -
case class
RelationTimeTravel(relation: LogicalPlan, timestamp: Option[Expression], version: Option[String]) extends LogicalPlan with LeafNode with Product with Serializable
A logical node used to time travel the child relation to the given
timestamporversion.A logical node used to time travel the child relation to the given
timestamporversion. Thechildmust support time travel, e.g. a v2 source, and cannot be a view, subquery or stream. The timestamp expression cannot refer to any columns and cannot contain subqueries. -
class
ResolveCatalogs extends Rule[LogicalPlan] with LookupCatalog
Resolves catalogs from the multi-part identifiers in SQL statements, and convert the statements to the corresponding v2 commands if the resolved catalog is not the session catalog.
-
case class
ResolveTableValuedFunctions(catalog: SessionCatalog) extends Rule[LogicalPlan] with Product with Serializable
Rule that resolves table-valued function references.
-
case class
ResolvedDBObjectName(catalog: CatalogPlugin, nameParts: Seq[String]) extends LogicalPlan with LeafNodeWithoutStats with Product with Serializable
A plan containing resolved database object name with catalog determined.
- case class ResolvedFieldName(path: Seq[String], field: StructField) extends LeafExpression with FieldName with Product with Serializable
- case class ResolvedFieldPosition(position: ColumnPosition) extends LeafExpression with FieldPosition with Product with Serializable
-
case class
ResolvedNamespace(catalog: CatalogPlugin, namespace: Seq[String]) extends LogicalPlan with LeafNodeWithoutStats with Product with Serializable
A plan containing resolved namespace.
-
case class
ResolvedNonPersistentFunc(name: String, func: UnboundFunction) extends LogicalPlan with LeafNodeWithoutStats with Product with Serializable
A plan containing resolved non-persistent (temp or built-in) function.
- case class ResolvedPartitionSpec(names: Seq[String], ident: InternalRow, location: Option[String] = None) extends LeafExpression with PartitionSpec with Product with Serializable
-
case class
ResolvedPersistentFunc(catalog: FunctionCatalog, identifier: Identifier, func: UnboundFunction) extends LogicalPlan with LeafNodeWithoutStats with Product with Serializable
A plan containing resolved persistent function.
-
case class
ResolvedStar(expressions: Seq[NamedExpression]) extends Star with Unevaluable with Product with Serializable
Represents all the resolved input attributes to a given relational operator.
Represents all the resolved input attributes to a given relational operator. This is used in the data frame DSL.
- expressions
Expressions to expand.
-
case class
ResolvedTable(catalog: TableCatalog, identifier: Identifier, table: Table, outputAttributes: Seq[Attribute]) extends LogicalPlan with LeafNodeWithoutStats with Product with Serializable
A plan containing resolved table.
-
case class
ResolvedView(identifier: Identifier, isTemp: Boolean) extends LogicalPlan with LeafNodeWithoutStats with Product with Serializable
A plan containing resolved (temp) views.
-
type
Resolver = (String, String) ⇒ Boolean
Resolver should return true if the first string refers to the same entity as the second string.
Resolver should return true if the first string refers to the same entity as the second string. For example, by using case insensitive equality.
- trait RewriteRowLevelCommand extends Rule[LogicalPlan]
- class SimpleFunctionRegistry extends SimpleFunctionRegistryBase[Expression] with FunctionRegistry
- trait SimpleFunctionRegistryBase[T] extends FunctionRegistryBase[T] with Logging
- class SimpleTableFunctionRegistry extends SimpleFunctionRegistryBase[LogicalPlan] with TableFunctionRegistry
-
abstract
class
Star extends LeafExpression with NamedExpression
Represents all of the input attributes to a given relational operator, for example in "SELECT * FROM ...".
Represents all of the input attributes to a given relational operator, for example in "SELECT * FROM ...". A Star gets automatically expanded during analysis.
- class TableAlreadyExistsException extends AnalysisException
-
trait
TableFunctionRegistry extends FunctionRegistryBase[LogicalPlan]
A catalog for looking up table functions.
-
case class
TempResolvedColumn(child: Expression, nameParts: Seq[String]) extends UnaryExpression with Unevaluable with Product with Serializable
An intermediate expression to hold a resolved (nested) column.
An intermediate expression to hold a resolved (nested) column. Some rules may need to undo the column resolution and use this expression to keep the original column name.
- class TempTableAlreadyExistsException extends TableAlreadyExistsException
- sealed trait TimeTravelSpec extends AnyRef
-
trait
TypeCheckResult extends AnyRef
Represents the result of
Expression.checkInputDataTypes.Represents the result of
Expression.checkInputDataTypes. We will throwAnalysisExceptioninCheckAnalysisifisFailureis true. - abstract class TypeCoercionBase extends AnyRef
- trait TypeCoercionRule extends Rule[LogicalPlan] with Logging
-
case class
UnresolvedAlias(child: Expression, aliasFunc: Option[(Expression) ⇒ String] = None) extends UnaryExpression with NamedExpression with Unevaluable with Product with Serializable
Holds the expression that has yet to be aliased.
Holds the expression that has yet to be aliased.
- child
The computation that is needs to be resolved during analysis.
- aliasFunc
The function if specified to be called to generate an alias to associate with the result of computing child
-
case class
UnresolvedAttribute(nameParts: Seq[String]) extends Attribute with Unevaluable with Product with Serializable
Holds the name of an attribute that has yet to be resolved.
-
case class
UnresolvedDBObjectName(nameParts: Seq[String], isNamespace: Boolean) extends LogicalPlan with LeafNode with Product with Serializable
Holds the name of a database object (table, view, namespace, function, etc.) that is to be created and we need to determine the catalog to store it.
Holds the name of a database object (table, view, namespace, function, etc.) that is to be created and we need to determine the catalog to store it. It will be resolved to ResolvedDBObjectName during analysis.
-
case class
UnresolvedDeserializer(deserializer: Expression, inputAttributes: Seq[Attribute] = Nil) extends UnaryExpression with Unevaluable with NonSQLExpression with Product with Serializable
Holds the deserializer expression and the attributes that are available during the resolution for it.
Holds the deserializer expression and the attributes that are available during the resolution for it. Deserializer expression is a special kind of expression that is not always resolved by children output, but by given attributes, e.g. the
keyDeserializerinMapGroupsshould be resolved bygroupingAttributesinstead of children output.- deserializer
The unresolved deserializer expression
- inputAttributes
The input attributes used to resolve deserializer expression, can be empty if we want to resolve deserializer by children output.
-
class
UnresolvedException extends AnalysisException
Thrown when an invalid attempt is made to access a property of a tree that has yet to be fully resolved.
-
case class
UnresolvedExtractValue(child: Expression, extraction: Expression) extends BinaryExpression with Unevaluable with Product with Serializable
Extracts a value or values from an Expression
Extracts a value or values from an Expression
- child
The expression to extract value from, can be Map, Array, Struct or array of Structs.
- extraction
The expression to describe the extraction, can be key of Map, index of Array, field name of Struct.
- case class UnresolvedFieldName(name: Seq[String]) extends LeafExpression with FieldName with Product with Serializable
- case class UnresolvedFieldPosition(position: ColumnPosition) extends LeafExpression with FieldPosition with Product with Serializable
-
case class
UnresolvedFunc(multipartIdentifier: Seq[String], commandName: String, requirePersistent: Boolean, funcTypeMismatchHint: Option[String], possibleQualifiedName: Option[Seq[String]] = None) extends LogicalPlan with LeafNode with Product with Serializable
Holds the name of a function that has yet to be looked up.
Holds the name of a function that has yet to be looked up. It will be resolved to ResolvedPersistentFunc or ResolvedNonPersistentFunc during analysis.
- case class UnresolvedFunction(nameParts: Seq[String], arguments: Seq[Expression], isDistinct: Boolean, filter: Option[Expression] = None, ignoreNulls: Boolean = false) extends Expression with Unevaluable with Product with Serializable
-
case class
UnresolvedGenerator(name: FunctionIdentifier, children: Seq[Expression]) extends Expression with Generator with Product with Serializable
Represents an unresolved generator, which will be created by the parser for the org.apache.spark.sql.catalyst.plans.logical.Generate operator.
Represents an unresolved generator, which will be created by the parser for the org.apache.spark.sql.catalyst.plans.logical.Generate operator. The analyzer will resolve this generator.
-
case class
UnresolvedHaving(havingCondition: Expression, child: LogicalPlan) extends LogicalPlan with UnaryNode with Product with Serializable
Represents unresolved having clause, the child for it can be Aggregate, GroupingSets, Rollup and Cube.
Represents unresolved having clause, the child for it can be Aggregate, GroupingSets, Rollup and Cube. It is turned by the analyzer into a Filter.
-
case class
UnresolvedInlineTable(names: Seq[String], rows: Seq[Seq[Expression]]) extends LogicalPlan with LeafNode with Product with Serializable
An inline table that has not been resolved yet.
An inline table that has not been resolved yet. Once resolved, it is turned by the analyzer into a org.apache.spark.sql.catalyst.plans.logical.LocalRelation.
- names
list of column names
- rows
expressions for the data
-
case class
UnresolvedNamespace(multipartIdentifier: Seq[String]) extends LogicalPlan with LeafNode with Product with Serializable
Holds the name of a namespace that has yet to be looked up in a catalog.
Holds the name of a namespace that has yet to be looked up in a catalog. It will be resolved to ResolvedNamespace during analysis.
-
case class
UnresolvedOrdinal(ordinal: Int) extends LeafExpression with Unevaluable with NonSQLExpression with Product with Serializable
Represents unresolved ordinal used in order by or group by.
Represents unresolved ordinal used in order by or group by.
For example:
select a from table order by 1 select a from table group by 1
- ordinal
ordinal starts from 1, instead of 0
- case class UnresolvedPartitionSpec(spec: TablePartitionSpec, location: Option[String] = None) extends LeafExpression with PartitionSpec with Product with Serializable
-
case class
UnresolvedRegex(regexPattern: String, table: Option[String], caseSensitive: Boolean) extends Star with Unevaluable with Product with Serializable
Represents all of the input attributes to a given relational operator, for example in "SELECT
(id)?+.+FROM ...".Represents all of the input attributes to a given relational operator, for example in "SELECT
(id)?+.+FROM ...".- table
an optional table that should be the target of the expansion. If omitted all tables' columns are produced.
-
case class
UnresolvedRelation(multipartIdentifier: Seq[String], options: CaseInsensitiveStringMap = CaseInsensitiveStringMap.empty(), isStreaming: Boolean = false) extends LogicalPlan with LeafNode with NamedRelation with Product with Serializable
Holds the name of a relation that has yet to be looked up in a catalog.
Holds the name of a relation that has yet to be looked up in a catalog.
- multipartIdentifier
table name
- options
options to scan this relation.
-
case class
UnresolvedStar(target: Option[Seq[String]]) extends Star with Unevaluable with Product with Serializable
Represents all of the input attributes to a given relational operator, for example in "SELECT * FROM ...".
Represents all of the input attributes to a given relational operator, for example in "SELECT * FROM ...".
This is also used to expand structs. For example: "SELECT record.* from (SELECT struct(a,b,c) as record ...)
- target
an optional name that should be the target of the expansion. If omitted all targets' columns are produced. This can either be a table name or struct name. This is a list of identifiers that is the path of the expansion.
-
case class
UnresolvedSubqueryColumnAliases(outputColumnNames: Seq[String], child: LogicalPlan) extends LogicalPlan with UnaryNode with Product with Serializable
Aliased column names resolved by positions for subquery.
Aliased column names resolved by positions for subquery. We could add alias names for output columns in the subquery:
// Assign alias names for output columns SELECT col1, col2 FROM testData AS t(col1, col2);- outputColumnNames
the LogicalPlan on which this subquery column aliases apply.
- child
the logical plan of this subquery.
-
case class
UnresolvedTable(multipartIdentifier: Seq[String], commandName: String, relationTypeMismatchHint: Option[String]) extends LogicalPlan with LeafNode with Product with Serializable
Holds the name of a table that has yet to be looked up in a catalog.
Holds the name of a table that has yet to be looked up in a catalog. It will be resolved to ResolvedTable during analysis.
-
case class
UnresolvedTableOrView(multipartIdentifier: Seq[String], commandName: String, allowTempView: Boolean) extends LogicalPlan with LeafNode with Product with Serializable
Holds the name of a table or view that has yet to be looked up in a catalog.
Holds the name of a table or view that has yet to be looked up in a catalog. It will be resolved to ResolvedTable or ResolvedView during analysis.
-
case class
UnresolvedTableValuedFunction(name: FunctionIdentifier, functionArgs: Seq[Expression], outputNames: Seq[String]) extends LogicalPlan with LeafNode with Product with Serializable
A table-valued function, e.g.
A table-valued function, e.g.
select id from range(10); // Assign alias names select t.a from range(10) t(a);
- name
qualified name of this table-value function
- functionArgs
list of function arguments
- outputNames
alias names of function output columns. If these names given, an analyzer adds Project to rename the output columns.
-
case class
UnresolvedView(multipartIdentifier: Seq[String], commandName: String, allowTemp: Boolean, relationTypeMismatchHint: Option[String]) extends LogicalPlan with LeafNode with Product with Serializable
Holds the name of a view that has yet to be looked up.
Holds the name of a view that has yet to be looked up. It will be resolved to ResolvedView during analysis.
-
sealed
trait
ViewType extends AnyRef
ViewType is used to specify the expected view type when we want to create or replace a view in CreateViewStatement.
Value Members
- val caseInsensitiveResolution: (String, String) ⇒ Boolean
- val caseSensitiveResolution: (String, String) ⇒ Boolean
-
def
withPosition[A](t: TreeNode[_])(f: ⇒ A): A
Catches any AnalysisExceptions thrown by
fand attachest's position if any. - object AnalysisContext extends Serializable
-
object
AnsiTypeCoercion extends TypeCoercionBase
In Spark ANSI mode, the type coercion rules are based on the type precedence lists of the input data types.
In Spark ANSI mode, the type coercion rules are based on the type precedence lists of the input data types. As per the section "Type precedence list determination" of "ISO/IEC 9075-2:2011 Information technology - Database languages - SQL - Part 2: Foundation (SQL/Foundation)", the type precedence lists of primitive data types are as following: * Byte: Byte, Short, Int, Long, Decimal, Float, Double * Short: Short, Int, Long, Decimal, Float, Double * Int: Int, Long, Decimal, Float, Double * Long: Long, Decimal, Float, Double * Decimal: Float, Double, or any wider Numeric type * Float: Float, Double * Double: Double * String: String * Date: Date, Timestamp * Timestamp: Timestamp * Binary: Binary * Boolean: Boolean * Interval: Interval As for complex data types, Spark will determine the precedent list recursively based on their sub-types and nullability.
With the definition of type precedent list, the general type coercion rules are as following: * Data type S is allowed to be implicitly cast as type T iff T is in the precedence list of S * Comparison is allowed iff the data type precedence list of both sides has at least one common element. When evaluating the comparison, Spark casts both sides as the tightest common data type of their precedent lists. * There should be at least one common data type among all the children's precedence lists for the following operators. The data type of the operator is the tightest common precedent data type. * In * Except * Intersect * Greatest * Least * Union * If * CaseWhen * CreateArray * Array Concat * Sequence * MapConcat * CreateMap * For complex types (struct, array, map), Spark recursively looks into the element type and applies the rules above. Note: this new type coercion system will allow implicit converting String type as other primitive types, in case of breaking too many existing Spark SQL queries. This is a special rule and it is not from the ANSI SQL standard.
-
object
ApplyCharTypePadding extends Rule[LogicalPlan]
This rule performs string padding for char type comparison.
This rule performs string padding for char type comparison.
When comparing char type column/field with string literal or char type column/field, right-pad the shorter one to the longer length.
-
object
CTESubstitution extends Rule[LogicalPlan]
Analyze WITH nodes and substitute child plan with CTE references or CTE definitions depending on the conditions below: 1.
Analyze WITH nodes and substitute child plan with CTE references or CTE definitions depending on the conditions below: 1. If in legacy mode, or if the query is a SQL command or DML statement, replace with CTE definitions, i.e., inline CTEs. 2. Otherwise, replace with CTE references
CTERelationRefs. The decision to inline or not inline will be made later by the ruleInlineCTEafter query analysis.All the CTE definitions that are not inlined after this substitution will be grouped together under one
WithCTEnode for each of the main query and the subqueries. Any of the main query or the subqueries that do not contain CTEs or have had all CTEs inlined will obviously not have anyWithCTEnodes. If any though, theWithCTEnode will be in the same place as where the outermostWithnode once was.The CTE definitions in a
WithCTEnode are kept in the order of how they have been resolved. That means the CTE definitions are guaranteed to be in topological order base on their dependency for any valid CTE query (i.e., given CTE definitions A and B with B referencing A, A is guaranteed to appear before B). Otherwise, it must be an invalid user query, and an analysis exception will be thrown later by relation resolving rules. -
object
CleanupAliases extends Rule[LogicalPlan] with AliasHelper
Cleans up unnecessary Aliases inside the plan.
Cleans up unnecessary Aliases inside the plan. Basically we only need Alias as a top level expression in Project(project list) or Aggregate(aggregate expressions) or Window(window expressions). Notice that if an expression has other expression parameters which are not in its
children, e.g.RuntimeReplaceable, the transformation for Aliases in this rule can't work for those parameters. -
object
DecimalPrecision extends Rule[LogicalPlan] with TypeCoercionRule
Calculates and propagates precision for fixed-precision decimals.
Calculates and propagates precision for fixed-precision decimals. Hive has a number of rules for this based on the SQL standard and MS SQL: https://cwiki.apache.org/confluence/download/attachments/27362075/Hive_Decimal_Precision_Scale_Support.pdf https://msdn.microsoft.com/en-us/library/ms190476.aspx
In particular, if we have expressions e1 and e2 with precision/scale p1/s2 and p2/s2 respectively, then the following operations have the following precision / scale:
Operation Result Precision Result Scale ------------------------------------------------------------------------ e1 + e2 max(s1, s2) + max(p1-s1, p2-s2) + 1 max(s1, s2) e1 - e2 max(s1, s2) + max(p1-s1, p2-s2) + 1 max(s1, s2) e1 * e2 p1 + p2 + 1 s1 + s2 e1 / e2 p1 - s1 + s2 + max(6, s1 + p2 + 1) max(6, s1 + p2 + 1) e1 % e2 min(p1-s1, p2-s2) + max(s1, s2) max(s1, s2) e1 union e2 max(s1, s2) + max(p1-s1, p2-s2) max(s1, s2)
When
spark.sql.decimalOperations.allowPrecisionLossis set to true, if the precision / scale needed are out of the range of available values, the scale is reduced up to 6, in order to prevent the truncation of the integer part of the decimals.To implement the rules for fixed-precision types, we introduce casts to turn them to unlimited precision, do the math on unlimited-precision numbers, then introduce casts back to the required fixed precision. This allows us to do all rounding and overflow handling in the cast-to-fixed-precision operator.
In addition, when mixing non-decimal types with decimals, we use the following rules: - BYTE gets turned into DECIMAL(3, 0) - SHORT gets turned into DECIMAL(5, 0) - INT gets turned into DECIMAL(10, 0) - LONG gets turned into DECIMAL(20, 0) - FLOAT and DOUBLE cause fixed-length decimals to turn into DOUBLE - Literals INT and LONG get turned into DECIMAL with the precision strictly needed by the value
- object DeduplicateRelations extends Rule[LogicalPlan]
-
object
EliminateEventTimeWatermark extends Rule[LogicalPlan]
Ignore event time watermark in batch query, which is only supported in Structured Streaming.
Ignore event time watermark in batch query, which is only supported in Structured Streaming. TODO: add this rule into analyzer rule list.
-
object
EliminateSubqueryAliases extends Rule[LogicalPlan]
Removes SubqueryAlias operators from the plan.
Removes SubqueryAlias operators from the plan. Subqueries are only required to provide scoping information for attributes and can be removed once analysis is complete.
-
object
EliminateUnions extends Rule[LogicalPlan]
Removes Union operators from the plan if it just has one child.
-
object
EliminateView extends Rule[LogicalPlan] with CastSupport
This rule removes View operators from the plan.
This rule removes View operators from the plan. The operator is respected till the end of analysis stage because we want to see which part of an analyzed logical plan is generated from a view.
- object EmptyFunctionRegistry extends EmptyFunctionRegistryBase[Expression] with FunctionRegistry
- object EmptyTableFunctionRegistry extends EmptyFunctionRegistryBase[LogicalPlan] with TableFunctionRegistry
- object FakeV2SessionCatalog extends TableCatalog with FunctionCatalog
- object FunctionRegistry
- object FunctionRegistryBase
-
object
GlobalTempView extends ViewType
GlobalTempView means cross-session global temporary views.
GlobalTempView means cross-session global temporary views. Its lifetime is the lifetime of the Spark application, i.e. it will be automatically dropped when the application terminates. It's tied to a system preserved database
global_temp, and we must use the qualified name to refer a global temp view, e.g. SELECT * FROM global_temp.view1. -
object
HintErrorLogger extends HintErrorHandler with Logging
The hint error handler that logs warnings for each hint error.
-
object
KeepLegacyOutputs extends Rule[LogicalPlan]
A rule for keeping the SQL command's legacy outputs.
-
object
LocalTempView extends ViewType
LocalTempView means session-scoped local temporary views.
LocalTempView means session-scoped local temporary views. Its lifetime is the lifetime of the session that created it, i.e. it will be automatically dropped when the session terminates. It's not tied to any databases, i.e. we can't use
db1.view1to reference a local temporary view. -
object
PersistedView extends ViewType
PersistedView means cross-session persisted views.
PersistedView means cross-session persisted views. Persisted views stay until they are explicitly dropped by user command. It's always tied to a database, default to the current database if not specified.
Note that, Existing persisted view with the same name are not visible to the current session while the local temporary view exists, unless the view name is qualified by database.
-
object
PullOutNondeterministic extends Rule[LogicalPlan]
Pulls out nondeterministic expressions from LogicalPlan which is not Project or Filter, put them into an inner Project and finally project them away at the outer Project.
-
object
RemoveTempResolvedColumn extends Rule[LogicalPlan]
Removes all TempResolvedColumns in the query plan.
Removes all TempResolvedColumns in the query plan. This is the last resort, in case some rules in the main resolution batch miss to remove TempResolvedColumns. We should run this rule right after the main resolution batch.
-
object
ResolveCommandsWithIfExists extends Rule[LogicalPlan]
A rule for handling commands when the table or temp view is not resolved.
A rule for handling commands when the table or temp view is not resolved. These commands support a flag, "ifExists", so that they do not fail when a relation is not resolved. If the "ifExists" flag is set to true. the plan is resolved to NoopCommand,
-
object
ResolveExpressionsWithNamePlaceholders extends Rule[LogicalPlan]
Resolve expressions if they contains NamePlaceholders.
-
object
ResolveHints
Collection of rules related to hints.
Collection of rules related to hints. The only hint currently available is join strategy hint.
Note that this is separately into two rules because in the future we might introduce new hint rules that have different ordering requirements from join strategies.
-
object
ResolveInlineTables extends Rule[LogicalPlan] with CastSupport with AliasHelper
An analyzer rule that replaces UnresolvedInlineTable with LocalRelation.
-
object
ResolveLambdaVariables extends Rule[LogicalPlan]
Resolve the lambda variables exposed by a higher order functions.
Resolve the lambda variables exposed by a higher order functions.
This rule works in two steps: [1]. Bind the anonymous variables exposed by the higher order function to the lambda function's arguments; this creates named and typed lambda variables. The argument names are checked for duplicates and the number of arguments are checked during this step. [2]. Resolve the used lambda variables used in the lambda function's function expression tree. Note that we allow the use of variables from outside the current lambda, this can either be a lambda function defined in an outer scope, or a attribute in produced by the plan's child. If names are duplicate, the name defined in the most inner scope is used.
-
object
ResolvePartitionSpec extends Rule[LogicalPlan]
Resolve UnresolvedPartitionSpec to ResolvedPartitionSpec in partition related commands.
-
object
ResolveTimeZone extends Rule[LogicalPlan]
Replace TimeZoneAwareExpression without timezone id by its copy with session local time zone.
-
object
ResolveUnion extends Rule[LogicalPlan]
Resolves different children of Union to a common set of columns.
-
object
ResolveWithCTE extends Rule[LogicalPlan]
Updates CTE references with the resolve output attributes of corresponding CTE definitions.
- object ResolvedTable extends Serializable
-
object
RewriteDeleteFromTable extends Rule[LogicalPlan] with RewriteRowLevelCommand
A rule that rewrites DELETE operations using plans that operate on individual or groups of rows.
A rule that rewrites DELETE operations using plans that operate on individual or groups of rows.
If a table implements SupportsDelete and SupportsRowLevelOperations, this rule will still rewrite the DELETE operation but the optimizer will check whether this particular DELETE statement can be handled by simply passing delete filters to the connector. If so, the optimizer will discard the rewritten plan and will allow the data source to delete using filters.
-
object
SessionWindowing extends Rule[LogicalPlan]
Maps a time column to a session window.
-
object
SimpleAnalyzer extends Analyzer
A trivial Analyzer with a dummy SessionCatalog, EmptyFunctionRegistry and EmptyTableFunctionRegistry.
A trivial Analyzer with a dummy SessionCatalog, EmptyFunctionRegistry and EmptyTableFunctionRegistry. Used for testing when all relations are already filled in and the analyzer needs only to resolve attribute references.
-
object
StreamingJoinHelper extends PredicateHelper with Logging
Helper object for stream joins.
Helper object for stream joins. See StreamingSymmetricHashJoinExec in SQL for more details.
-
object
SubstituteUnresolvedOrdinals extends Rule[LogicalPlan]
Replaces ordinal in 'order by' or 'group by' with UnresolvedOrdinal expression.
- object TableFunctionRegistry
- object TableOutputResolver
- object TimeTravelSpec
-
object
TimeWindowing extends Rule[LogicalPlan]
Maps a time column to multiple time windows using the Expand operator.
Maps a time column to multiple time windows using the Expand operator. Since it's non-trivial to figure out how many windows a time column can map to, we over-estimate the number of windows and filter out the rows where the time column is not inside the time window.
- object TypeCheckResult
-
object
TypeCoercion extends TypeCoercionBase
A collection of Rule that can be used to coerce differing types that participate in operations into compatible ones.
A collection of Rule that can be used to coerce differing types that participate in operations into compatible ones.
Notes about type widening / tightest common types: Broadly, there are two cases when we need to widen data types (e.g. union, binary comparison). In case 1, we are looking for a common data type for two or more data types, and in this case no loss of precision is allowed. Examples include type inference in JSON (e.g. what's the column's data type if one row is an integer while the other row is a long?). In case 2, we are looking for a widened data type with some acceptable loss of precision (e.g. there is no common type for double and decimal because double's range is larger than decimal, and yet decimal is more precise than double, but in union we would cast the decimal into double).
- object UnresolvedAttribute extends Serializable
- object UnresolvedFunction extends Serializable
- object UnresolvedRelation extends Serializable
-
object
UnresolvedSeed extends LeafExpression with Unevaluable with Product with Serializable
A place holder expression used in random functions, will be replaced after analyze.
- object UnresolvedTableValuedFunction extends Serializable
-
object
UnsupportedOperationChecker extends Logging
Analyzes the presence of unsupported operations in a logical plan.
-
object
UpdateAttributeNullability extends Rule[LogicalPlan]
Updates nullability of Attributes in a resolved LogicalPlan by using the nullability of corresponding Attributes of its children output Attributes.
Updates nullability of Attributes in a resolved LogicalPlan by using the nullability of corresponding Attributes of its children output Attributes. This step is needed because users can use a resolved AttributeReference in the Dataset API and outer joins can change the nullability of an AttributeReference. Without this rule, a nullable column's nullable field can be actually set as non-nullable, which cause illegal optimization (e.g., NULL propagation) and wrong answers. See SPARK-13484 and SPARK-13801 for the concrete queries of this case.
-
object
UpdateOuterReferences extends Rule[LogicalPlan]
The aggregate expressions from subquery referencing outer query block are pushed down to the outer query block for evaluation.
The aggregate expressions from subquery referencing outer query block are pushed down to the outer query block for evaluation. This rule below updates such outer references as AttributeReference referring attributes from the parent/outer query block.
For example (SQL):
SELECT l.a FROM l GROUP BY 1 HAVING EXISTS (SELECT 1 FROM r WHERE r.d < min(l.b))
Plan before the rule. Project [a#226] +- Filter exists#245 [min(b#227)#249] : +- Project [1 AS 1#247] : +- Filter (d#238 < min(outer(b#227))) <----- : +- SubqueryAlias r : +- Project [_1#234 AS c#237, _2#235 AS d#238] : +- LocalRelation [_1#234, _2#235] +- Aggregate [a#226], [a#226, min(b#227) AS min(b#227)#249] +- SubqueryAlias l +- Project [_1#223 AS a#226, _2#224 AS b#227] +- LocalRelation [_1#223, _2#224] Plan after the rule. Project [a#226] +- Filter exists#245 [min(b#227)#249] : +- Project [1 AS 1#247] : +- Filter (d#238 < outer(min(b#227)#249)) <----- : +- SubqueryAlias r : +- Project [_1#234 AS c#237, _2#235 AS d#238] : +- LocalRelation [_1#234, _2#235] +- Aggregate [a#226], [a#226, min(b#227) AS min(b#227)#249] +- SubqueryAlias l +- Project [_1#223 AS a#226, _2#224 AS b#227] +- LocalRelation [_1#223, _2#224]