OmniSciDB  c07336695a
org.apache.calcite.sql2rel.SqlToRelConverter Class Reference
+ Collaboration diagram for org.apache.calcite.sql2rel.SqlToRelConverter:

Classes

class  AggConverter
 
class  AggregateFinder
 
class  Blackboard
 
interface  Config
 
class  ConfigBuilder
 
class  ConfigImpl
 
class  CorrelationUse
 
class  DeferredLookup
 
class  HistogramShuttle
 
class  LookupContext
 
class  NoOpSubQueryConverter
 
class  RexAccessShuttle
 
class  SubQuery
 

Public Member Functions

 SqlToRelConverter (RelOptTable.ViewExpander viewExpander, SqlValidator validator, Prepare.CatalogReader catalogReader, RelOptPlanner planner, RexBuilder rexBuilder, SqlRexConvertletTable convertletTable)
 
 SqlToRelConverter (RelOptTable.ViewExpander viewExpander, SqlValidator validator, Prepare.CatalogReader catalogReader, RelOptCluster cluster, SqlRexConvertletTable convertletTable)
 
 SqlToRelConverter (RelOptTable.ViewExpander viewExpander, SqlValidator validator, Prepare.CatalogReader catalogReader, RelOptCluster cluster, SqlRexConvertletTable convertletTable, Config config)
 
RelOptCluster getCluster ()
 
RexBuilder getRexBuilder ()
 
int getDynamicParamCount ()
 
RelDataType getDynamicParamType (int index)
 
int getDynamicParamCountInExplain (boolean increment)
 
Map< SqlNode, RexNode > getMapConvertedNonCorrSubqs ()
 
void addConvertedNonCorrSubqs (Map< SqlNode, RexNode > alreadyConvertedNonCorrSubqs)
 
void setSubQueryConverter (SubQueryConverter converter)
 
void setDynamicParamCountInExplain (int explainParamCount)
 
RelNode flattenTypes (RelNode rootRel, boolean restructure)
 
RelNode decorrelate (SqlNode query, RelNode rootRel)
 
RelNode trimUnusedFields (boolean ordered, RelNode rootRel)
 
RelRoot convertQuery (SqlNode query, final boolean needsValidation, final boolean top)
 
RelNode convertSelect (SqlSelect select, boolean top)
 
RelNode convertToSingleValueSubq (SqlNode query, RelNode plan)
 
RexNode convertExpression (SqlNode node)
 
RexNode convertExpression (SqlNode node, Map< String, RexNode > nameToNodeMap)
 
RexDynamicParam convertDynamicParam (final SqlDynamicParam dynamicParam)
 
boolean isTrimUnusedFields ()
 
RelNode toRel (final RelOptTable table)
 
RelRoot convertWith (SqlWith with, boolean top)
 
RelNode convertValues (SqlCall values, RelDataType targetRowType)
 

Static Public Member Functions

static boolean isOrdered (SqlNode query)
 
static ConfigBuilder configBuilder ()
 

Public Attributes

final SqlToRelConverter.Config config
 
final RelOptTable.ViewExpander viewExpander
 

Static Public Attributes

static final int DEFAULT_IN_SUB_QUERY_THRESHOLD = 20
 
static final int DEFAULT_IN_SUBQUERY_THRESHOLD = DEFAULT_IN_SUB_QUERY_THRESHOLD
 

Protected Member Functions

RelFieldTrimmer newFieldTrimmer ()
 
Blackboard createBlackboard (SqlValidatorScope scope, Map< String, RexNode > nameToNodeMap, boolean top)
 
void convertSelectImpl (final Blackboard bb, SqlSelect select)
 
void convertOrder (SqlSelect select, Blackboard bb, RelCollation collation, List< SqlNode > orderExprList, SqlNode offset, SqlNode fetch)
 
int getInSubqueryThreshold ()
 
RexNode convertExtendedExpression (SqlNode node, Blackboard bb)
 
void convertFrom (Blackboard bb, SqlNode from)
 
void convertMatchRecognize (Blackboard bb, SqlCall call)
 
void convertCollectionTable (Blackboard bb, SqlCall call)
 
void afterTableFunction (SqlToRelConverter.Blackboard bb, SqlCall call, LogicalTableFunctionScan callRel)
 
RelNode createJoin (Blackboard bb, RelNode leftRel, RelNode rightRel, RexNode joinCond, JoinRelType joinType)
 
List< RelDataTypeField > getSystemFields ()
 
void convertAgg (Blackboard bb, SqlSelect select, List< SqlNode > orderExprList)
 
final void createAggImpl (Blackboard bb, final AggConverter aggConverter, SqlNodeList selectList, SqlNodeList groupList, SqlNode having, List< SqlNode > orderExprList)
 
RelNode createAggregate (Blackboard bb, ImmutableBitSet groupSet, ImmutableList< ImmutableBitSet > groupSets, List< AggregateCall > aggCalls)
 
void gatherOrderExprs (Blackboard bb, SqlSelect select, SqlNodeList orderList, List< SqlNode > extraOrderExprs, List< RelFieldCollation > collationList)
 
RelFieldCollation convertOrderItem (SqlSelect select, SqlNode orderItem, List< SqlNode > extraExprs, RelFieldCollation.Direction direction, RelFieldCollation.NullDirection nullDirection)
 
boolean enableDecorrelation ()
 
RelNode decorrelateQuery (RelNode rootRel)
 
RelRoot convertQueryRecursive (SqlNode query, boolean top, RelDataType targetRowType)
 
RelNode convertSetOp (SqlCall call)
 
RelNode convertInsert (SqlInsert call)
 
RelOptTable getTargetTable (SqlNode call)
 
RelNode convertColumnList (final SqlInsert call, RelNode source)
 
void collectInsertTargets (SqlInsert call, final RexNode sourceRef, final List< String > targetColumnNames, List< RexNode > columnExprs)
 
RexNode adjustInputRef (Blackboard bb, RexInputRef inputRef)
 
void extraSelectItems (Blackboard bb, SqlSelect select, List< RexNode > exprList, List< String > nameList, Collection< String > aliasList, List< SqlMonotonicity > columnMonotonicityList)
 

Protected Attributes

final SqlValidator validator
 
final RexBuilder rexBuilder
 
final Prepare.CatalogReader catalogReader
 
final RelOptCluster cluster
 
final List< RelNode > leaves = new ArrayList<>()
 
final RelDataTypeFactory typeFactory
 

Static Protected Attributes

static final Logger SQL2REL_LOGGER = CalciteTrace.getSqlToRelTracer()
 

Private Member Functions

void checkConvertedType (SqlNode query, RelNode result)
 
RelCollation requiredCollation (RelNode r)
 
void distinctify (Blackboard bb, boolean checkForDupExprs)
 
void convertWhere (final Blackboard bb, final SqlNode where)
 
void replaceSubQueries (final Blackboard bb, final SqlNode expr, RelOptUtil.Logic logic)
 
void substituteSubQuery (Blackboard bb, SubQuery subQuery)
 
RexNode translateIn (RelOptUtil.Logic logic, RelNode root, final RexNode rex)
 
boolean convertNonCorrelatedSubQuery (SubQuery subQuery, Blackboard bb, RelNode converted, boolean isExists)
 
RexNode convertInToOr (final Blackboard bb, final List< RexNode > leftKeys, SqlNodeList valuesList, SqlInOperator op)
 
RexNode ensureSqlType (RelDataType type, RexNode node)
 
RelOptUtil.Exists convertExists (SqlNode seek, RelOptUtil.SubQueryType subQueryType, RelOptUtil.Logic logic, boolean notIn, RelDataType targetDataType)
 
RelNode convertQueryOrInList (Blackboard bb, SqlNode seek, RelDataType targetRowType)
 
RelNode convertRowValues (Blackboard bb, SqlNode rowList, Collection< SqlNode > rows, boolean allowLiteralsOnly, RelDataType targetRowType)
 
RexLiteral convertLiteralInValuesList (SqlNode sqlNode, Blackboard bb, RelDataType rowType, int iField)
 
boolean isRowConstructor (SqlNode node)
 
void findSubQueries (Blackboard bb, SqlNode node, RelOptUtil.Logic logic, boolean registerOnlyScalarSubQueries)
 
RexNode convertOver (Blackboard bb, SqlNode node)
 
void convertIdentifier (Blackboard bb, SqlIdentifier id, SqlNodeList extendedColumns)
 
void snapshotTemporalTable (Blackboard bb, SqlCall call)
 
Set< RelColumnMapping > getColumnMappings (SqlOperator op)
 
CorrelationUse getCorrelationUse (Blackboard bb, final RelNode r0)
 
boolean isSubQueryNonCorrelated (RelNode subq, Blackboard bb)
 
RexNode convertJoinCondition (Blackboard bb, SqlValidatorNamespace leftNamespace, SqlValidatorNamespace rightNamespace, SqlNode condition, JoinConditionType conditionType, RelNode leftRel, RelNode rightRel)
 
RexNode convertUsing (SqlValidatorNamespace leftNamespace, SqlValidatorNamespace rightNamespace, List< String > nameList)
 
boolean all (SqlCall call)
 
RelNode createModify (RelOptTable targetTable, RelNode source)
 
RelNode createSource (RelOptTable targetTable, RelNode source, ModifiableView modifiableView, RelDataType delegateRowType)
 
RelOptTable.ToRelContext createToRelContext ()
 
Blackboard createInsertBlackboard (RelOptTable targetTable, RexNode sourceRef, List< String > targetColumnNames)
 
InitializerExpressionFactory getInitializerFactory (SqlValidatorTable validatorTable)
 
RexNode castNullLiteralIfNeeded (RexNode node, RelDataType type)
 
RelNode convertDelete (SqlDelete call)
 
RelNode convertUpdate (SqlUpdate call)
 
RelNode convertMerge (SqlMerge call)
 
RexNode convertIdentifier (Blackboard bb, SqlIdentifier identifier)
 
RelNode convertRowConstructor (Blackboard bb, SqlCall rowConstructor)
 
RelNode convertCursor (Blackboard bb, SubQuery subQuery)
 
RelNode convertMultisets (final List< SqlNode > operands, Blackboard bb)
 
void convertSelectList (Blackboard bb, SqlSelect select, List< SqlNode > orderList)
 
String deriveAlias (final SqlNode node, Collection< String > aliases, final int ordinal)
 
void convertValuesImpl (Blackboard bb, SqlCall values, RelDataType targetRowType)
 
SqlQuantifyOperator negate (SqlQuantifyOperator operator)
 

Static Private Member Functions

static boolean isStream (SqlNode query)
 
static boolean containsInOperator (SqlNode node)
 
static SqlNode pushDownNotForIn (SqlValidatorScope scope, SqlNode sqlNode)
 
static SqlNode reg (SqlValidatorScope scope, SqlNode e)
 
static boolean containsNullLiteral (SqlNodeList valueList)
 
static JoinRelType convertJoinType (JoinType joinType)
 
static boolean desc (RelFieldCollation.Direction direction)
 
static< T > T unwrap (Object o, Class< T > clazz)
 

Private Attributes

SubQueryConverter subQueryConverter
 
final List< SqlDynamicParam > dynamicParamSqlNodes = new ArrayList<>()
 
final SqlOperatorTable opTab
 
final SqlNodeToRexConverter exprConverter
 
int explainParamCount
 
final RelBuilder relBuilder
 
final Map< CorrelationId, DeferredLookupmapCorrelToDeferred = new HashMap<>()
 
final Deque< String > datasetStack = new ArrayDeque<>()
 
final Map< SqlNode, RexNode > mapConvertedNonCorrSubqs = new HashMap<>()
 

Static Private Attributes

static final BigDecimal TWO = BigDecimal.valueOf(2L)
 

Detailed Description

Converts a SQL parse tree (consisting of org.apache.calcite.sql.SqlNode objects) into a relational algebra expression (consisting of org.apache.calcite.rel.RelNode objects).

The public entry points are: convertQuery, convertExpression(SqlNode).

Definition at line 215 of file SqlToRelConverter.java.

Constructor & Destructor Documentation

◆ SqlToRelConverter() [1/3]

org.apache.calcite.sql2rel.SqlToRelConverter.SqlToRelConverter ( RelOptTable.ViewExpander  viewExpander,
SqlValidator  validator,
Prepare.CatalogReader  catalogReader,
RelOptPlanner  planner,
RexBuilder  rexBuilder,
SqlRexConvertletTable  convertletTable 
)
inline

Creates a converter.

Parameters
viewExpanderPreparing statement
validatorValidator
catalogReaderSchema
plannerPlanner
rexBuilderRex builder
convertletTableExpression converter

Definition at line 279 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.catalogReader, org.apache.calcite.sql2rel.SqlToRelConverter.Config.DEFAULT, org.apache.calcite.sql2rel.SqlToRelConverter.validator, and org.apache.calcite.sql2rel.SqlToRelConverter.viewExpander.

284  {
285  this(viewExpander,
286  validator,
288  RelOptCluster.create(planner, rexBuilder),
289  convertletTable,
290  Config.DEFAULT);
291  }

◆ SqlToRelConverter() [2/3]

org.apache.calcite.sql2rel.SqlToRelConverter.SqlToRelConverter ( RelOptTable.ViewExpander  viewExpander,
SqlValidator  validator,
Prepare.CatalogReader  catalogReader,
RelOptCluster  cluster,
SqlRexConvertletTable  convertletTable 
)
inline

◆ SqlToRelConverter() [3/3]

org.apache.calcite.sql2rel.SqlToRelConverter.SqlToRelConverter ( RelOptTable.ViewExpander  viewExpander,
SqlValidator  validator,
Prepare.CatalogReader  catalogReader,
RelOptCluster  cluster,
SqlRexConvertletTable  convertletTable,
Config  config 
)
inline

Definition at line 308 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.ConfigBuilder.build(), org.apache.calcite.sql2rel.SqlToRelConverter.catalogReader, org.apache.calcite.sql2rel.SqlToRelConverter.Config.getRelBuilderFactory(), org.apache.calcite.sql2rel.SqlToRelConverter.validator, org.apache.calcite.sql2rel.SqlToRelConverter.viewExpander, and org.apache.calcite.sql2rel.SqlToRelConverter.ConfigBuilder.withConfig().

313  {
314  this.viewExpander = viewExpander;
315  this.opTab = (validator == null) ? SqlStdOperatorTable.instance()
316  : validator.getOperatorTable();
317  this.validator = validator;
319  this.subQueryConverter = new NoOpSubQueryConverter();
320  this.rexBuilder = cluster.getRexBuilder();
321  this.typeFactory = rexBuilder.getTypeFactory();
322  this.cluster = Objects.requireNonNull(cluster);
323  this.exprConverter = new SqlNodeToRexConverterImpl(convertletTable);
324  this.explainParamCount = 0;
325  this.config = new ConfigBuilder().withConfig(config).build();
326  this.relBuilder = config.getRelBuilderFactory().create(cluster, null);
327  }
+ Here is the call graph for this function:

Member Function Documentation

◆ addConvertedNonCorrSubqs()

void org.apache.calcite.sql2rel.SqlToRelConverter.addConvertedNonCorrSubqs ( Map< SqlNode, RexNode >  alreadyConvertedNonCorrSubqs)
inline

Adds to the current map of non-correlated converted sub-queries the elements from another map that contains non-correlated sub-queries that have been converted by another SqlToRelConverter.

Parameters
alreadyConvertedNonCorrSubqsthe other map

Definition at line 399 of file SqlToRelConverter.java.

400  {
401  mapConvertedNonCorrSubqs.putAll(alreadyConvertedNonCorrSubqs);
402  }
final Map< SqlNode, RexNode > mapConvertedNonCorrSubqs

◆ adjustInputRef()

RexNode org.apache.calcite.sql2rel.SqlToRelConverter.adjustInputRef ( Blackboard  bb,
RexInputRef  inputRef 
)
inlineprotected

Adjusts the type of a reference to an input field to account for nulls introduced by outer joins; and adjusts the offset to match the physical implementation.

Parameters
bbBlackboard
inputRefInput ref
Returns
Adjusted input ref

Definition at line 3562 of file SqlToRelConverter.java.

References field(), and org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.getRootField().

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertIdentifier().

3562  {
3563  RelDataTypeField field = bb.getRootField(inputRef);
3564  if (field != null) {
3565  return rexBuilder.makeInputRef(field.getType(), inputRef.getIndex());
3566  }
3567  return inputRef;
3568  }
const rapidjson::Value & field(const rapidjson::Value &obj, const char field[]) noexcept
Definition: JsonAccessors.h:31
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ afterTableFunction()

void org.apache.calcite.sql2rel.SqlToRelConverter.afterTableFunction ( SqlToRelConverter.Blackboard  bb,
SqlCall  call,
LogicalTableFunctionScan  callRel 
)
inlineprotected

Definition at line 2266 of file SqlToRelConverter.java.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertCollectionTable().

2268  {}
+ Here is the caller graph for this function:

◆ all()

boolean org.apache.calcite.sql2rel.SqlToRelConverter.all ( SqlCall  call)
inlineprivate

Definition at line 3033 of file SqlToRelConverter.java.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertSetOp().

3033  {
3034  return ((SqlSetOperator) call.getOperator()).isAll();
3035  }
+ Here is the caller graph for this function:

◆ castNullLiteralIfNeeded()

RexNode org.apache.calcite.sql2rel.SqlToRelConverter.castNullLiteralIfNeeded ( RexNode  node,
RelDataType  type 
)
inlineprivate

Definition at line 3294 of file SqlToRelConverter.java.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertColumnList().

3294  {
3295  if (!RexLiteral.isNullLiteral(node)) {
3296  return node;
3297  }
3298  return rexBuilder.makeCast(type, node);
3299  }
+ Here is the caller graph for this function:

◆ checkConvertedType()

void org.apache.calcite.sql2rel.SqlToRelConverter.checkConvertedType ( SqlNode  query,
RelNode  result 
)
inlineprivate

Definition at line 425 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.catalogReader.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertQuery(), and org.apache.calcite.sql2rel.SqlToRelConverter.decorrelate().

425  {
426  if (query.isA(SqlKind.DML)) {
427  return;
428  }
429  // Verify that conversion from SQL to relational algebra did
430  // not perturb any type information. (We can't do this if the
431  // SQL statement is something like an INSERT which has no
432  // validator type information associated with its result,
433  // hence the namespace check above.)
434  final List<RelDataTypeField> validatedFields =
435  validator.getValidatedNodeType(query).getFieldList();
436  final RelDataType validatedRowType =
437  validator.getTypeFactory().createStructType(Pair.right(validatedFields),
438  SqlValidatorUtil.uniquify(Pair.left(validatedFields),
439  catalogReader.nameMatcher().isCaseSensitive()));
440 
441  final List<RelDataTypeField> convertedFields =
442  result.getRowType().getFieldList().subList(0, validatedFields.size());
443  final RelDataType convertedRowType =
444  validator.getTypeFactory().createStructType(convertedFields);
445 
446  if (!RelOptUtil.equal("validated row type",
447  validatedRowType,
448  "converted row type",
449  convertedRowType,
450  Litmus.IGNORE)) {
451  throw new AssertionError("Conversion to relational algebra failed to "
452  + "preserve datatypes:\n"
453  + "validated type:\n" + validatedRowType.getFullTypeString()
454  + "\nconverted type:\n" + convertedRowType.getFullTypeString() + "\nrel:\n"
455  + RelOptUtil.toString(result));
456  }
457  }
+ Here is the caller graph for this function:

◆ collectInsertTargets()

void org.apache.calcite.sql2rel.SqlToRelConverter.collectInsertTargets ( SqlInsert  call,
final RexNode  sourceRef,
final List< String >  targetColumnNames,
List< RexNode >  columnExprs 
)
inlineprotected

Given an INSERT statement, collects the list of names to be populated and the expressions to put in them.

Parameters
callInsert statement
sourceRefExpression representing a row from the source relational expression
targetColumnNamesList of target column names, to be populated
columnExprsList of expressions, to be populated

Definition at line 3311 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.catalogReader, org.apache.calcite.sql2rel.SqlToRelConverter.createInsertBlackboard(), field(), org.apache.calcite.sql2rel.SqlToRelConverter.getTargetTable(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.nameToNodeMap, and Experimental.String.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertColumnList().

3314  {
3315  final RelOptTable targetTable = getTargetTable(call);
3316  final RelDataType tableRowType = targetTable.getRowType();
3317  SqlNodeList targetColumnList = call.getTargetColumnList();
3318  if (targetColumnList == null) {
3319  if (validator.getConformance().isInsertSubsetColumnsAllowed()) {
3320  final RelDataType targetRowType =
3321  typeFactory.createStructType(tableRowType.getFieldList().subList(
3322  0, sourceRef.getType().getFieldCount()));
3323  targetColumnNames.addAll(targetRowType.getFieldNames());
3324  } else {
3325  targetColumnNames.addAll(tableRowType.getFieldNames());
3326  }
3327  } else {
3328  for (int i = 0; i < targetColumnList.size(); i++) {
3329  SqlIdentifier id = (SqlIdentifier) targetColumnList.get(i);
3330  RelDataTypeField field = SqlValidatorUtil.getTargetField(
3331  tableRowType, typeFactory, id, catalogReader, targetTable);
3332  assert field != null : "column " + id.toString() + " not found";
3333  targetColumnNames.add(field.getName());
3334  }
3335  }
3336 
3337  final Blackboard bb =
3338  createInsertBlackboard(targetTable, sourceRef, targetColumnNames);
3339 
3340  // Next, assign expressions for generated columns.
3341  final List<ColumnStrategy> strategies = targetTable.getColumnStrategies();
3342  for (String columnName : targetColumnNames) {
3343  final int i = tableRowType.getFieldNames().indexOf(columnName);
3344  final RexNode expr;
3345  switch (strategies.get(i)) {
3346  case STORED:
3347  final InitializerExpressionFactory f =
3348  Util.first(targetTable.unwrap(InitializerExpressionFactory.class),
3349  NullInitializerExpressionFactory.INSTANCE);
3350  expr = f.newColumnDefaultValue(targetTable, i, bb);
3351  break;
3352  case VIRTUAL:
3353  expr = null;
3354  break;
3355  default:
3356  expr = bb.nameToNodeMap.get(columnName);
3357  }
3358  columnExprs.add(expr);
3359  }
3360 
3361  // Remove virtual columns from the list.
3362  for (int i = 0; i < targetColumnNames.size(); i++) {
3363  if (columnExprs.get(i) == null) {
3364  columnExprs.remove(i);
3365  targetColumnNames.remove(i);
3366  --i;
3367  }
3368  }
3369  }
const rapidjson::Value & field(const rapidjson::Value &obj, const char field[]) noexcept
Definition: JsonAccessors.h:31
Blackboard createInsertBlackboard(RelOptTable targetTable, RexNode sourceRef, List< String > targetColumnNames)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ configBuilder()

static ConfigBuilder org.apache.calcite.sql2rel.SqlToRelConverter.configBuilder ( )
inlinestatic

Creates a builder for a Config.

Definition at line 5244 of file SqlToRelConverter.java.

5244  {
5245  return new ConfigBuilder();
5246  }

◆ containsInOperator()

static boolean org.apache.calcite.sql2rel.SqlToRelConverter.containsInOperator ( SqlNode  node)
inlinestaticprivate

Returns whether a given node contains a SqlInOperator.

Parameters
nodea RexNode tree

Definition at line 798 of file SqlToRelConverter.java.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.pushDownNotForIn().

798  {
799  try {
800  SqlVisitor<Void> visitor = new SqlBasicVisitor<Void>() {
801  public Void visit(SqlCall call) {
802  if (call.getOperator() instanceof SqlInOperator) {
803  throw new Util.FoundOne(call);
804  }
805  return super.visit(call);
806  }
807  };
808  node.accept(visitor);
809  return false;
810  } catch (Util.FoundOne e) {
811  Util.swallow(e, null);
812  return true;
813  }
814  }
+ Here is the caller graph for this function:

◆ containsNullLiteral()

static boolean org.apache.calcite.sql2rel.SqlToRelConverter.containsNullLiteral ( SqlNodeList  valueList)
inlinestaticprivate

Definition at line 1260 of file SqlToRelConverter.java.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.substituteSubQuery().

1260  {
1261  for (SqlNode node : valueList.getList()) {
1262  if (node instanceof SqlLiteral) {
1263  SqlLiteral lit = (SqlLiteral) node;
1264  if (lit.getValue() == null) {
1265  return true;
1266  }
1267  }
1268  }
1269  return false;
1270  }
+ Here is the caller graph for this function:

◆ convertAgg()

void org.apache.calcite.sql2rel.SqlToRelConverter.convertAgg ( Blackboard  bb,
SqlSelect  select,
List< SqlNode >  orderExprList 
)
inlineprotected

Converts the SELECT, GROUP BY and HAVING clauses of an aggregate query.

This method extracts SELECT, GROUP BY and HAVING clauses, and creates an AggConverter, then delegates to createAggImpl. Derived class may override this method to change any of those clauses or specify a different AggConverter.

Parameters
bbScope within which to resolve identifiers
selectQuery
orderExprListAdditional expressions needed to implement ORDER BY

Definition at line 2615 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.createAggImpl(), and org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.root.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertSelectImpl().

2616  {
2617  assert bb.root != null : "precondition: child != null";
2618  SqlNodeList groupList = select.getGroup();
2619  SqlNodeList selectList = select.getSelectList();
2620  SqlNode having = select.getHaving();
2621 
2622  final AggConverter aggConverter = new AggConverter(bb, select);
2623  createAggImpl(bb, aggConverter, selectList, groupList, having, orderExprList);
2624  }
final void createAggImpl(Blackboard bb, final AggConverter aggConverter, SqlNodeList selectList, SqlNodeList groupList, SqlNode having, List< SqlNode > orderExprList)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertCollectionTable()

void org.apache.calcite.sql2rel.SqlToRelConverter.convertCollectionTable ( Blackboard  bb,
SqlCall  call 
)
inlineprotected

Definition at line 2215 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.afterTableFunction(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.convertExpression(), org.apache.calcite.sql2rel.SqlToRelConverter.convertQuery(), org.apache.calcite.sql2rel.SqlToRelConverter.getColumnMappings(), anonymous_namespace{UpdateMetadataTest.cpp}.query, org.apache.calcite.sql2rel.SqlToRelConverter.replaceSubQueries(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.retrieveCursors(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.scope, org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.setRoot(), Experimental.String, and org.apache.calcite.sql2rel.SqlToRelConverter.toRel().

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom().

2215  {
2216  final SqlOperator operator = call.getOperator();
2217  if (operator == SqlStdOperatorTable.TABLESAMPLE) {
2218  final String sampleName =
2219  SqlLiteral.unchain(call.operand(0)).getValueAs(String.class);
2220  datasetStack.push(sampleName);
2221  SqlCall cursorCall = call.operand(1);
2222  SqlNode query = cursorCall.operand(0);
2223  RelNode converted = convertQuery(query, false, false).rel;
2224  bb.setRoot(converted, false);
2225  datasetStack.pop();
2226  return;
2227  }
2228  replaceSubQueries(bb, call, RelOptUtil.Logic.TRUE_FALSE_UNKNOWN);
2229 
2230  // Expand table macro if possible. It's more efficient than
2231  // LogicalTableFunctionScan.
2232  final SqlCallBinding callBinding =
2233  new SqlCallBinding(bb.scope.getValidator(), bb.scope, call);
2234  if (operator instanceof SqlUserDefinedTableMacro) {
2235  final SqlUserDefinedTableMacro udf = (SqlUserDefinedTableMacro) operator;
2236  final TranslatableTable table = udf.getTable(typeFactory, callBinding.operands());
2237  final RelDataType rowType = table.getRowType(typeFactory);
2238  RelOptTable relOptTable =
2239  RelOptTableImpl.create(null, rowType, table, udf.getNameAsId().names);
2240  RelNode converted = toRel(relOptTable);
2241  bb.setRoot(converted, true);
2242  return;
2243  }
2244 
2245  Type elementType;
2246  if (operator instanceof SqlUserDefinedTableFunction) {
2247  SqlUserDefinedTableFunction udtf = (SqlUserDefinedTableFunction) operator;
2248  elementType = udtf.getElementType(typeFactory, callBinding.operands());
2249  } else {
2250  elementType = null;
2251  }
2252 
2253  RexNode rexCall = bb.convertExpression(call);
2254  final List<RelNode> inputs = bb.retrieveCursors();
2255  Set<RelColumnMapping> columnMappings = getColumnMappings(operator);
2256  LogicalTableFunctionScan callRel = LogicalTableFunctionScan.create(cluster,
2257  inputs,
2258  rexCall,
2259  elementType,
2260  validator.getValidatedNodeType(call),
2261  columnMappings);
2262  bb.setRoot(callRel, true);
2263  afterTableFunction(bb, call, callRel);
2264  }
void afterTableFunction(SqlToRelConverter.Blackboard bb, SqlCall call, LogicalTableFunctionScan callRel)
void replaceSubQueries(final Blackboard bb, final SqlNode expr, RelOptUtil.Logic logic)
Set< RelColumnMapping > getColumnMappings(SqlOperator op)
RelRoot convertQuery(SqlNode query, final boolean needsValidation, final boolean top)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertColumnList()

RelNode org.apache.calcite.sql2rel.SqlToRelConverter.convertColumnList ( final SqlInsert  call,
RelNode  source 
)
inlineprotected

Creates a source for an INSERT statement.

If the column list is not specified, source expressions match target columns in order.

If the column list is specified, Source expressions are mapped to target columns by name via targetColumnList, and may not cover the entire target table. So, we'll make up a full row, using a combination of default values and the source expressions provided.

Parameters
callInsert expression
sourceSource relational expression
Returns
Converted INSERT statement

Definition at line 3198 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.castNullLiteralIfNeeded(), org.apache.calcite.sql2rel.SqlToRelConverter.catalogReader, org.apache.calcite.sql2rel.SqlToRelConverter.collectInsertTargets(), org.apache.calcite.sql2rel.SqlToRelConverter.createInsertBlackboard(), field(), org.apache.calcite.sql2rel.SqlToRelConverter.getInitializerFactory(), org.apache.calcite.sql2rel.SqlToRelConverter.getTargetTable(), and Experimental.String.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertInsert().

3198  {
3199  RelDataType sourceRowType = source.getRowType();
3200  final RexNode sourceRef = rexBuilder.makeRangeReference(sourceRowType, 0, false);
3201  final List<String> targetColumnNames = new ArrayList<>();
3202  final List<RexNode> columnExprs = new ArrayList<>();
3203  collectInsertTargets(call, sourceRef, targetColumnNames, columnExprs);
3204 
3205  final RelOptTable targetTable = getTargetTable(call);
3206  final RelDataType targetRowType = RelOptTableImpl.realRowType(targetTable);
3207  final List<RelDataTypeField> targetFields = targetRowType.getFieldList();
3208  final List<RexNode> sourceExps =
3209  new ArrayList<>(Collections.nCopies(targetFields.size(), null));
3210  final List<String> fieldNames =
3211  new ArrayList<>(Collections.nCopies(targetFields.size(), null));
3212 
3213  final InitializerExpressionFactory initializerFactory =
3214  getInitializerFactory(validator.getNamespace(call).getTable());
3215 
3216  // Walk the name list and place the associated value in the
3217  // expression list according to the ordinal value returned from
3218  // the table construct, leaving nulls in the list for columns
3219  // that are not referenced.
3220  final SqlNameMatcher nameMatcher = catalogReader.nameMatcher();
3221  for (Pair<String, RexNode> p : Pair.zip(targetColumnNames, columnExprs)) {
3222  RelDataTypeField field = nameMatcher.field(targetRowType, p.left);
3223  assert field != null : "column " + p.left + " not found";
3224  sourceExps.set(field.getIndex(), p.right);
3225  }
3226 
3227  // Lazily create a blackboard that contains all non-generated columns.
3228  final Supplier<Blackboard> bb =
3229  () -> createInsertBlackboard(targetTable, sourceRef, targetColumnNames);
3230 
3231  // Walk the expression list and get default values for any columns
3232  // that were not supplied in the statement. Get field names too.
3233  for (int i = 0; i < targetFields.size(); ++i) {
3234  final RelDataTypeField field = targetFields.get(i);
3235  final String fieldName = field.getName();
3236  fieldNames.set(i, fieldName);
3237  if (sourceExps.get(i) == null || sourceExps.get(i).getKind() == SqlKind.DEFAULT) {
3238  sourceExps.set(
3239  i, initializerFactory.newColumnDefaultValue(targetTable, i, bb.get()));
3240 
3241  // bare nulls are dangerous in the wrong hands
3242  sourceExps.set(i, castNullLiteralIfNeeded(sourceExps.get(i), field.getType()));
3243  }
3244  }
3245 
3246  return relBuilder.push(source).projectNamed(sourceExps, fieldNames, false).build();
3247  }
RexNode castNullLiteralIfNeeded(RexNode node, RelDataType type)
InitializerExpressionFactory getInitializerFactory(SqlValidatorTable validatorTable)
const rapidjson::Value & field(const rapidjson::Value &obj, const char field[]) noexcept
Definition: JsonAccessors.h:31
void collectInsertTargets(SqlInsert call, final RexNode sourceRef, final List< String > targetColumnNames, List< RexNode > columnExprs)
Blackboard createInsertBlackboard(RelOptTable targetTable, RexNode sourceRef, List< String > targetColumnNames)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertCursor()

RelNode org.apache.calcite.sql2rel.SqlToRelConverter.convertCursor ( Blackboard  bb,
SubQuery  subQuery 
)
inlineprivate

Definition at line 3583 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.convertQuery(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.cursors, org.apache.calcite.sql2rel.SqlToRelConverter.SubQuery.expr, org.apache.calcite.sql2rel.SqlToRelConverter.SubQuery.node, and anonymous_namespace{UpdateMetadataTest.cpp}.query.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.substituteSubQuery().

3583  {
3584  final SqlCall cursorCall = (SqlCall) subQuery.node;
3585  assert cursorCall.operandCount() == 1;
3586  SqlNode query = cursorCall.operand(0);
3587  RelNode converted = convertQuery(query, false, false).rel;
3588  int iCursor = bb.cursors.size();
3589  bb.cursors.add(converted);
3590  subQuery.expr = new RexInputRef(iCursor, converted.getRowType());
3591  return converted;
3592  }
RelRoot convertQuery(SqlNode query, final boolean needsValidation, final boolean top)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertDelete()

RelNode org.apache.calcite.sql2rel.SqlToRelConverter.convertDelete ( SqlDelete  call)
inlineprivate

Definition at line 3371 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.catalogReader, org.apache.calcite.sql2rel.SqlToRelConverter.convertSelect(), and org.apache.calcite.sql2rel.SqlToRelConverter.getTargetTable().

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertQueryRecursive().

3371  {
3372  RelOptTable targetTable = getTargetTable(call);
3373  RelNode sourceRel = convertSelect(call.getSourceSelect(), false);
3374  return LogicalTableModify.create(targetTable,
3375  catalogReader,
3376  sourceRel,
3377  LogicalTableModify.Operation.DELETE,
3378  null,
3379  null,
3380  false);
3381  }
RelNode convertSelect(SqlSelect select, boolean top)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertDynamicParam()

RexDynamicParam org.apache.calcite.sql2rel.SqlToRelConverter.convertDynamicParam ( final SqlDynamicParam  dynamicParam)
inline

Definition at line 2819 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.getDynamicParamType().

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.visit().

2819  {
2820  // REVIEW jvs 8-Jan-2005: dynamic params may be encountered out of
2821  // order. Should probably cross-check with the count from the parser
2822  // at the end and make sure they all got filled in. Why doesn't List
2823  // have a resize() method?!? Make this a utility.
2824  while (dynamicParam.getIndex() >= dynamicParamSqlNodes.size()) {
2825  dynamicParamSqlNodes.add(null);
2826  }
2827 
2828  dynamicParamSqlNodes.set(dynamicParam.getIndex(), dynamicParam);
2829  return rexBuilder.makeDynamicParam(
2830  getDynamicParamType(dynamicParam.getIndex()), dynamicParam.getIndex());
2831  }
final List< SqlDynamicParam > dynamicParamSqlNodes
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertExists()

RelOptUtil.Exists org.apache.calcite.sql2rel.SqlToRelConverter.convertExists ( SqlNode  seek,
RelOptUtil.SubQueryType  subQueryType,
RelOptUtil.Logic  logic,
boolean  notIn,
RelDataType  targetDataType 
)
inlineprivate

Converts an EXISTS or IN predicate into a join. For EXISTS, the sub-query produces an indicator variable, and the result is a relational expression which outer joins that indicator to the original query. After performing the outer join, the condition will be TRUE if the EXISTS condition holds, NULL otherwise.

Parameters
seekA query, for example 'select * from emp' or 'values (1,2,3)' or '('Foo', 34)'.
subQueryTypeWhether sub-query is IN, EXISTS or scalar
logicWhether the answer needs to be in full 3-valued logic (TRUE, FALSE, UNKNOWN) will be required, or whether we can accept an approximation (say representing UNKNOWN as FALSE)
notInWhether the operation is NOT IN
Returns
join expression

Definition at line 1454 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.convertQueryOrInList(), and org.apache.calcite.sql2rel.SqlToRelConverter.createBlackboard().

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.substituteSubQuery().

1458  {
1459  final SqlValidatorScope seekScope = (seek instanceof SqlSelect)
1460  ? validator.getSelectScope((SqlSelect) seek)
1461  : null;
1462  final Blackboard seekBb = createBlackboard(seekScope, null, false);
1463  RelNode seekRel = convertQueryOrInList(seekBb, seek, targetDataType);
1464 
1465  return RelOptUtil.createExistsPlan(seekRel, subQueryType, logic, notIn, relBuilder);
1466  }
RelNode convertQueryOrInList(Blackboard bb, SqlNode seek, RelDataType targetRowType)
Blackboard createBlackboard(SqlValidatorScope scope, Map< String, RexNode > nameToNodeMap, boolean top)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertExpression() [1/2]

RexNode org.apache.calcite.sql2rel.SqlToRelConverter.convertExpression ( SqlNode  node)
inline

Converts an expression from SqlNode to RexNode format.

Parameters
nodeExpression to translate
Returns
Converted expression

Definition at line 1716 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.convertExpression(), and org.apache.calcite.sql2rel.SqlToRelConverter.createBlackboard().

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.convertExpression(), org.apache.calcite.sql2rel.SqlToRelConverter.convertOrder(), and org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.convertSortExpression().

1716  {
1717  Map<String, RelDataType> nameToTypeMap = Collections.emptyMap();
1718  final ParameterScope scope =
1719  new ParameterScope((SqlValidatorImpl) validator, nameToTypeMap);
1720  final Blackboard bb = createBlackboard(scope, null, false);
1721  return bb.convertExpression(node);
1722  }
Blackboard createBlackboard(SqlValidatorScope scope, Map< String, RexNode > nameToNodeMap, boolean top)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertExpression() [2/2]

RexNode org.apache.calcite.sql2rel.SqlToRelConverter.convertExpression ( SqlNode  node,
Map< String, RexNode >  nameToNodeMap 
)
inline

Converts an expression from SqlNode to RexNode format, mapping identifier references to predefined expressions.

Parameters
nodeExpression to translate
nameToNodeMapmap from String to RexNode; when an SqlIdentifier is encountered, it is used as a key and translated to the corresponding value from this map
Returns
Converted expression

Definition at line 1735 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.convertExpression(), org.apache.calcite.sql2rel.SqlToRelConverter.createBlackboard(), and Experimental.String.

1735  {
1736  final Map<String, RelDataType> nameToTypeMap = new HashMap<>();
1737  for (Map.Entry<String, RexNode> entry : nameToNodeMap.entrySet()) {
1738  nameToTypeMap.put(entry.getKey(), entry.getValue().getType());
1739  }
1740  final ParameterScope scope =
1741  new ParameterScope((SqlValidatorImpl) validator, nameToTypeMap);
1742  final Blackboard bb = createBlackboard(scope, nameToNodeMap, false);
1743  return bb.convertExpression(node);
1744  }
Blackboard createBlackboard(SqlValidatorScope scope, Map< String, RexNode > nameToNodeMap, boolean top)
+ Here is the call graph for this function:

◆ convertExtendedExpression()

RexNode org.apache.calcite.sql2rel.SqlToRelConverter.convertExtendedExpression ( SqlNode  node,
Blackboard  bb 
)
inlineprotected

Converts a non-standard expression.

This method is an extension-point that derived classes can override. If this method returns a null result, the normal expression translation process will proceed. The default implementation always returns null.

Parameters
nodeExpression
bbBlackboard
Returns
null to proceed with the usual expression translation process

Definition at line 1757 of file SqlToRelConverter.java.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.convertExpression().

1757  {
1758  return null;
1759  }
+ Here is the caller graph for this function:

◆ convertFrom()

void org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom ( Blackboard  bb,
SqlNode  from 
)
inlineprotected

Converts a FROM clause into a relational expression.

Parameters
bbScope within which to resolve identifiers
fromFROM clause of a query. Examples include:
        <ul>
        <li>a single table ("SALES.EMP"),
        <li>an aliased table ("EMP AS E"),
        <li>a list of tables ("EMP, DEPT"),
        <li>an ANSI Join expression ("EMP JOIN DEPT ON EMP.DEPTNO =
        DEPT.DEPTNO"),
        <li>a VALUES clause ("VALUES ('Fred', 20)"),
        <li>a query ("(SELECT * FROM EMP WHERE GENDER = 'F')"),
        <li>or any combination of the above.
        </ul>

Definition at line 1852 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.catalogReader, org.apache.calcite.sql2rel.SqlToRelConverter.convertCollectionTable(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.convertExpression(), org.apache.calcite.sql2rel.SqlToRelConverter.convertIdentifier(), org.apache.calcite.sql2rel.SqlToRelConverter.convertJoinCondition(), org.apache.calcite.sql2rel.SqlToRelConverter.convertJoinType(), org.apache.calcite.sql2rel.SqlToRelConverter.convertMatchRecognize(), org.apache.calcite.sql2rel.SqlToRelConverter.convertQueryRecursive(), org.apache.calcite.sql2rel.SqlToRelConverter.convertUsing(), org.apache.calcite.sql2rel.SqlToRelConverter.convertValuesImpl(), org.apache.calcite.sql2rel.SqlToRelConverter.createBlackboard(), org.apache.calcite.sql2rel.SqlToRelConverter.createJoin(), join(), anonymous_namespace{UpdateMetadataTest.cpp}.query, org.apache.calcite.sql2rel.SqlToRelConverter.replaceSubQueries(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.root, org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.scope, org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.setRoot(), org.apache.calcite.sql2rel.SqlToRelConverter.snapshotTemporalTable(), and Experimental.String.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertIdentifier(), org.apache.calcite.sql2rel.SqlToRelConverter.convertMatchRecognize(), org.apache.calcite.sql2rel.SqlToRelConverter.convertSelectImpl(), and org.apache.calcite.sql2rel.SqlToRelConverter.snapshotTemporalTable().

1852  {
1853  if (from == null) {
1854  bb.setRoot(LogicalValues.createOneRow(cluster), false);
1855  return;
1856  }
1857 
1858  final SqlCall call;
1859  final SqlNode[] operands;
1860  switch (from.getKind()) {
1861  case MATCH_RECOGNIZE:
1862  convertMatchRecognize(bb, (SqlCall) from);
1863  return;
1864 
1865  case AS:
1866  call = (SqlCall) from;
1867  convertFrom(bb, call.operand(0));
1868  if (call.operandCount() > 2
1869  && (bb.root instanceof Values || bb.root instanceof Uncollect)) {
1870  final List<String> fieldNames = new ArrayList<>();
1871  for (SqlNode node : Util.skip(call.getOperandList(), 2)) {
1872  fieldNames.add(((SqlIdentifier) node).getSimple());
1873  }
1874  bb.setRoot(relBuilder.push(bb.root).rename(fieldNames).build(), true);
1875  }
1876  return;
1877 
1878  case WITH_ITEM:
1879  convertFrom(bb, ((SqlWithItem) from).query);
1880  return;
1881 
1882  case WITH:
1883  convertFrom(bb, ((SqlWith) from).body);
1884  return;
1885 
1886  case TABLESAMPLE:
1887  operands = ((SqlBasicCall) from).getOperands();
1888  SqlSampleSpec sampleSpec = SqlLiteral.sampleValue(operands[1]);
1889  if (sampleSpec instanceof SqlSampleSpec.SqlSubstitutionSampleSpec) {
1890  String sampleName =
1891  ((SqlSampleSpec.SqlSubstitutionSampleSpec) sampleSpec).getName();
1892  datasetStack.push(sampleName);
1893  convertFrom(bb, operands[0]);
1894  datasetStack.pop();
1895  } else if (sampleSpec instanceof SqlSampleSpec.SqlTableSampleSpec) {
1896  SqlSampleSpec.SqlTableSampleSpec tableSampleSpec =
1897  (SqlSampleSpec.SqlTableSampleSpec) sampleSpec;
1898  convertFrom(bb, operands[0]);
1899  RelOptSamplingParameters params =
1900  new RelOptSamplingParameters(tableSampleSpec.isBernoulli(),
1901  tableSampleSpec.getSamplePercentage(),
1902  tableSampleSpec.isRepeatable(),
1903  tableSampleSpec.getRepeatableSeed());
1904  bb.setRoot(new Sample(cluster, bb.root, params), false);
1905  } else {
1906  throw new AssertionError("unknown TABLESAMPLE type: " + sampleSpec);
1907  }
1908  return;
1909 
1910  case IDENTIFIER:
1911  convertIdentifier(bb, (SqlIdentifier) from, null);
1912  return;
1913 
1914  case EXTEND:
1915  call = (SqlCall) from;
1916  SqlIdentifier id = (SqlIdentifier) call.getOperandList().get(0);
1917  SqlNodeList extendedColumns = (SqlNodeList) call.getOperandList().get(1);
1918  convertIdentifier(bb, id, extendedColumns);
1919  return;
1920 
1921  case SNAPSHOT:
1922  snapshotTemporalTable(bb, (SqlCall) from);
1923  return;
1924 
1925  case JOIN:
1926  final SqlJoin join = (SqlJoin) from;
1927  final SqlValidatorScope scope = validator.getJoinScope(from);
1928  final Blackboard fromBlackboard = createBlackboard(scope, null, false);
1929  SqlNode left = join.getLeft();
1930  SqlNode right = join.getRight();
1931  final boolean isNatural = join.isNatural();
1932  final JoinType joinType = join.getJoinType();
1933  final SqlValidatorScope leftScope = Util.first(
1934  validator.getJoinScope(left), ((DelegatingScope) bb.scope).getParent());
1935  final Blackboard leftBlackboard = createBlackboard(leftScope, null, false);
1936  final SqlValidatorScope rightScope = Util.first(
1937  validator.getJoinScope(right), ((DelegatingScope) bb.scope).getParent());
1938  final Blackboard rightBlackboard = createBlackboard(rightScope, null, false);
1939  convertFrom(leftBlackboard, left);
1940  RelNode leftRel = leftBlackboard.root;
1941  convertFrom(rightBlackboard, right);
1942  RelNode rightRel = rightBlackboard.root;
1943  JoinRelType convertedJoinType = convertJoinType(joinType);
1944  RexNode conditionExp;
1945  final SqlValidatorNamespace leftNamespace = validator.getNamespace(left);
1946  final SqlValidatorNamespace rightNamespace = validator.getNamespace(right);
1947  if (isNatural) {
1948  final RelDataType leftRowType = leftNamespace.getRowType();
1949  final RelDataType rightRowType = rightNamespace.getRowType();
1950  final List<String> columnList = SqlValidatorUtil.deriveNaturalJoinColumnList(
1951  catalogReader.nameMatcher(), leftRowType, rightRowType);
1952  conditionExp = convertUsing(leftNamespace, rightNamespace, columnList);
1953  } else {
1954  conditionExp = convertJoinCondition(fromBlackboard,
1955  leftNamespace,
1956  rightNamespace,
1957  join.getCondition(),
1958  join.getConditionType(),
1959  leftRel,
1960  rightRel);
1961  }
1962 
1963  final RelNode joinRel = createJoin(
1964  fromBlackboard, leftRel, rightRel, conditionExp, convertedJoinType);
1965  bb.setRoot(joinRel, false);
1966  return;
1967 
1968  case SELECT:
1969  case INTERSECT:
1970  case EXCEPT:
1971  case UNION:
1972  final RelNode rel = convertQueryRecursive(from, false, null).project();
1973  bb.setRoot(rel, true);
1974  return;
1975 
1976  case VALUES:
1977  convertValuesImpl(bb, (SqlCall) from, null);
1978  return;
1979 
1980  case UNNEST:
1981  call = (SqlCall) from;
1982  final List<SqlNode> nodes = call.getOperandList();
1983  final SqlUnnestOperator operator = (SqlUnnestOperator) call.getOperator();
1984  for (SqlNode node : nodes) {
1985  replaceSubQueries(bb, node, RelOptUtil.Logic.TRUE_FALSE_UNKNOWN);
1986  }
1987  final List<RexNode> exprs = new ArrayList<>();
1988  final List<String> fieldNames = new ArrayList<>();
1989  for (Ord<SqlNode> node : Ord.zip(nodes)) {
1990  exprs.add(bb.convertExpression(node.e));
1991  fieldNames.add(validator.deriveAlias(node.e, node.i));
1992  }
1993  RelNode child = (null != bb.root) ? bb.root : LogicalValues.createOneRow(cluster);
1994  relBuilder.push(child).projectNamed(exprs, fieldNames, false);
1995 
1996  Uncollect uncollect = new Uncollect(cluster,
1997  cluster.traitSetOf(Convention.NONE),
1998  relBuilder.build(),
1999  operator.withOrdinality);
2000  bb.setRoot(uncollect, true);
2001  return;
2002 
2003  case COLLECTION_TABLE:
2004  call = (SqlCall) from;
2005 
2006  // Dig out real call; TABLE() wrapper is just syntactic.
2007  assert call.getOperandList().size() == 1;
2008  final SqlCall call2 = call.operand(0);
2009  convertCollectionTable(bb, call2);
2010  return;
2011 
2012  default:
2013  throw new AssertionError("not a join operator " + from);
2014  }
2015  }
void snapshotTemporalTable(Blackboard bb, SqlCall call)
JoinType
Definition: sqldefs.h:98
void convertCollectionTable(Blackboard bb, SqlCall call)
std::string join(T const &container, std::string const &delim)
void convertValuesImpl(Blackboard bb, SqlCall values, RelDataType targetRowType)
void convertFrom(Blackboard bb, SqlNode from)
RelRoot convertQueryRecursive(SqlNode query, boolean top, RelDataType targetRowType)
RexNode convertUsing(SqlValidatorNamespace leftNamespace, SqlValidatorNamespace rightNamespace, List< String > nameList)
RexNode convertJoinCondition(Blackboard bb, SqlValidatorNamespace leftNamespace, SqlValidatorNamespace rightNamespace, SqlNode condition, JoinConditionType conditionType, RelNode leftRel, RelNode rightRel)
void replaceSubQueries(final Blackboard bb, final SqlNode expr, RelOptUtil.Logic logic)
void convertIdentifier(Blackboard bb, SqlIdentifier id, SqlNodeList extendedColumns)
void convertMatchRecognize(Blackboard bb, SqlCall call)
RelNode createJoin(Blackboard bb, RelNode leftRel, RelNode rightRel, RexNode joinCond, JoinRelType joinType)
Blackboard createBlackboard(SqlValidatorScope scope, Map< String, RexNode > nameToNodeMap, boolean top)
static JoinRelType convertJoinType(JoinType joinType)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertIdentifier() [1/2]

void org.apache.calcite.sql2rel.SqlToRelConverter.convertIdentifier ( Blackboard  bb,
SqlIdentifier  id,
SqlNodeList  extendedColumns 
)
inlineprivate

Definition at line 2185 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.catalogReader, org.apache.calcite.sql2rel.SqlToRelConverter.config, org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.setDataset(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.setRoot(), Experimental.String, and org.apache.calcite.sql2rel.SqlToRelConverter.toRel().

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(), and org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.visit().

2186  {
2187  final SqlValidatorNamespace fromNamespace = validator.getNamespace(id).resolve();
2188  if (fromNamespace.getNode() != null) {
2189  convertFrom(bb, fromNamespace.getNode());
2190  return;
2191  }
2192  final String datasetName = datasetStack.isEmpty() ? null : datasetStack.peek();
2193  final boolean[] usedDataset = {false};
2194  RelOptTable table = SqlValidatorUtil.getRelOptTable(
2195  fromNamespace, catalogReader, datasetName, usedDataset);
2196  if (extendedColumns != null && extendedColumns.size() > 0) {
2197  assert table != null;
2198  final SqlValidatorTable validatorTable = table.unwrap(SqlValidatorTable.class);
2199  final List<RelDataTypeField> extendedFields = SqlValidatorUtil.getExtendedColumns(
2200  validator.getTypeFactory(), validatorTable, extendedColumns);
2201  table = table.extend(extendedFields);
2202  }
2203  final RelNode tableRel;
2204  if (config.isConvertTableAccess()) {
2205  tableRel = toRel(table);
2206  } else {
2207  tableRel = LogicalTableScan.create(cluster, table);
2208  }
2209  bb.setRoot(tableRel, true);
2210  if (usedDataset[0]) {
2211  bb.setDataset(datasetName);
2212  }
2213  }
void convertFrom(Blackboard bb, SqlNode from)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertIdentifier() [2/2]

RexNode org.apache.calcite.sql2rel.SqlToRelConverter.convertIdentifier ( Blackboard  bb,
SqlIdentifier  identifier 
)
inlineprivate

Converts an identifier into an expression in a given scope. For example, the "empno" in "select empno from emp join dept" becomes "emp.empno".

Definition at line 3503 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.adjustInputRef(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.convertExpression(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.getValidator(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.isPatternVarRef, org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.lookupExp(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.mapCorrelateToRex, org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.scope, and Experimental.String.

3503  {
3504  // first check for reserved identifiers like CURRENT_USER
3505  final SqlCall call = bb.getValidator().makeNullaryCall(identifier);
3506  if (call != null) {
3507  return bb.convertExpression(call);
3508  }
3509 
3510  String pv = null;
3511  if (bb.isPatternVarRef && identifier.names.size() > 1) {
3512  pv = identifier.names.get(0);
3513  }
3514 
3515  final SqlQualified qualified;
3516  if (bb.scope != null) {
3517  qualified = bb.scope.fullyQualify(identifier);
3518  } else {
3519  qualified = SqlQualified.create(null, 1, null, identifier);
3520  }
3521  final Pair<RexNode, Map<String, Integer>> e0 = bb.lookupExp(qualified);
3522  RexNode e = e0.left;
3523  for (String name : qualified.suffix()) {
3524  if (e == e0.left && e0.right != null) {
3525  int i = e0.right.get(name);
3526  e = rexBuilder.makeFieldAccess(e, i);
3527  } else {
3528  final boolean caseSensitive = true; // name already fully-qualified
3529  if (identifier.isStar() && bb.scope instanceof MatchRecognizeScope) {
3530  e = rexBuilder.makeFieldAccess(e, 0);
3531  } else {
3532  e = rexBuilder.makeFieldAccess(e, name, caseSensitive);
3533  }
3534  }
3535  }
3536  if (e instanceof RexInputRef) {
3537  // adjust the type to account for nulls introduced by outer joins
3538  e = adjustInputRef(bb, (RexInputRef) e);
3539  if (pv != null) {
3540  e = RexPatternFieldRef.of(pv, (RexInputRef) e);
3541  }
3542  }
3543 
3544  if (e0.left instanceof RexCorrelVariable) {
3545  assert e instanceof RexFieldAccess;
3546  final RexNode prev = bb.mapCorrelateToRex.put(
3547  ((RexCorrelVariable) e0.left).id, (RexFieldAccess) e);
3548  assert prev == null;
3549  }
3550  return e;
3551  }
RexNode adjustInputRef(Blackboard bb, RexInputRef inputRef)
+ Here is the call graph for this function:

◆ convertInsert()

RelNode org.apache.calcite.sql2rel.SqlToRelConverter.convertInsert ( SqlInsert  call)
inlineprotected

Definition at line 3037 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.convertColumnList(), org.apache.calcite.sql2rel.SqlToRelConverter.convertQueryRecursive(), org.apache.calcite.sql2rel.SqlToRelConverter.createModify(), and org.apache.calcite.sql2rel.SqlToRelConverter.getTargetTable().

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertMerge(), and org.apache.calcite.sql2rel.SqlToRelConverter.convertQueryRecursive().

3037  {
3038  RelOptTable targetTable = getTargetTable(call);
3039 
3040  final RelDataType targetRowType = validator.getValidatedNodeType(call);
3041  assert targetRowType != null;
3042  RelNode sourceRel =
3043  convertQueryRecursive(call.getSource(), false, targetRowType).project();
3044  RelNode massagedRel = convertColumnList(call, sourceRel);
3045 
3046  return createModify(targetTable, massagedRel);
3047  }
RelRoot convertQueryRecursive(SqlNode query, boolean top, RelDataType targetRowType)
RelNode createModify(RelOptTable targetTable, RelNode source)
RelNode convertColumnList(final SqlInsert call, RelNode source)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertInToOr()

RexNode org.apache.calcite.sql2rel.SqlToRelConverter.convertInToOr ( final Blackboard  bb,
final List< RexNode >  leftKeys,
SqlNodeList  valuesList,
SqlInOperator  op 
)
inlineprivate

Converts "x IN (1, 2, ...)" to "x=1 OR x=2 OR ...".

Parameters
leftKeysLHS
valuesListRHS
opThe operator (IN, NOT IN, > SOME, ...)
Returns
converted expression

Definition at line 1360 of file SqlToRelConverter.java.

References ALL, org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.convertExpression(), and org.apache.calcite.sql2rel.SqlToRelConverter.ensureSqlType().

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.substituteSubQuery().

1363  {
1364  final List<RexNode> comparisons = new ArrayList<>();
1365  for (SqlNode rightVals : valuesList) {
1366  RexNode rexComparison;
1367  final SqlOperator comparisonOp;
1368  if (op instanceof SqlQuantifyOperator) {
1369  comparisonOp = RelOptUtil.op(
1370  ((SqlQuantifyOperator) op).comparisonKind, SqlStdOperatorTable.EQUALS);
1371  } else {
1372  comparisonOp = SqlStdOperatorTable.EQUALS;
1373  }
1374  if (leftKeys.size() == 1) {
1375  rexComparison = rexBuilder.makeCall(comparisonOp,
1376  leftKeys.get(0),
1377  ensureSqlType(
1378  leftKeys.get(0).getType(), bb.convertExpression(rightVals)));
1379  } else {
1380  assert rightVals instanceof SqlCall;
1381  final SqlBasicCall call = (SqlBasicCall) rightVals;
1382  assert (call.getOperator() instanceof SqlRowOperator)
1383  && call.operandCount() == leftKeys.size();
1384  rexComparison = RexUtil.composeConjunction(rexBuilder,
1385  Iterables.transform(Pair.zip(leftKeys, call.getOperandList()),
1386  pair
1387  -> rexBuilder.makeCall(comparisonOp,
1388  pair.left,
1389  ensureSqlType(pair.left.getType(),
1390  bb.convertExpression(pair.right)))));
1391  }
1392  comparisons.add(rexComparison);
1393  }
1394 
1395  switch (op.kind) {
1396  case ALL:
1397  return RexUtil.composeConjunction(rexBuilder, comparisons, true);
1398  case NOT_IN:
1399  return rexBuilder.makeCall(SqlStdOperatorTable.NOT,
1400  RexUtil.composeDisjunction(rexBuilder, comparisons, true));
1401  case IN:
1402  case SOME:
1403  return RexUtil.composeDisjunction(rexBuilder, comparisons, true);
1404  default:
1405  throw new AssertionError();
1406  }
1407  }
const std::vector< std::shared_ptr< TestColumnDescriptor > > ALL
RexNode ensureSqlType(RelDataType type, RexNode node)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertJoinCondition()

RexNode org.apache.calcite.sql2rel.SqlToRelConverter.convertJoinCondition ( Blackboard  bb,
SqlValidatorNamespace  leftNamespace,
SqlValidatorNamespace  rightNamespace,
SqlNode  condition,
JoinConditionType  conditionType,
RelNode  leftRel,
RelNode  rightRel 
)
inlineprivate

Definition at line 2526 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.convertExpression(), org.apache.calcite.sql2rel.SqlToRelConverter.convertUsing(), org.apache.calcite.sql2rel.SqlToRelConverter.replaceSubQueries(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.setRoot(), and Experimental.String.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom().

2532  {
2533  if (condition == null) {
2534  return rexBuilder.makeLiteral(true);
2535  }
2536  bb.setRoot(ImmutableList.of(leftRel, rightRel));
2537  replaceSubQueries(bb, condition, RelOptUtil.Logic.UNKNOWN_AS_FALSE);
2538  switch (conditionType) {
2539  case ON:
2540  bb.setRoot(ImmutableList.of(leftRel, rightRel));
2541  return bb.convertExpression(condition);
2542  case USING:
2543  final SqlNodeList list = (SqlNodeList) condition;
2544  final List<String> nameList = new ArrayList<>();
2545  for (SqlNode columnName : list) {
2546  final SqlIdentifier id = (SqlIdentifier) columnName;
2547  String name = id.getSimple();
2548  nameList.add(name);
2549  }
2550  return convertUsing(leftNamespace, rightNamespace, nameList);
2551  default:
2552  throw Util.unexpected(conditionType);
2553  }
2554  }
RexNode convertUsing(SqlValidatorNamespace leftNamespace, SqlValidatorNamespace rightNamespace, List< String > nameList)
void replaceSubQueries(final Blackboard bb, final SqlNode expr, RelOptUtil.Logic logic)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertJoinType()

static JoinRelType org.apache.calcite.sql2rel.SqlToRelConverter.convertJoinType ( JoinType  joinType)
inlinestaticprivate

Definition at line 2586 of file SqlToRelConverter.java.

References INNER, and LEFT.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom().

2586  {
2587  switch (joinType) {
2588  case COMMA:
2589  case INNER:
2590  case CROSS:
2591  return JoinRelType.INNER;
2592  case FULL:
2593  return JoinRelType.FULL;
2594  case LEFT:
2595  return JoinRelType.LEFT;
2596  case RIGHT:
2597  return JoinRelType.RIGHT;
2598  default:
2599  throw Util.unexpected(joinType);
2600  }
2601  }
+ Here is the caller graph for this function:

◆ convertLiteralInValuesList()

RexLiteral org.apache.calcite.sql2rel.SqlToRelConverter.convertLiteralInValuesList ( SqlNode  sqlNode,
Blackboard  bb,
RelDataType  rowType,
int  iField 
)
inlineprivate

Definition at line 1558 of file SqlToRelConverter.java.

References field(), and run-benchmark-import.type.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertRowValues().

1559  {
1560  if (!(sqlNode instanceof SqlLiteral)) {
1561  return null;
1562  }
1563  RelDataTypeField field = rowType.getFieldList().get(iField);
1564  RelDataType type = field.getType();
1565  if (type.isStruct()) {
1566  // null literals for weird stuff like UDT's need
1567  // special handling during type flattening, so
1568  // don't use LogicalValues for those
1569  return null;
1570  }
1571 
1572  RexNode literalExpr = exprConverter.convertLiteral(bb, (SqlLiteral) sqlNode);
1573 
1574  if (!(literalExpr instanceof RexLiteral)) {
1575  assert literalExpr.isA(SqlKind.CAST);
1576  RexNode child = ((RexCall) literalExpr).getOperands().get(0);
1577  assert RexLiteral.isNullLiteral(child);
1578 
1579  // NOTE jvs 22-Nov-2006: we preserve type info
1580  // in LogicalValues digest, so it's OK to lose it here
1581  return (RexLiteral) child;
1582  }
1583 
1584  RexLiteral literal = (RexLiteral) literalExpr;
1585 
1586  Comparable value = literal.getValue();
1587 
1588  if (SqlTypeUtil.isExactNumeric(type) && SqlTypeUtil.hasScale(type)) {
1589  BigDecimal roundedValue =
1590  NumberUtil.rescaleBigDecimal((BigDecimal) value, type.getScale());
1591  return rexBuilder.makeExactLiteral(roundedValue, type);
1592  }
1593 
1594  if ((value instanceof NlsString) && (type.getSqlTypeName() == SqlTypeName.CHAR)) {
1595  // pad fixed character type
1596  NlsString unpadded = (NlsString) value;
1597  return rexBuilder.makeCharLiteral(
1598  new NlsString(Spaces.padRight(unpadded.getValue(), type.getPrecision()),
1599  unpadded.getCharsetName(),
1600  unpadded.getCollation()));
1601  }
1602  return literal;
1603  }
const rapidjson::Value & field(const rapidjson::Value &obj, const char field[]) noexcept
Definition: JsonAccessors.h:31
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertMatchRecognize()

void org.apache.calcite.sql2rel.SqlToRelConverter.convertMatchRecognize ( Blackboard  bb,
SqlCall  call 
)
inlineprotected

Definition at line 2017 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.convertExpression(), org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.convertLiteral(), org.apache.calcite.sql2rel.SqlToRelConverter.createBlackboard(), org.apache.calcite.sql2rel.SqlToRelConverter.desc(), org.apache.calcite.sql2rel.SqlToRelConverter.replaceSubQueries(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.root, org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.setPatternVarRef(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.setRoot(), and Experimental.String.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom().

2017  {
2018  final SqlMatchRecognize matchRecognize = (SqlMatchRecognize) call;
2019  final SqlValidatorNamespace ns = validator.getNamespace(matchRecognize);
2020  final SqlValidatorScope scope = validator.getMatchRecognizeScope(matchRecognize);
2021 
2022  final Blackboard matchBb = createBlackboard(scope, null, false);
2023  final RelDataType rowType = ns.getRowType();
2024  // convert inner query, could be a table name or a derived table
2025  SqlNode expr = matchRecognize.getTableRef();
2026  convertFrom(matchBb, expr);
2027  final RelNode input = matchBb.root;
2028 
2029  // PARTITION BY
2030  final SqlNodeList partitionList = matchRecognize.getPartitionList();
2031  final List<RexNode> partitionKeys = new ArrayList<>();
2032  for (SqlNode partition : partitionList) {
2033  RexNode e = matchBb.convertExpression(partition);
2034  partitionKeys.add(e);
2035  }
2036 
2037  // ORDER BY
2038  final SqlNodeList orderList = matchRecognize.getOrderList();
2039  final List<RelFieldCollation> orderKeys = new ArrayList<>();
2040  for (SqlNode order : orderList) {
2041  final RelFieldCollation.Direction direction;
2042  switch (order.getKind()) {
2043  case DESCENDING:
2044  direction = RelFieldCollation.Direction.DESCENDING;
2045  order = ((SqlCall) order).operand(0);
2046  break;
2047  case NULLS_FIRST:
2048  case NULLS_LAST:
2049  throw new AssertionError();
2050  default:
2051  direction = RelFieldCollation.Direction.ASCENDING;
2052  break;
2053  }
2054  final RelFieldCollation.NullDirection nullDirection =
2055  validator.getDefaultNullCollation().last(desc(direction))
2056  ? RelFieldCollation.NullDirection.LAST
2057  : RelFieldCollation.NullDirection.FIRST;
2058  RexNode e = matchBb.convertExpression(order);
2059  orderKeys.add(new RelFieldCollation(
2060  ((RexInputRef) e).getIndex(), direction, nullDirection));
2061  }
2062  final RelCollation orders = cluster.traitSet().canonize(RelCollations.of(orderKeys));
2063 
2064  // convert pattern
2065  final Set<String> patternVarsSet = new HashSet<>();
2066  SqlNode pattern = matchRecognize.getPattern();
2067  final SqlBasicVisitor<RexNode> patternVarVisitor = new SqlBasicVisitor<RexNode>() {
2068  @Override
2069  public RexNode visit(SqlCall call) {
2070  List<SqlNode> operands = call.getOperandList();
2071  List<RexNode> newOperands = new ArrayList<>();
2072  for (SqlNode node : operands) {
2073  newOperands.add(node.accept(this));
2074  }
2075  return rexBuilder.makeCall(
2076  validator.getUnknownType(), call.getOperator(), newOperands);
2077  }
2078 
2079  @Override
2080  public RexNode visit(SqlIdentifier id) {
2081  assert id.isSimple();
2082  patternVarsSet.add(id.getSimple());
2083  return rexBuilder.makeLiteral(id.getSimple());
2084  }
2085 
2086  @Override
2087  public RexNode visit(SqlLiteral literal) {
2088  if (literal instanceof SqlNumericLiteral) {
2089  return rexBuilder.makeExactLiteral(BigDecimal.valueOf(literal.intValue(true)));
2090  } else {
2091  return rexBuilder.makeLiteral(literal.booleanValue());
2092  }
2093  }
2094  };
2095  final RexNode patternNode = pattern.accept(patternVarVisitor);
2096 
2097  SqlLiteral interval = matchRecognize.getInterval();
2098  RexNode intervalNode = null;
2099  if (interval != null) {
2100  intervalNode = matchBb.convertLiteral(interval);
2101  }
2102 
2103  // convert subset
2104  final SqlNodeList subsets = matchRecognize.getSubsetList();
2105  final Map<String, TreeSet<String>> subsetMap = new HashMap<>();
2106  for (SqlNode node : subsets) {
2107  List<SqlNode> operands = ((SqlCall) node).getOperandList();
2108  SqlIdentifier left = (SqlIdentifier) operands.get(0);
2109  patternVarsSet.add(left.getSimple());
2110  SqlNodeList rights = (SqlNodeList) operands.get(1);
2111  final TreeSet<String> list = new TreeSet<>();
2112  for (SqlNode right : rights) {
2113  assert right instanceof SqlIdentifier;
2114  list.add(((SqlIdentifier) right).getSimple());
2115  }
2116  subsetMap.put(left.getSimple(), list);
2117  }
2118 
2119  SqlNode afterMatch = matchRecognize.getAfter();
2120  if (afterMatch == null) {
2121  afterMatch =
2122  SqlMatchRecognize.AfterOption.SKIP_TO_NEXT_ROW.symbol(SqlParserPos.ZERO);
2123  }
2124 
2125  final RexNode after;
2126  if (afterMatch instanceof SqlCall) {
2127  List<SqlNode> operands = ((SqlCall) afterMatch).getOperandList();
2128  SqlOperator operator = ((SqlCall) afterMatch).getOperator();
2129  assert operands.size() == 1;
2130  SqlIdentifier id = (SqlIdentifier) operands.get(0);
2131  assert patternVarsSet.contains(id.getSimple())
2132  : id.getSimple()
2133  + " not defined in pattern";
2134  RexNode rex = rexBuilder.makeLiteral(id.getSimple());
2135  after = rexBuilder.makeCall(
2136  validator.getUnknownType(), operator, ImmutableList.of(rex));
2137  } else {
2138  after = matchBb.convertExpression(afterMatch);
2139  }
2140 
2141  matchBb.setPatternVarRef(true);
2142 
2143  // convert measures
2144  final ImmutableMap.Builder<String, RexNode> measureNodes = ImmutableMap.builder();
2145  for (SqlNode measure : matchRecognize.getMeasureList()) {
2146  List<SqlNode> operands = ((SqlCall) measure).getOperandList();
2147  String alias = ((SqlIdentifier) operands.get(1)).getSimple();
2148  RexNode rex = matchBb.convertExpression(operands.get(0));
2149  measureNodes.put(alias, rex);
2150  }
2151 
2152  // convert definitions
2153  final ImmutableMap.Builder<String, RexNode> definitionNodes = ImmutableMap.builder();
2154  for (SqlNode def : matchRecognize.getPatternDefList()) {
2155  replaceSubQueries(matchBb, def, RelOptUtil.Logic.UNKNOWN_AS_FALSE);
2156  List<SqlNode> operands = ((SqlCall) def).getOperandList();
2157  String alias = ((SqlIdentifier) operands.get(1)).getSimple();
2158  RexNode rex = matchBb.convertExpression(operands.get(0));
2159  definitionNodes.put(alias, rex);
2160  }
2161 
2162  final SqlLiteral rowsPerMatch = matchRecognize.getRowsPerMatch();
2163  final boolean allRows = rowsPerMatch != null
2164  && rowsPerMatch.getValue() == SqlMatchRecognize.RowsPerMatchOption.ALL_ROWS;
2165 
2166  matchBb.setPatternVarRef(false);
2167 
2168  final RelFactories.MatchFactory factory = RelFactories.DEFAULT_MATCH_FACTORY;
2169  final RelNode rel = factory.createMatch(input,
2170  patternNode,
2171  rowType,
2172  matchRecognize.getStrictStart().booleanValue(),
2173  matchRecognize.getStrictEnd().booleanValue(),
2174  definitionNodes.build(),
2175  measureNodes.build(),
2176  after,
2177  subsetMap,
2178  allRows,
2179  partitionKeys,
2180  orders,
2181  intervalNode);
2182  bb.setRoot(rel, false);
2183  }
void convertFrom(Blackboard bb, SqlNode from)
void replaceSubQueries(final Blackboard bb, final SqlNode expr, RelOptUtil.Logic logic)
static boolean desc(RelFieldCollation.Direction direction)
Blackboard createBlackboard(SqlValidatorScope scope, Map< String, RexNode > nameToNodeMap, boolean top)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertMerge()

RelNode org.apache.calcite.sql2rel.SqlToRelConverter.convertMerge ( SqlMerge  call)
inlineprivate

Definition at line 3419 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.catalogReader, org.apache.calcite.sql2rel.SqlToRelConverter.convertInsert(), org.apache.calcite.sql2rel.SqlToRelConverter.convertSelect(), field(), org.apache.calcite.sql2rel.SqlToRelConverter.getTargetTable(), and join().

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertQueryRecursive().

3419  {
3420  RelOptTable targetTable = getTargetTable(call);
3421 
3422  // convert update column list from SqlIdentifier to String
3423  final List<String> targetColumnNameList = new ArrayList<>();
3424  final RelDataType targetRowType = targetTable.getRowType();
3425  SqlUpdate updateCall = call.getUpdateCall();
3426  if (updateCall != null) {
3427  for (SqlNode targetColumn : updateCall.getTargetColumnList()) {
3428  SqlIdentifier id = (SqlIdentifier) targetColumn;
3429  RelDataTypeField field = SqlValidatorUtil.getTargetField(
3430  targetRowType, typeFactory, id, catalogReader, targetTable);
3431  assert field != null : "column " + id.toString() + " not found";
3432  targetColumnNameList.add(field.getName());
3433  }
3434  }
3435 
3436  // replace the projection of the source select with a
3437  // projection that contains the following:
3438  // 1) the expressions corresponding to the new insert row (if there is
3439  // an insert)
3440  // 2) all columns from the target table (if there is an update)
3441  // 3) the set expressions in the update call (if there is an update)
3442 
3443  // first, convert the merge's source select to construct the columns
3444  // from the target table and the set expressions in the update call
3445  RelNode mergeSourceRel = convertSelect(call.getSourceSelect(), false);
3446 
3447  // then, convert the insert statement so we can get the insert
3448  // values expressions
3449  SqlInsert insertCall = call.getInsertCall();
3450  int nLevel1Exprs = 0;
3451  List<RexNode> level1InsertExprs = null;
3452  List<RexNode> level2InsertExprs = null;
3453  if (insertCall != null) {
3454  RelNode insertRel = convertInsert(insertCall);
3455 
3456  // if there are 2 level of projections in the insert source, combine
3457  // them into a single project; level1 refers to the topmost project;
3458  // the level1 projection contains references to the level2
3459  // expressions, except in the case where no target expression was
3460  // provided, in which case, the expression is the default value for
3461  // the column; or if the expressions directly map to the source
3462  // table
3463  level1InsertExprs = ((LogicalProject) insertRel.getInput(0)).getProjects();
3464  if (insertRel.getInput(0).getInput(0) instanceof LogicalProject) {
3465  level2InsertExprs =
3466  ((LogicalProject) insertRel.getInput(0).getInput(0)).getProjects();
3467  }
3468  nLevel1Exprs = level1InsertExprs.size();
3469  }
3470 
3471  LogicalJoin join = (LogicalJoin) mergeSourceRel.getInput(0);
3472  int nSourceFields = join.getLeft().getRowType().getFieldCount();
3473  final List<RexNode> projects = new ArrayList<>();
3474  for (int level1Idx = 0; level1Idx < nLevel1Exprs; level1Idx++) {
3475  if ((level2InsertExprs != null)
3476  && (level1InsertExprs.get(level1Idx) instanceof RexInputRef)) {
3477  int level2Idx = ((RexInputRef) level1InsertExprs.get(level1Idx)).getIndex();
3478  projects.add(level2InsertExprs.get(level2Idx));
3479  } else {
3480  projects.add(level1InsertExprs.get(level1Idx));
3481  }
3482  }
3483  if (updateCall != null) {
3484  final LogicalProject project = (LogicalProject) mergeSourceRel;
3485  projects.addAll(Util.skip(project.getProjects(), nSourceFields));
3486  }
3487 
3488  relBuilder.push(join).project(projects);
3489 
3490  return LogicalTableModify.create(targetTable,
3491  catalogReader,
3492  relBuilder.build(),
3493  LogicalTableModify.Operation.MERGE,
3494  targetColumnNameList,
3495  null,
3496  false);
3497  }
std::string join(T const &container, std::string const &delim)
const rapidjson::Value & field(const rapidjson::Value &obj, const char field[]) noexcept
Definition: JsonAccessors.h:31
RelNode convertSelect(SqlSelect select, boolean top)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertMultisets()

RelNode org.apache.calcite.sql2rel.SqlToRelConverter.convertMultisets ( final List< SqlNode >  operands,
Blackboard  bb 
)
inlineprivate

Definition at line 3594 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.convertQuery(), org.apache.calcite.sql2rel.SqlToRelConverter.convertQueryOrInList(), org.apache.calcite.sql2rel.SqlToRelConverter.createBlackboard(), and org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.scope.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertRowConstructor(), and org.apache.calcite.sql2rel.SqlToRelConverter.substituteSubQuery().

3594  {
3595  // NOTE: Wael 2/04/05: this implementation is not the most efficient in
3596  // terms of planning since it generates XOs that can be reduced.
3597  final List<Object> joinList = new ArrayList<>();
3598  List<SqlNode> lastList = new ArrayList<>();
3599  for (int i = 0; i < operands.size(); i++) {
3600  SqlNode operand = operands.get(i);
3601  if (!(operand instanceof SqlCall)) {
3602  lastList.add(operand);
3603  continue;
3604  }
3605 
3606  final SqlCall call = (SqlCall) operand;
3607  final RelNode input;
3608  switch (call.getKind()) {
3609  case MULTISET_VALUE_CONSTRUCTOR:
3610  case ARRAY_VALUE_CONSTRUCTOR:
3611  final SqlNodeList list =
3612  new SqlNodeList(call.getOperandList(), call.getParserPosition());
3613  CollectNamespace nss = (CollectNamespace) validator.getNamespace(call);
3614  Blackboard usedBb;
3615  if (null != nss) {
3616  usedBb = createBlackboard(nss.getScope(), null, false);
3617  } else {
3618  usedBb = createBlackboard(new ListScope(bb.scope) {
3619  public SqlNode getNode() {
3620  return call;
3621  }
3622  }, null, false);
3623  }
3624  RelDataType multisetType = validator.getValidatedNodeType(call);
3625  ((SqlValidatorImpl) validator)
3626  .setValidatedNodeType(list, multisetType.getComponentType());
3627  input = convertQueryOrInList(usedBb, list, null);
3628  break;
3629  case MULTISET_QUERY_CONSTRUCTOR:
3630  case ARRAY_QUERY_CONSTRUCTOR:
3631  final RelRoot root = convertQuery(call.operand(0), false, true);
3632  input = root.rel;
3633  break;
3634  default:
3635  lastList.add(operand);
3636  continue;
3637  }
3638 
3639  if (lastList.size() > 0) {
3640  joinList.add(lastList);
3641  }
3642  lastList = new ArrayList<>();
3643  Collect collect = new Collect(cluster,
3644  cluster.traitSetOf(Convention.NONE),
3645  input,
3646  validator.deriveAlias(call, i));
3647  joinList.add(collect);
3648  }
3649 
3650  if (joinList.size() == 0) {
3651  joinList.add(lastList);
3652  }
3653 
3654  for (int i = 0; i < joinList.size(); i++) {
3655  Object o = joinList.get(i);
3656  if (o instanceof List) {
3657  @SuppressWarnings("unchecked")
3658  List<SqlNode> projectList = (List<SqlNode>) o;
3659  final List<RexNode> selectList = new ArrayList<>();
3660  final List<String> fieldNameList = new ArrayList<>();
3661  for (int j = 0; j < projectList.size(); j++) {
3662  SqlNode operand = projectList.get(j);
3663  selectList.add(bb.convertExpression(operand));
3664 
3665  // REVIEW angel 5-June-2005: Use deriveAliasFromOrdinal
3666  // instead of deriveAlias to match field names from
3667  // SqlRowOperator. Otherwise, get error Type
3668  // 'RecordType(INTEGER EMPNO)' has no field 'EXPR$0' when
3669  // doing select * from unnest( select multiset[empno]
3670  // from sales.emps);
3671 
3672  fieldNameList.add(SqlUtil.deriveAliasFromOrdinal(j));
3673  }
3674 
3675  relBuilder.push(LogicalValues.createOneRow(cluster))
3676  .projectNamed(selectList, fieldNameList, true);
3677 
3678  joinList.set(i, relBuilder.build());
3679  }
3680  }
3681 
3682  RelNode ret = (RelNode) joinList.get(0);
3683  for (int i = 1; i < joinList.size(); i++) {
3684  RelNode relNode = (RelNode) joinList.get(i);
3685  ret = RelFactories.DEFAULT_JOIN_FACTORY.createJoin(ret,
3686  relNode,
3687  rexBuilder.makeLiteral(true),
3688  ImmutableSet.of(),
3689  JoinRelType.INNER,
3690  false);
3691  }
3692  return ret;
3693  }
RelNode convertQueryOrInList(Blackboard bb, SqlNode seek, RelDataType targetRowType)
Blackboard createBlackboard(SqlValidatorScope scope, Map< String, RexNode > nameToNodeMap, boolean top)
RelRoot convertQuery(SqlNode query, final boolean needsValidation, final boolean top)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertNonCorrelatedSubQuery()

boolean org.apache.calcite.sql2rel.SqlToRelConverter.convertNonCorrelatedSubQuery ( SubQuery  subQuery,
Blackboard  bb,
RelNode  converted,
boolean  isExists 
)
inlineprivate

Determines if a sub-query is non-correlated and if so, converts it to a constant.

Parameters
subQuerythe call that references the sub-query
bbblackboard used to convert the sub-query
convertedRelNode tree corresponding to the sub-query
isExiststrue if the sub-query is part of an EXISTS expression
Returns
Whether the sub-query can be converted to a constant

Definition at line 1282 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.config, org.apache.calcite.sql2rel.SqlToRelConverter.SubQuery.expr, org.apache.calcite.sql2rel.SqlToRelConverter.isSubQueryNonCorrelated(), and org.apache.calcite.sql2rel.SqlToRelConverter.SubQuery.node.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.substituteSubQuery().

1283  {
1284  SqlCall call = (SqlBasicCall) subQuery.node;
1285  if (subQueryConverter.canConvertSubQuery()
1286  && isSubQueryNonCorrelated(converted, bb)) {
1287  // First check if the sub-query has already been converted
1288  // because it's a nested sub-query. If so, don't re-evaluate
1289  // it again.
1290  RexNode constExpr = mapConvertedNonCorrSubqs.get(call);
1291  if (constExpr == null) {
1292  constExpr = subQueryConverter.convertSubQuery(
1293  call, this, isExists, config.isExplain());
1294  }
1295  if (constExpr != null) {
1296  subQuery.expr = constExpr;
1297  mapConvertedNonCorrSubqs.put(call, constExpr);
1298  return true;
1299  }
1300  }
1301  return false;
1302  }
final Map< SqlNode, RexNode > mapConvertedNonCorrSubqs
boolean isSubQueryNonCorrelated(RelNode subq, Blackboard bb)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertOrder()

void org.apache.calcite.sql2rel.SqlToRelConverter.convertOrder ( SqlSelect  select,
Blackboard  bb,
RelCollation  collation,
List< SqlNode >  orderExprList,
SqlNode  offset,
SqlNode  fetch 
)
inlineprotected

Converts a query's ORDER BY clause, if any.

Ignores the ORDER BY clause if the query is not top-level and FETCH or OFFSET are not present.

Parameters
selectQuery
bbBlackboard
collationCollation list
orderExprListMethod populates this list with orderBy expressions not present in selectList
offsetExpression for number of rows to discard before returning first row
fetchExpression for number of rows to fetch

Definition at line 749 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.convertExpression(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.root, org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.setRoot(), and org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.top.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertSelectImpl().

754  {
755  if (!bb.top || select.getOrderList() == null
756  || select.getOrderList().getList().isEmpty()) {
757  assert !bb.top || collation.getFieldCollations().isEmpty();
758  if ((offset == null
759  || (offset instanceof SqlLiteral
760  && ((SqlLiteral) offset)
761  .bigDecimalValue()
762  .equals(BigDecimal.ZERO)))
763  && fetch == null) {
764  return;
765  }
766  }
767 
768  // Create a sorter using the previously constructed collations.
769  bb.setRoot(LogicalSort.create(bb.root,
770  collation,
771  offset == null ? null : convertExpression(offset),
772  fetch == null ? null : convertExpression(fetch)),
773  false);
774 
775  // If extra expressions were added to the project list for sorting,
776  // add another project to remove them. But make the collation empty, because
777  // we can't represent the real collation.
778  //
779  // If it is the top node, use the real collation, but don't trim fields.
780  if (orderExprList.size() > 0 && !bb.top) {
781  final List<RexNode> exprs = new ArrayList<>();
782  final RelDataType rowType = bb.root.getRowType();
783  final int fieldCount = rowType.getFieldCount() - orderExprList.size();
784  for (int i = 0; i < fieldCount; i++) {
785  exprs.add(rexBuilder.makeInputRef(bb.root, i));
786  }
787  bb.setRoot(LogicalProject.create(
788  bb.root, exprs, rowType.getFieldNames().subList(0, fieldCount)),
789  false);
790  }
791  }
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertOrderItem()

RelFieldCollation org.apache.calcite.sql2rel.SqlToRelConverter.convertOrderItem ( SqlSelect  select,
SqlNode  orderItem,
List< SqlNode >  extraExprs,
RelFieldCollation.Direction  direction,
RelFieldCollation.NullDirection  nullDirection 
)
inlineprotected

Definition at line 2880 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.desc().

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.gatherOrderExprs().

2884  {
2885  assert select != null;
2886  // Handle DESC keyword, e.g. 'select a, b from t order by a desc'.
2887  switch (orderItem.getKind()) {
2888  case DESCENDING:
2889  return convertOrderItem(select,
2890  ((SqlCall) orderItem).operand(0),
2891  extraExprs,
2892  RelFieldCollation.Direction.DESCENDING,
2893  nullDirection);
2894  case NULLS_FIRST:
2895  return convertOrderItem(select,
2896  ((SqlCall) orderItem).operand(0),
2897  extraExprs,
2898  direction,
2899  RelFieldCollation.NullDirection.FIRST);
2900  case NULLS_LAST:
2901  return convertOrderItem(select,
2902  ((SqlCall) orderItem).operand(0),
2903  extraExprs,
2904  direction,
2905  RelFieldCollation.NullDirection.LAST);
2906  }
2907 
2908  SqlNode converted = validator.expandOrderExpr(select, orderItem);
2909 
2910  switch (nullDirection) {
2911  case UNSPECIFIED:
2912  nullDirection = validator.getDefaultNullCollation().last(desc(direction))
2913  ? RelFieldCollation.NullDirection.LAST
2914  : RelFieldCollation.NullDirection.FIRST;
2915  }
2916 
2917  // Scan the select list and order exprs for an identical expression.
2918  final SelectScope selectScope = validator.getRawSelectScope(select);
2919  int ordinal = -1;
2920  for (SqlNode selectItem : selectScope.getExpandedSelectList()) {
2921  ++ordinal;
2922  if (converted.equalsDeep(stripAs(selectItem), Litmus.IGNORE)) {
2923  return new RelFieldCollation(ordinal, direction, nullDirection);
2924  }
2925  }
2926 
2927  for (SqlNode extraExpr : extraExprs) {
2928  ++ordinal;
2929  if (converted.equalsDeep(extraExpr, Litmus.IGNORE)) {
2930  return new RelFieldCollation(ordinal, direction, nullDirection);
2931  }
2932  }
2933 
2934  // TODO: handle collation sequence
2935  // TODO: flag expressions as non-standard
2936 
2937  extraExprs.add(converted);
2938  return new RelFieldCollation(ordinal + 1, direction, nullDirection);
2939  }
static boolean desc(RelFieldCollation.Direction direction)
RelFieldCollation convertOrderItem(SqlSelect select, SqlNode orderItem, List< SqlNode > extraExprs, RelFieldCollation.Direction direction, RelFieldCollation.NullDirection nullDirection)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertOver()

RexNode org.apache.calcite.sql2rel.SqlToRelConverter.convertOver ( Blackboard  bb,
SqlNode  node 
)
inlineprivate

Definition at line 1761 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.convertExpression(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.convertSortExpression(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.scope, and org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.window.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.convertExpression().

1761  {
1762  SqlCall call = (SqlCall) node;
1763  SqlCall aggCall = call.operand(0);
1764  boolean ignoreNulls = false;
1765  switch (aggCall.getKind()) {
1766  case IGNORE_NULLS:
1767  ignoreNulls = true;
1768  // fall through
1769  case RESPECT_NULLS:
1770  aggCall = aggCall.operand(0);
1771  }
1772 
1773  SqlNode windowOrRef = call.operand(1);
1774  final SqlWindow window = validator.resolveWindow(windowOrRef, bb.scope, true);
1775 
1776  // ROW_NUMBER() expects specific kind of framing.
1777  if (aggCall.getKind() == SqlKind.ROW_NUMBER) {
1778  window.setLowerBound(SqlWindow.createUnboundedPreceding(SqlParserPos.ZERO));
1779  window.setUpperBound(SqlWindow.createCurrentRow(SqlParserPos.ZERO));
1780  window.setRows(SqlLiteral.createBoolean(true, SqlParserPos.ZERO));
1781  }
1782  final SqlNodeList partitionList = window.getPartitionList();
1783  final ImmutableList.Builder<RexNode> partitionKeys = ImmutableList.builder();
1784  for (SqlNode partition : partitionList) {
1785  partitionKeys.add(bb.convertExpression(partition));
1786  }
1787  RexNode lowerBound = bb.convertExpression(window.getLowerBound());
1788  RexNode upperBound = bb.convertExpression(window.getUpperBound());
1789  SqlNodeList orderList = window.getOrderList();
1790  if ((orderList.size() == 0) && !window.isRows()) {
1791  // A logical range requires an ORDER BY clause. Use the implicit
1792  // ordering of this relation. There must be one, otherwise it would
1793  // have failed validation.
1794  orderList = bb.scope.getOrderList();
1795  if (orderList == null) {
1796  throw new AssertionError("Relation should have sort key for implicit ORDER BY");
1797  }
1798  }
1799 
1800  final ImmutableList.Builder<RexFieldCollation> orderKeys = ImmutableList.builder();
1801  for (SqlNode order : orderList) {
1802  orderKeys.add(bb.convertSortExpression(order,
1803  RelFieldCollation.Direction.ASCENDING,
1804  RelFieldCollation.NullDirection.UNSPECIFIED));
1805  }
1806 
1807  try {
1808  Preconditions.checkArgument(bb.window == null, "already in window agg mode");
1809  bb.window = window;
1810  RexNode rexAgg = exprConverter.convertCall(bb, aggCall);
1811  rexAgg = rexBuilder.ensureType(validator.getValidatedNodeType(call), rexAgg, false);
1812 
1813  // Walk over the tree and apply 'over' to all agg functions. This is
1814  // necessary because the returned expression is not necessarily a call
1815  // to an agg function. For example, AVG(x) becomes SUM(x) / COUNT(x).
1816 
1817  final SqlLiteral q = aggCall.getFunctionQuantifier();
1818  final boolean isDistinct = q != null && q.getValue() == SqlSelectKeyword.DISTINCT;
1819 
1820  final RexShuttle visitor = new HistogramShuttle(partitionKeys.build(),
1821  orderKeys.build(),
1822  RexWindowBound.create(window.getLowerBound(), lowerBound),
1823  RexWindowBound.create(window.getUpperBound(), upperBound),
1824  window,
1825  isDistinct,
1826  ignoreNulls);
1827  RexNode overNode = rexAgg.accept(visitor);
1828 
1829  return overNode;
1830  } finally {
1831  bb.window = null;
1832  }
1833  }
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertQuery()

RelRoot org.apache.calcite.sql2rel.SqlToRelConverter.convertQuery ( SqlNode  query,
final boolean  needsValidation,
final boolean  top 
)
inline

Converts an unvalidated query's parse tree into a relational expression.

Parameters
queryQuery to convert
needsValidationWhether to validate the query before converting; false if the query has already been validated.
topWhether the query is top-level, say if its result will become a JDBC result set; false if the query will be part of a view.

Definition at line 546 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.checkConvertedType(), org.apache.calcite.sql2rel.SqlToRelConverter.convertQueryRecursive(), org.apache.calcite.sql2rel.SqlToRelConverter.isOrdered(), org.apache.calcite.sql2rel.SqlToRelConverter.isStream(), org.apache.calcite.sql2rel.SqlToRelConverter.requiredCollation(), and run-benchmark-import.result.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertCollectionTable(), org.apache.calcite.sql2rel.SqlToRelConverter.convertCursor(), org.apache.calcite.sql2rel.SqlToRelConverter.convertMultisets(), and org.apache.calcite.sql2rel.SqlToRelConverter.convertWith().

547  {
548  if (needsValidation) {
549  query = validator.validate(query);
550  }
551 
552  RelMetadataQuery.THREAD_PROVIDERS.set(
553  JaninoRelMetadataProvider.of(cluster.getMetadataProvider()));
554  RelNode result = convertQueryRecursive(query, top, null).rel;
555  if (top) {
556  if (isStream(query)) {
557  result = new LogicalDelta(cluster, result.getTraitSet(), result);
558  }
559  }
560  RelCollation collation = RelCollations.EMPTY;
561  if (!query.isA(SqlKind.DML)) {
562  if (isOrdered(query)) {
563  collation = requiredCollation(result);
564  }
565  }
566  checkConvertedType(query, result);
567 
568  if (SQL2REL_LOGGER.isDebugEnabled()) {
569  SQL2REL_LOGGER.debug(RelOptUtil.dumpPlan("Plan after converting SqlNode to RelNode",
570  result,
571  SqlExplainFormat.TEXT,
572  SqlExplainLevel.EXPPLAN_ATTRIBUTES));
573  }
574 
575  final RelDataType validatedRowType = validator.getValidatedNodeType(query);
576  return RelRoot.of(result, validatedRowType, query.getKind()).withCollation(collation);
577  }
void checkConvertedType(SqlNode query, RelNode result)
RelRoot convertQueryRecursive(SqlNode query, boolean top, RelDataType targetRowType)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertQueryOrInList()

RelNode org.apache.calcite.sql2rel.SqlToRelConverter.convertQueryOrInList ( Blackboard  bb,
SqlNode  seek,
RelDataType  targetRowType 
)
inlineprivate

Definition at line 1468 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.convertQueryRecursive(), and org.apache.calcite.sql2rel.SqlToRelConverter.convertRowValues().

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertExists(), org.apache.calcite.sql2rel.SqlToRelConverter.convertMultisets(), and org.apache.calcite.sql2rel.SqlToRelConverter.substituteSubQuery().

1469  {
1470  // NOTE: Once we start accepting single-row queries as row constructors,
1471  // there will be an ambiguity here for a case like X IN ((SELECT Y FROM
1472  // Z)). The SQL standard resolves the ambiguity by saying that a lone
1473  // select should be interpreted as a table expression, not a row
1474  // expression. The semantic difference is that a table expression can
1475  // return multiple rows.
1476  if (seek instanceof SqlNodeList) {
1477  return convertRowValues(
1478  bb, seek, ((SqlNodeList) seek).getList(), false, targetRowType);
1479  } else {
1480  return convertQueryRecursive(seek, false, null).project();
1481  }
1482  }
RelNode convertRowValues(Blackboard bb, SqlNode rowList, Collection< SqlNode > rows, boolean allowLiteralsOnly, RelDataType targetRowType)
RelRoot convertQueryRecursive(SqlNode query, boolean top, RelDataType targetRowType)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertQueryRecursive()

RelRoot org.apache.calcite.sql2rel.SqlToRelConverter.convertQueryRecursive ( SqlNode  query,
boolean  top,
RelDataType  targetRowType 
)
inlineprotected

Recursively converts a query to a relational expression.

Parameters
queryQuery
topWhether this query is the top-level query of the statement
targetRowTypeTarget row type, or null
Returns
Relational expression

Definition at line 2981 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.convertDelete(), org.apache.calcite.sql2rel.SqlToRelConverter.convertInsert(), org.apache.calcite.sql2rel.SqlToRelConverter.convertMerge(), org.apache.calcite.sql2rel.SqlToRelConverter.convertSelect(), org.apache.calcite.sql2rel.SqlToRelConverter.convertSetOp(), org.apache.calcite.sql2rel.SqlToRelConverter.convertUpdate(), org.apache.calcite.sql2rel.SqlToRelConverter.convertValues(), and org.apache.calcite.sql2rel.SqlToRelConverter.convertWith().

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.convertExpression(), org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(), org.apache.calcite.sql2rel.SqlToRelConverter.convertInsert(), org.apache.calcite.sql2rel.SqlToRelConverter.convertQuery(), org.apache.calcite.sql2rel.SqlToRelConverter.convertQueryOrInList(), and org.apache.calcite.sql2rel.SqlToRelConverter.convertSetOp().

2982  {
2983  final SqlKind kind = query.getKind();
2984  switch (kind) {
2985  case SELECT:
2986  return RelRoot.of(convertSelect((SqlSelect) query, top), kind);
2987  case INSERT:
2988  return RelRoot.of(convertInsert((SqlInsert) query), kind);
2989  case DELETE:
2990  return RelRoot.of(convertDelete((SqlDelete) query), kind);
2991  case UPDATE:
2992  return RelRoot.of(convertUpdate((SqlUpdate) query), kind);
2993  case MERGE:
2994  return RelRoot.of(convertMerge((SqlMerge) query), kind);
2995  case UNION:
2996  case INTERSECT:
2997  case EXCEPT:
2998  return RelRoot.of(convertSetOp((SqlCall) query), kind);
2999  case WITH:
3000  return convertWith((SqlWith) query, top);
3001  case VALUES:
3002  return RelRoot.of(convertValues((SqlCall) query, targetRowType), kind);
3003  default:
3004  throw new AssertionError("not a query: " + query);
3005  }
3006  }
RelRoot convertWith(SqlWith with, boolean top)
RelNode convertValues(SqlCall values, RelDataType targetRowType)
RelNode convertSelect(SqlSelect select, boolean top)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertRowConstructor()

RelNode org.apache.calcite.sql2rel.SqlToRelConverter.convertRowConstructor ( Blackboard  bb,
SqlCall  rowConstructor 
)
inlineprivate

Converts a row constructor into a relational expression.

Parameters
bbBlackboard
rowConstructorRow constructor expression
Returns
Relational expression which returns a single row.

Definition at line 3577 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.convertMultisets(), and org.apache.calcite.sql2rel.SqlToRelConverter.isRowConstructor().

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertRowValues().

3577  {
3578  Preconditions.checkArgument(isRowConstructor(rowConstructor));
3579  final List<SqlNode> operands = rowConstructor.getOperandList();
3580  return convertMultisets(operands, bb);
3581  }
RelNode convertMultisets(final List< SqlNode > operands, Blackboard bb)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertRowValues()

RelNode org.apache.calcite.sql2rel.SqlToRelConverter.convertRowValues ( Blackboard  bb,
SqlNode  rowList,
Collection< SqlNode >  rows,
boolean  allowLiteralsOnly,
RelDataType  targetRowType 
)
inlineprivate

Definition at line 1484 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.config, org.apache.calcite.sql2rel.SqlToRelConverter.convertLiteralInValuesList(), org.apache.calcite.sql2rel.SqlToRelConverter.convertRowConstructor(), and org.apache.calcite.sql2rel.SqlToRelConverter.isRowConstructor().

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertQueryOrInList(), and org.apache.calcite.sql2rel.SqlToRelConverter.convertValuesImpl().

1488  {
1489  // NOTE jvs 30-Apr-2006: We combine all rows consisting entirely of
1490  // literals into a single LogicalValues; this gives the optimizer a smaller
1491  // input tree. For everything else (computed expressions, row
1492  // sub-queries), we union each row in as a projection on top of a
1493  // LogicalOneRow.
1494 
1495  final ImmutableList.Builder<ImmutableList<RexLiteral>> tupleList =
1496  ImmutableList.builder();
1497  final RelDataType rowType;
1498  if (targetRowType != null) {
1499  rowType = targetRowType;
1500  } else {
1501  rowType = SqlTypeUtil.promoteToRowType(
1502  typeFactory, validator.getValidatedNodeType(rowList), null);
1503  }
1504 
1505  final List<RelNode> unionInputs = new ArrayList<>();
1506  for (SqlNode node : rows) {
1507  SqlBasicCall call;
1508  if (isRowConstructor(node)) {
1509  call = (SqlBasicCall) node;
1510  ImmutableList.Builder<RexLiteral> tuple = ImmutableList.builder();
1511  for (Ord<SqlNode> operand : Ord.zip(call.operands)) {
1512  RexLiteral rexLiteral =
1513  convertLiteralInValuesList(operand.e, bb, rowType, operand.i);
1514  if ((rexLiteral == null) && allowLiteralsOnly) {
1515  return null;
1516  }
1517  if ((rexLiteral == null) || !config.isCreateValuesRel()) {
1518  // fallback to convertRowConstructor
1519  tuple = null;
1520  break;
1521  }
1522  tuple.add(rexLiteral);
1523  }
1524  if (tuple != null) {
1525  tupleList.add(tuple.build());
1526  continue;
1527  }
1528  } else {
1529  RexLiteral rexLiteral = convertLiteralInValuesList(node, bb, rowType, 0);
1530  if ((rexLiteral != null) && config.isCreateValuesRel()) {
1531  tupleList.add(ImmutableList.of(rexLiteral));
1532  continue;
1533  } else {
1534  if ((rexLiteral == null) && allowLiteralsOnly) {
1535  return null;
1536  }
1537  }
1538 
1539  // convert "1" to "row(1)"
1540  call = (SqlBasicCall) SqlStdOperatorTable.ROW.createCall(SqlParserPos.ZERO, node);
1541  }
1542  unionInputs.add(convertRowConstructor(bb, call));
1543  }
1544  LogicalValues values = LogicalValues.create(cluster, rowType, tupleList.build());
1545  RelNode resultRel;
1546  if (unionInputs.isEmpty()) {
1547  resultRel = values;
1548  } else {
1549  if (!values.getTuples().isEmpty()) {
1550  unionInputs.add(values);
1551  }
1552  resultRel = LogicalUnion.create(unionInputs, true);
1553  }
1554  leaves.add(resultRel);
1555  return resultRel;
1556  }
RelNode convertRowConstructor(Blackboard bb, SqlCall rowConstructor)
RexLiteral convertLiteralInValuesList(SqlNode sqlNode, Blackboard bb, RelDataType rowType, int iField)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertSelect()

RelNode org.apache.calcite.sql2rel.SqlToRelConverter.convertSelect ( SqlSelect  select,
boolean  top 
)
inline

Converts a SELECT statement's parse tree into a relational expression.

Definition at line 614 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.convertSelectImpl(), org.apache.calcite.sql2rel.SqlToRelConverter.createBlackboard(), and org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.root.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertDelete(), org.apache.calcite.sql2rel.SqlToRelConverter.convertMerge(), and org.apache.calcite.sql2rel.SqlToRelConverter.convertQueryRecursive().

614  {
615  final SqlValidatorScope selectScope = validator.getWhereScope(select);
616  final Blackboard bb = createBlackboard(selectScope, null, top);
617  convertSelectImpl(bb, select);
618  return bb.root;
619  }
void convertSelectImpl(final Blackboard bb, SqlSelect select)
Blackboard createBlackboard(SqlValidatorScope scope, Map< String, RexNode > nameToNodeMap, boolean top)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertSelectImpl()

void org.apache.calcite.sql2rel.SqlToRelConverter.convertSelectImpl ( final Blackboard  bb,
SqlSelect  select 
)
inlineprotected

Implementation of convertSelect(SqlSelect, boolean); derived class may override.

Definition at line 633 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.convertAgg(), org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(), org.apache.calcite.sql2rel.SqlToRelConverter.convertOrder(), org.apache.calcite.sql2rel.SqlToRelConverter.convertSelectList(), org.apache.calcite.sql2rel.SqlToRelConverter.convertWhere(), org.apache.calcite.sql2rel.SqlToRelConverter.distinctify(), org.apache.calcite.sql2rel.SqlToRelConverter.gatherOrderExprs(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.root, and org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.setRoot().

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertSelect(), and org.apache.calcite.sql2rel.SqlToRelConverter.convertUpdate().

633  {
634  convertFrom(bb, select.getFrom());
635  convertWhere(bb, select.getWhere());
636 
637  final List<SqlNode> orderExprList = new ArrayList<>();
638  final List<RelFieldCollation> collationList = new ArrayList<>();
639  gatherOrderExprs(bb, select, select.getOrderList(), orderExprList, collationList);
640  final RelCollation collation =
641  cluster.traitSet().canonize(RelCollations.of(collationList));
642 
643  if (validator.isAggregate(select)) {
644  convertAgg(bb, select, orderExprList);
645  } else {
646  convertSelectList(bb, select, orderExprList);
647  }
648 
649  if (select.isDistinct()) {
650  distinctify(bb, true);
651  }
652  convertOrder(
653  select, bb, collation, orderExprList, select.getOffset(), select.getFetch());
654  bb.setRoot(bb.root, true);
655  }
void convertFrom(Blackboard bb, SqlNode from)
void distinctify(Blackboard bb, boolean checkForDupExprs)
void convertAgg(Blackboard bb, SqlSelect select, List< SqlNode > orderExprList)
void gatherOrderExprs(Blackboard bb, SqlSelect select, SqlNodeList orderList, List< SqlNode > extraOrderExprs, List< RelFieldCollation > collationList)
void convertWhere(final Blackboard bb, final SqlNode where)
void convertOrder(SqlSelect select, Blackboard bb, RelCollation collation, List< SqlNode > orderExprList, SqlNode offset, SqlNode fetch)
void convertSelectList(Blackboard bb, SqlSelect select, List< SqlNode > orderList)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertSelectList()

void org.apache.calcite.sql2rel.SqlToRelConverter.convertSelectList ( Blackboard  bb,
SqlSelect  select,
List< SqlNode >  orderList 
)
inlineprivate

Definition at line 3695 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.catalogReader, org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.columnMonotonicities, org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.convertExpression(), org.apache.calcite.sql2rel.SqlToRelConverter.deriveAlias(), org.apache.calcite.sql2rel.SqlToRelConverter.extraSelectItems(), org.apache.calcite.sql2rel.SqlToRelConverter.relBuilder, org.apache.calcite.sql2rel.SqlToRelConverter.replaceSubQueries(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.root, org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.scope, org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.setRoot(), and org.apache.calcite.sql2rel.SqlToRelConverter.validator.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertSelectImpl().

3696  {
3697  SqlNodeList selectList = select.getSelectList();
3698  selectList = validator.expandStar(selectList, select, false);
3699 
3700  replaceSubQueries(bb, selectList, RelOptUtil.Logic.TRUE_FALSE_UNKNOWN);
3701 
3702  List<String> fieldNames = new ArrayList<>();
3703  final List<RexNode> exprs = new ArrayList<>();
3704  final Collection<String> aliases = new TreeSet<>();
3705 
3706  // Project any system fields. (Must be done before regular select items,
3707  // because offsets may be affected.)
3708  final List<SqlMonotonicity> columnMonotonicityList = new ArrayList<>();
3709  extraSelectItems(bb, select, exprs, fieldNames, aliases, columnMonotonicityList);
3710 
3711  // Project select clause.
3712  int i = -1;
3713  for (SqlNode expr : selectList) {
3714  ++i;
3715  exprs.add(bb.convertExpression(expr));
3716  fieldNames.add(deriveAlias(expr, aliases, i));
3717  }
3718 
3719  // Project extra fields for sorting.
3720  for (SqlNode expr : orderList) {
3721  ++i;
3722  SqlNode expr2 = validator.expandOrderExpr(select, expr);
3723  exprs.add(bb.convertExpression(expr2));
3724  fieldNames.add(deriveAlias(expr, aliases, i));
3725  }
3726 
3727  fieldNames = SqlValidatorUtil.uniquify(
3728  fieldNames, catalogReader.nameMatcher().isCaseSensitive());
3729 
3730  relBuilder.push(bb.root).projectNamed(exprs, fieldNames, true);
3731  bb.setRoot(relBuilder.build(), false);
3732 
3733  assert bb.columnMonotonicities.isEmpty();
3734  bb.columnMonotonicities.addAll(columnMonotonicityList);
3735  for (SqlNode selectItem : selectList) {
3736  bb.columnMonotonicities.add(selectItem.getMonotonicity(bb.scope));
3737  }
3738  }
void extraSelectItems(Blackboard bb, SqlSelect select, List< RexNode > exprList, List< String > nameList, Collection< String > aliasList, List< SqlMonotonicity > columnMonotonicityList)
String deriveAlias(final SqlNode node, Collection< String > aliases, final int ordinal)
void replaceSubQueries(final Blackboard bb, final SqlNode expr, RelOptUtil.Logic logic)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertSetOp()

RelNode org.apache.calcite.sql2rel.SqlToRelConverter.convertSetOp ( SqlCall  call)
inlineprotected

Converts a set operation (UNION, INTERSECT, MINUS) into relational expressions.

Parameters
callCall to set operator
Returns
Relational expression

Definition at line 3015 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.all(), and org.apache.calcite.sql2rel.SqlToRelConverter.convertQueryRecursive().

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertQueryRecursive().

3015  {
3016  final RelNode left = convertQueryRecursive(call.operand(0), false, null).project();
3017  final RelNode right = convertQueryRecursive(call.operand(1), false, null).project();
3018  switch (call.getKind()) {
3019  case UNION:
3020  return LogicalUnion.create(ImmutableList.of(left, right), all(call));
3021 
3022  case INTERSECT:
3023  return LogicalIntersect.create(ImmutableList.of(left, right), all(call));
3024 
3025  case EXCEPT:
3026  return LogicalMinus.create(ImmutableList.of(left, right), all(call));
3027 
3028  default:
3029  throw Util.unexpected(call.getKind());
3030  }
3031  }
RelRoot convertQueryRecursive(SqlNode query, boolean top, RelDataType targetRowType)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertToSingleValueSubq()

RelNode org.apache.calcite.sql2rel.SqlToRelConverter.convertToSingleValueSubq ( SqlNode  query,
RelNode  plan 
)
inline

Converts the RelNode tree for a select statement to a select that produces a single value.

Parameters
querythe query
planthe original RelNode tree corresponding to the statement
Returns
the converted RelNode tree

Definition at line 1312 of file SqlToRelConverter.java.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.substituteSubQuery().

1312  {
1313  // Check whether query is guaranteed to produce a single value.
1314  if (query instanceof SqlSelect) {
1315  SqlSelect select = (SqlSelect) query;
1316  SqlNodeList selectList = select.getSelectList();
1317  SqlNodeList groupList = select.getGroup();
1318 
1319  if ((selectList.size() == 1) && ((groupList == null) || (groupList.size() == 0))) {
1320  SqlNode selectExpr = selectList.get(0);
1321  if (selectExpr instanceof SqlCall) {
1322  SqlCall selectExprCall = (SqlCall) selectExpr;
1323  if (Util.isSingleValue(selectExprCall)) {
1324  return plan;
1325  }
1326  }
1327 
1328  // If there is a limit with 0 or 1,
1329  // it is ensured to produce a single value
1330  if (select.getFetch() != null && select.getFetch() instanceof SqlNumericLiteral) {
1331  SqlNumericLiteral limitNum = (SqlNumericLiteral) select.getFetch();
1332  if (((BigDecimal) limitNum.getValue()).intValue() < 2) {
1333  return plan;
1334  }
1335  }
1336  }
1337  } else if (query instanceof SqlCall) {
1338  // If the query is (values ...),
1339  // it is necessary to look into the operands to determine
1340  // whether SingleValueAgg is necessary
1341  SqlCall exprCall = (SqlCall) query;
1342  if (exprCall.getOperator() instanceof SqlValuesOperator
1343  && Util.isSingleValue(exprCall)) {
1344  return plan;
1345  }
1346  }
1347 
1348  // If not, project SingleValueAgg
1349  return RelOptUtil.createSingleValueAggRel(cluster, plan);
1350  }
+ Here is the caller graph for this function:

◆ convertUpdate()

RelNode org.apache.calcite.sql2rel.SqlToRelConverter.convertUpdate ( SqlUpdate  call)
inlineprivate

Definition at line 3383 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.catalogReader, org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.convertExpression(), org.apache.calcite.sql2rel.SqlToRelConverter.convertSelectImpl(), org.apache.calcite.sql2rel.SqlToRelConverter.createBlackboard(), field(), org.apache.calcite.sql2rel.SqlToRelConverter.getTargetTable(), org.apache.calcite.sql2rel.SqlToRelConverter.replaceSubQueries(), and org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.root.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertQueryRecursive().

3383  {
3384  final SqlValidatorScope scope = validator.getWhereScope(call.getSourceSelect());
3385  Blackboard bb = createBlackboard(scope, null, false);
3386 
3387  Builder<RexNode> rexNodeSourceExpressionListBuilder = ImmutableList.builder();
3388  for (SqlNode n : call.getSourceExpressionList()) {
3389  replaceSubQueries(bb, n, RelOptUtil.Logic.UNKNOWN_AS_FALSE);
3390  RexNode rn = bb.convertExpression(n);
3391  rexNodeSourceExpressionListBuilder.add(rn);
3392  }
3393 
3394  RelOptTable targetTable = getTargetTable(call);
3395 
3396  // convert update column list from SqlIdentifier to String
3397  final List<String> targetColumnNameList = new ArrayList<>();
3398  final RelDataType targetRowType = targetTable.getRowType();
3399  for (SqlNode node : call.getTargetColumnList()) {
3400  SqlIdentifier id = (SqlIdentifier) node;
3401  RelDataTypeField field = SqlValidatorUtil.getTargetField(
3402  targetRowType, typeFactory, id, catalogReader, targetTable);
3403  assert field != null : "column " + id.toString() + " not found";
3404  targetColumnNameList.add(field.getName());
3405  }
3406 
3407  convertSelectImpl(bb, call.getSourceSelect());
3408  RelNode sourceRel = bb.root;
3409 
3410  return LogicalTableModify.create(targetTable,
3411  catalogReader,
3412  sourceRel,
3413  LogicalTableModify.Operation.UPDATE,
3414  targetColumnNameList,
3415  rexNodeSourceExpressionListBuilder.build(),
3416  false);
3417  }
const rapidjson::Value & field(const rapidjson::Value &obj, const char field[]) noexcept
Definition: JsonAccessors.h:31
void convertSelectImpl(final Blackboard bb, SqlSelect select)
void replaceSubQueries(final Blackboard bb, final SqlNode expr, RelOptUtil.Logic logic)
Blackboard createBlackboard(SqlValidatorScope scope, Map< String, RexNode > nameToNodeMap, boolean top)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertUsing()

RexNode org.apache.calcite.sql2rel.SqlToRelConverter.convertUsing ( SqlValidatorNamespace  leftNamespace,
SqlValidatorNamespace  rightNamespace,
List< String >  nameList 
)
inlineprivate

Returns an expression for matching columns of a USING clause or inferred from NATURAL JOIN. "a JOIN b USING (x, y)" becomes "a.x = b.x AND a.y = b.y". Returns null if the column list is empty.

Parameters
leftNamespaceNamespace of left input to join
rightNamespaceNamespace of right input to join
nameListList of column names to join on
Returns
Expression to match columns from name list, or true if name list is empty

Definition at line 2567 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.catalogReader, field(), and Experimental.String.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(), and org.apache.calcite.sql2rel.SqlToRelConverter.convertJoinCondition().

2569  {
2570  final SqlNameMatcher nameMatcher = catalogReader.nameMatcher();
2571  final List<RexNode> list = new ArrayList<>();
2572  for (String name : nameList) {
2573  List<RexNode> operands = new ArrayList<>();
2574  int offset = 0;
2575  for (SqlValidatorNamespace n : ImmutableList.of(leftNamespace, rightNamespace)) {
2576  final RelDataType rowType = n.getRowType();
2577  final RelDataTypeField field = nameMatcher.field(rowType, name);
2578  operands.add(rexBuilder.makeInputRef(field.getType(), offset + field.getIndex()));
2579  offset += rowType.getFieldList().size();
2580  }
2581  list.add(rexBuilder.makeCall(SqlStdOperatorTable.EQUALS, operands));
2582  }
2583  return RexUtil.composeConjunction(rexBuilder, list);
2584  }
const rapidjson::Value & field(const rapidjson::Value &obj, const char field[]) noexcept
Definition: JsonAccessors.h:31
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertValues()

RelNode org.apache.calcite.sql2rel.SqlToRelConverter.convertValues ( SqlCall  values,
RelDataType  targetRowType 
)
inline

Converts a SELECT statement's parse tree into a relational expression.

Definition at line 3786 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.convertValuesImpl(), org.apache.calcite.sql2rel.SqlToRelConverter.createBlackboard(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.root, and org.apache.calcite.sql2rel.SqlToRelConverter.validator.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertQueryRecursive().

3786  {
3787  final SqlValidatorScope scope = validator.getOverScope(values);
3788  assert scope != null;
3789  final Blackboard bb = createBlackboard(scope, null, false);
3790  convertValuesImpl(bb, values, targetRowType);
3791  return bb.root;
3792  }
void convertValuesImpl(Blackboard bb, SqlCall values, RelDataType targetRowType)
Blackboard createBlackboard(SqlValidatorScope scope, Map< String, RexNode > nameToNodeMap, boolean top)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertValuesImpl()

void org.apache.calcite.sql2rel.SqlToRelConverter.convertValuesImpl ( Blackboard  bb,
SqlCall  values,
RelDataType  targetRowType 
)
inlineprivate

Converts a values clause (as in "INSERT INTO T(x,y) VALUES (1,2)") into a relational expression.

Parameters
bbBlackboard
valuesCall to SQL VALUES operator
targetRowTypeTarget row type

Definition at line 3802 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.cluster, org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.convertExpression(), org.apache.calcite.sql2rel.SqlToRelConverter.convertRowValues(), org.apache.calcite.sql2rel.SqlToRelConverter.createBlackboard(), org.apache.calcite.sql2rel.SqlToRelConverter.relBuilder, org.apache.calcite.sql2rel.SqlToRelConverter.replaceSubQueries(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.root, org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.scope, org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.setRoot(), and org.apache.calcite.sql2rel.SqlToRelConverter.validator.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(), and org.apache.calcite.sql2rel.SqlToRelConverter.convertValues().

3803  {
3804  // Attempt direct conversion to LogicalValues; if that fails, deal with
3805  // fancy stuff like sub-queries below.
3806  RelNode valuesRel =
3807  convertRowValues(bb, values, values.getOperandList(), true, targetRowType);
3808  if (valuesRel != null) {
3809  bb.setRoot(valuesRel, true);
3810  return;
3811  }
3812 
3813  final List<RelNode> unionRels = new ArrayList<>();
3814  for (SqlNode rowConstructor1 : values.getOperandList()) {
3815  SqlCall rowConstructor = (SqlCall) rowConstructor1;
3816  Blackboard tmpBb = createBlackboard(bb.scope, null, false);
3817  replaceSubQueries(tmpBb, rowConstructor, RelOptUtil.Logic.TRUE_FALSE_UNKNOWN);
3818  final List<Pair<RexNode, String>> exps = new ArrayList<>();
3819  for (Ord<SqlNode> operand : Ord.zip(rowConstructor.getOperandList())) {
3820  exps.add(Pair.of(tmpBb.convertExpression(operand.e),
3821  validator.deriveAlias(operand.e, operand.i)));
3822  }
3823  RelNode in =
3824  (null == tmpBb.root) ? LogicalValues.createOneRow(cluster) : tmpBb.root;
3825  unionRels.add(
3826  relBuilder.push(in).project(Pair.left(exps), Pair.right(exps)).build());
3827  }
3828 
3829  if (unionRels.size() == 0) {
3830  throw new AssertionError("empty values clause");
3831  } else if (unionRels.size() == 1) {
3832  bb.setRoot(unionRels.get(0), true);
3833  } else {
3834  bb.setRoot(LogicalUnion.create(unionRels, true), true);
3835  }
3836  }
RelNode convertRowValues(Blackboard bb, SqlNode rowList, Collection< SqlNode > rows, boolean allowLiteralsOnly, RelDataType targetRowType)
void replaceSubQueries(final Blackboard bb, final SqlNode expr, RelOptUtil.Logic logic)
Blackboard createBlackboard(SqlValidatorScope scope, Map< String, RexNode > nameToNodeMap, boolean top)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertWhere()

void org.apache.calcite.sql2rel.SqlToRelConverter.convertWhere ( final Blackboard  bb,
final SqlNode  where 
)
inlineprivate

Converts a WHERE clause.

Parameters
bbBlackboard
whereWHERE clause, may be null

Definition at line 922 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.convertExpression(), org.apache.calcite.sql2rel.SqlToRelConverter.getCorrelationUse(), org.apache.calcite.sql2rel.SqlToRelConverter.CorrelationUse.id, org.apache.calcite.sql2rel.SqlToRelConverter.pushDownNotForIn(), org.apache.calcite.sql2rel.SqlToRelConverter.CorrelationUse.r, org.apache.calcite.sql2rel.SqlToRelConverter.replaceSubQueries(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.root, org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.scope, and org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.setRoot().

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertSelectImpl().

922  {
923  if (where == null) {
924  return;
925  }
926  SqlNode newWhere = pushDownNotForIn(bb.scope, where);
927  replaceSubQueries(bb, newWhere, RelOptUtil.Logic.UNKNOWN_AS_FALSE);
928  final RexNode convertedWhere = bb.convertExpression(newWhere);
929  final RexNode convertedWhere2 =
930  RexUtil.removeNullabilityCast(typeFactory, convertedWhere);
931 
932  // only allocate filter if the condition is not TRUE
933  if (convertedWhere2.isAlwaysTrue()) {
934  return;
935  }
936 
937  final RelFactories.FilterFactory filterFactory = RelFactories.DEFAULT_FILTER_FACTORY;
938  final RelNode filter = filterFactory.createFilter(bb.root, convertedWhere2);
939  final RelNode r;
940  final CorrelationUse p = getCorrelationUse(bb, filter);
941  if (p != null) {
942  assert p.r instanceof Filter;
943  Filter f = (Filter) p.r;
944  r = LogicalFilter.create(f.getInput(), f.getCondition(), ImmutableSet.of(p.id));
945  } else {
946  r = filter;
947  }
948 
949  bb.setRoot(r, false);
950  }
static SqlNode pushDownNotForIn(SqlValidatorScope scope, SqlNode sqlNode)
void replaceSubQueries(final Blackboard bb, final SqlNode expr, RelOptUtil.Logic logic)
CorrelationUse getCorrelationUse(Blackboard bb, final RelNode r0)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ convertWith()

RelRoot org.apache.calcite.sql2rel.SqlToRelConverter.convertWith ( SqlWith  with,
boolean  top 
)
inline

Converts a WITH sub-query into a relational expression.

Definition at line 3779 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.convertQuery().

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertQueryRecursive().

3779  {
3780  return convertQuery(with.body, false, top);
3781  }
RelRoot convertQuery(SqlNode query, final boolean needsValidation, final boolean top)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ createAggImpl()

final void org.apache.calcite.sql2rel.SqlToRelConverter.createAggImpl ( Blackboard  bb,
final AggConverter  aggConverter,
SqlNodeList  selectList,
SqlNodeList  groupList,
SqlNode  having,
List< SqlNode >  orderExprList 
)
inlineprotected

Definition at line 2626 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.AggConverter.addGroupExpr(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.agg, org.apache.calcite.sql2rel.SqlToRelConverter.AggConverter.aggregatingSelectScope, org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.columnMonotonicities, org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.convertExpression(), org.apache.calcite.sql2rel.SqlToRelConverter.createAggregate(), org.apache.calcite.sql2rel.SqlToRelConverter.AggregateFinder.filterList, org.apache.calcite.sql2rel.SqlToRelConverter.AggConverter.getAggCalls(), org.apache.calcite.sql2rel.SqlToRelConverter.AggConverter.getPreExprs(), org.apache.calcite.sql2rel.SqlToRelConverter.AggConverter.inOver, org.apache.calcite.sql2rel.SqlToRelConverter.AggregateFinder.list, org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.mapRootRelToFieldProjection, org.apache.calcite.sql2rel.SqlToRelConverter.AggregateFinder.orderList, org.apache.calcite.sql2rel.SqlToRelConverter.pushDownNotForIn(), org.apache.calcite.sql2rel.SqlToRelConverter.replaceSubQueries(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.root, org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.scope, org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.setRoot(), and Experimental.String.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertAgg().

2631  {
2632  // Find aggregate functions in SELECT and HAVING clause
2633  final AggregateFinder aggregateFinder = new AggregateFinder();
2634  selectList.accept(aggregateFinder);
2635  if (having != null) {
2636  having.accept(aggregateFinder);
2637  }
2638 
2639  // first replace the sub-queries inside the aggregates
2640  // because they will provide input rows to the aggregates.
2641  replaceSubQueries(bb, aggregateFinder.list, RelOptUtil.Logic.TRUE_FALSE_UNKNOWN);
2642 
2643  // also replace sub-queries inside filters in the aggregates
2645  bb, aggregateFinder.filterList, RelOptUtil.Logic.TRUE_FALSE_UNKNOWN);
2646 
2647  // also replace sub-queries inside ordering spec in the aggregates
2648  replaceSubQueries(bb, aggregateFinder.orderList, RelOptUtil.Logic.TRUE_FALSE_UNKNOWN);
2649 
2650  // If group-by clause is missing, pretend that it has zero elements.
2651  if (groupList == null) {
2652  groupList = SqlNodeList.EMPTY;
2653  }
2654 
2655  replaceSubQueries(bb, groupList, RelOptUtil.Logic.TRUE_FALSE_UNKNOWN);
2656 
2657  // register the group exprs
2658 
2659  // build a map to remember the projections from the top scope to the
2660  // output of the current root.
2661  //
2662  // Calcite allows expressions, not just column references in
2663  // group by list. This is not SQL 2003 compliant, but hey.
2664 
2665  final AggregatingSelectScope scope = aggConverter.aggregatingSelectScope;
2666  final AggregatingSelectScope.Resolved r = scope.resolved.get();
2667  for (SqlNode groupExpr : r.groupExprList) {
2668  aggConverter.addGroupExpr(groupExpr);
2669  }
2670 
2671  final RexNode havingExpr;
2672  final List<Pair<RexNode, String>> projects = new ArrayList<>();
2673 
2674  try {
2675  Preconditions.checkArgument(bb.agg == null, "already in agg mode");
2676  bb.agg = aggConverter;
2677 
2678  // convert the select and having expressions, so that the
2679  // agg converter knows which aggregations are required
2680 
2681  selectList.accept(aggConverter);
2682  // Assert we don't have dangling items left in the stack
2683  assert !aggConverter.inOver;
2684  for (SqlNode expr : orderExprList) {
2685  expr.accept(aggConverter);
2686  assert !aggConverter.inOver;
2687  }
2688  if (having != null) {
2689  having.accept(aggConverter);
2690  assert !aggConverter.inOver;
2691  }
2692 
2693  // compute inputs to the aggregator
2694  List<Pair<RexNode, String>> preExprs = aggConverter.getPreExprs();
2695 
2696  if (preExprs.size() == 0) {
2697  // Special case for COUNT(*), where we can end up with no inputs
2698  // at all. The rest of the system doesn't like 0-tuples, so we
2699  // select a dummy constant here.
2700  final RexNode zero = rexBuilder.makeExactLiteral(BigDecimal.ZERO);
2701  preExprs = ImmutableList.of(Pair.of(zero, (String) null));
2702  }
2703 
2704  final RelNode inputRel = bb.root;
2705 
2706  // Project the expressions required by agg and having.
2707  bb.setRoot(relBuilder.push(inputRel)
2708  .projectNamed(Pair.left(preExprs), Pair.right(preExprs), false)
2709  .build(),
2710  false);
2711  bb.mapRootRelToFieldProjection.put(bb.root, r.groupExprProjection);
2712 
2713  // REVIEW jvs 31-Oct-2007: doesn't the declaration of
2714  // monotonicity here assume sort-based aggregation at
2715  // the physical level?
2716 
2717  // Tell bb which of group columns are sorted.
2718  bb.columnMonotonicities.clear();
2719  for (SqlNode groupItem : groupList) {
2720  bb.columnMonotonicities.add(bb.scope.getMonotonicity(groupItem));
2721  }
2722 
2723  // Add the aggregator
2724  bb.setRoot(createAggregate(bb, r.groupSet, r.groupSets, aggConverter.getAggCalls()),
2725  false);
2726 
2727  bb.mapRootRelToFieldProjection.put(bb.root, r.groupExprProjection);
2728 
2729  // Replace sub-queries in having here and modify having to use
2730  // the replaced expressions
2731  if (having != null) {
2732  SqlNode newHaving = pushDownNotForIn(bb.scope, having);
2733  replaceSubQueries(bb, newHaving, RelOptUtil.Logic.UNKNOWN_AS_FALSE);
2734  havingExpr = bb.convertExpression(newHaving);
2735  } else {
2736  havingExpr = relBuilder.literal(true);
2737  }
2738 
2739  // Now convert the other sub-queries in the select list.
2740  // This needs to be done separately from the sub-query inside
2741  // any aggregate in the select list, and after the aggregate rel
2742  // is allocated.
2743  replaceSubQueries(bb, selectList, RelOptUtil.Logic.TRUE_FALSE_UNKNOWN);
2744 
2745  // Now sub-queries in the entire select list have been converted.
2746  // Convert the select expressions to get the final list to be
2747  // projected.
2748  int k = 0;
2749 
2750  // For select expressions, use the field names previously assigned
2751  // by the validator. If we derive afresh, we might generate names
2752  // like "EXPR$2" that don't match the names generated by the
2753  // validator. This is especially the case when there are system
2754  // fields; system fields appear in the relnode's rowtype but do not
2755  // (yet) appear in the validator type.
2756  final SelectScope selectScope = SqlValidatorUtil.getEnclosingSelectScope(bb.scope);
2757  assert selectScope != null;
2758  final SqlValidatorNamespace selectNamespace =
2759  validator.getNamespace(selectScope.getNode());
2760  final List<String> names = selectNamespace.getRowType().getFieldNames();
2761  int sysFieldCount = selectList.size() - names.size();
2762  for (SqlNode expr : selectList) {
2763  projects.add(Pair.of(bb.convertExpression(expr),
2764  k < sysFieldCount ? validator.deriveAlias(expr, k++)
2765  : names.get(k++ - sysFieldCount)));
2766  }
2767 
2768  for (SqlNode expr : orderExprList) {
2769  projects.add(
2770  Pair.of(bb.convertExpression(expr), validator.deriveAlias(expr, k++)));
2771  }
2772  } finally {
2773  bb.agg = null;
2774  }
2775 
2776  // implement HAVING (we have already checked that it is non-trivial)
2777  relBuilder.push(bb.root);
2778  if (havingExpr != null) {
2779  relBuilder.filter(havingExpr);
2780  }
2781 
2782  // implement the SELECT list
2783  relBuilder.project(Pair.left(projects), Pair.right(projects))
2784  .rename(Pair.right(projects));
2785  bb.setRoot(relBuilder.build(), false);
2786 
2787  // Tell bb which of group columns are sorted.
2788  bb.columnMonotonicities.clear();
2789  for (SqlNode selectItem : selectList) {
2790  bb.columnMonotonicities.add(bb.scope.getMonotonicity(selectItem));
2791  }
2792  }
static SqlNode pushDownNotForIn(SqlValidatorScope scope, SqlNode sqlNode)
void replaceSubQueries(final Blackboard bb, final SqlNode expr, RelOptUtil.Logic logic)
RelNode createAggregate(Blackboard bb, ImmutableBitSet groupSet, ImmutableList< ImmutableBitSet > groupSets, List< AggregateCall > aggCalls)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ createAggregate()

RelNode org.apache.calcite.sql2rel.SqlToRelConverter.createAggregate ( Blackboard  bb,
ImmutableBitSet  groupSet,
ImmutableList< ImmutableBitSet >  groupSets,
List< AggregateCall >  aggCalls 
)
inlineprotected

Creates an Aggregate.

In case the aggregate rel changes the order in which it projects fields, the groupExprProjection parameter is provided, and the implementation of this method may modify it.

The sortedCount parameter is the number of expressions known to be monotonic. These expressions must be on the leading edge of the grouping keys. The default implementation of this method ignores this parameter.

Parameters
bbBlackboard
groupSetBit set of ordinals of grouping columns
groupSetsGrouping sets
aggCallsArray of calls to aggregate functions
Returns
LogicalAggregate

Definition at line 2812 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.root.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.createAggImpl(), and org.apache.calcite.sql2rel.SqlToRelConverter.distinctify().

2815  {
2816  return LogicalAggregate.create(bb.root, groupSet, groupSets, aggCalls);
2817  }
+ Here is the caller graph for this function:

◆ createBlackboard()

Blackboard org.apache.calcite.sql2rel.SqlToRelConverter.createBlackboard ( SqlValidatorScope  scope,
Map< String, RexNode >  nameToNodeMap,
boolean  top 
)
inlineprotected

◆ createInsertBlackboard()

Blackboard org.apache.calcite.sql2rel.SqlToRelConverter.createInsertBlackboard ( RelOptTable  targetTable,
RexNode  sourceRef,
List< String >  targetColumnNames 
)
inlineprivate

Creates a blackboard for translating the expressions of generated columns in an INSERT statement.

Definition at line 3253 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.createBlackboard(), and Experimental.String.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.collectInsertTargets(), org.apache.calcite.sql2rel.SqlToRelConverter.convertColumnList(), and org.apache.calcite.sql2rel.SqlToRelConverter.toRel().

3254  {
3255  final Map<String, RexNode> nameToNodeMap = new HashMap<>();
3256  int j = 0;
3257 
3258  // Assign expressions for non-generated columns.
3259  final List<ColumnStrategy> strategies = targetTable.getColumnStrategies();
3260  final List<String> targetFields = targetTable.getRowType().getFieldNames();
3261  for (String targetColumnName : targetColumnNames) {
3262  final int i = targetFields.indexOf(targetColumnName);
3263  switch (strategies.get(i)) {
3264  case STORED:
3265  case VIRTUAL:
3266  break;
3267  default:
3268  nameToNodeMap.put(targetColumnName, rexBuilder.makeFieldAccess(sourceRef, j++));
3269  }
3270  }
3271  return createBlackboard(null, nameToNodeMap, false);
3272  }
Blackboard createBlackboard(SqlValidatorScope scope, Map< String, RexNode > nameToNodeMap, boolean top)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ createJoin()

RelNode org.apache.calcite.sql2rel.SqlToRelConverter.createJoin ( Blackboard  bb,
RelNode  leftRel,
RelNode  rightRel,
RexNode  joinCond,
JoinRelType  joinType 
)
inlineprotected

Definition at line 2324 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.getCorrelationUse(), org.apache.calcite.sql2rel.SqlToRelConverter.CorrelationUse.id, org.apache.calcite.sql2rel.SqlToRelConverter.CorrelationUse.r, org.apache.calcite.sql2rel.SqlToRelConverter.CorrelationUse.requiredColumns, org.apache.calcite.sql2rel.SqlToRelConverter.RexAccessShuttle.RexAccessShuttle(), org.apache.calcite.sql2rel.SqlToRelConverter.RexAccessShuttle.rexCorrel, and org.apache.calcite.sql2rel.SqlToRelConverter.RexAccessShuttle.varCols.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(), and org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.register().

2328  {
2329  assert joinCond != null;
2330 
2331  final CorrelationUse p = getCorrelationUse(bb, rightRel);
2332  if (p != null) {
2333  RelNode innerRel = p.r;
2334  ImmutableBitSet requiredCols = p.requiredColumns;
2335 
2336  if (!joinCond.isAlwaysTrue()) {
2337  final RelFactories.FilterFactory factory = RelFactories.DEFAULT_FILTER_FACTORY;
2338  final RexCorrelVariable rexCorrel =
2339  (RexCorrelVariable) rexBuilder.makeCorrel(leftRel.getRowType(), p.id);
2340  final RexAccessShuttle shuttle = new RexAccessShuttle(rexBuilder, rexCorrel);
2341 
2342  // Replace outer RexInputRef with RexFieldAccess,
2343  // and push lateral join predicate into inner child
2344  final RexNode newCond = joinCond.accept(shuttle);
2345  innerRel = factory.createFilter(p.r, newCond);
2346  requiredCols =
2347  ImmutableBitSet.fromBitSet(shuttle.varCols).union(p.requiredColumns);
2348  }
2349 
2350  LogicalCorrelate corr =
2351  LogicalCorrelate.create(leftRel, innerRel, p.id, requiredCols, joinType);
2352  return corr;
2353  }
2354 
2355  final Join originalJoin = (Join) RelFactories.DEFAULT_JOIN_FACTORY.createJoin(
2356  leftRel, rightRel, joinCond, ImmutableSet.of(), joinType, false);
2357 
2358  return RelOptUtil.pushDownJoinConditions(originalJoin, relBuilder);
2359  }
CorrelationUse getCorrelationUse(Blackboard bb, final RelNode r0)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ createModify()

RelNode org.apache.calcite.sql2rel.SqlToRelConverter.createModify ( RelOptTable  targetTable,
RelNode  source 
)
inlineprivate

Creates a relational expression to modify a table or modifiable view.

Definition at line 3050 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.catalogReader, and org.apache.calcite.sql2rel.SqlToRelConverter.createSource().

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertInsert().

3050  {
3051  final ModifiableTable modifiableTable = targetTable.unwrap(ModifiableTable.class);
3052  if (modifiableTable != null && modifiableTable == targetTable.unwrap(Table.class)) {
3053  return modifiableTable.toModificationRel(cluster,
3054  targetTable,
3055  catalogReader,
3056  source,
3057  LogicalTableModify.Operation.INSERT,
3058  null,
3059  null,
3060  false);
3061  }
3062  final ModifiableView modifiableView = targetTable.unwrap(ModifiableView.class);
3063  if (modifiableView != null) {
3064  final Table delegateTable = modifiableView.getTable();
3065  final RelDataType delegateRowType = delegateTable.getRowType(typeFactory);
3066  final RelOptTable delegateRelOptTable = RelOptTableImpl.create(
3067  null, delegateRowType, delegateTable, modifiableView.getTablePath());
3068  final RelNode newSource =
3069  createSource(targetTable, source, modifiableView, delegateRowType);
3070  return createModify(delegateRelOptTable, newSource);
3071  }
3072  return LogicalTableModify.create(targetTable,
3073  catalogReader,
3074  source,
3075  LogicalTableModify.Operation.INSERT,
3076  null,
3077  null,
3078  false);
3079  }
RelNode createSource(RelOptTable targetTable, RelNode source, ModifiableView modifiableView, RelDataType delegateRowType)
RelNode createModify(RelOptTable targetTable, RelNode source)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ createSource()

RelNode org.apache.calcite.sql2rel.SqlToRelConverter.createSource ( RelOptTable  targetTable,
RelNode  source,
ModifiableView  modifiableView,
RelDataType  delegateRowType 
)
inlineprivate

Wraps a relational expression in the projects and filters implied by a ModifiableView.

The input relational expression is suitable for inserting into the view, and the returned relational expression is suitable for inserting into its delegate table.

In principle, the delegate table of a view might be another modifiable view, and if so, the process can be repeated.

Definition at line 3092 of file SqlToRelConverter.java.

References field().

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.createModify().

3095  {
3096  final ImmutableIntList mapping = modifiableView.getColumnMapping();
3097  assert mapping.size() == targetTable.getRowType().getFieldCount();
3098 
3099  // For columns represented in the mapping, the expression is just a field
3100  // reference.
3101  final Map<Integer, RexNode> projectMap = new HashMap<>();
3102  final List<RexNode> filters = new ArrayList<>();
3103  for (int i = 0; i < mapping.size(); i++) {
3104  int target = mapping.get(i);
3105  if (target >= 0) {
3106  projectMap.put(target, RexInputRef.of(i, source.getRowType()));
3107  }
3108  }
3109 
3110  // For columns that are not in the mapping, and have a constraint of the
3111  // form "column = value", the expression is the literal "value".
3112  //
3113  // If a column has multiple constraints, the extra ones will become a
3114  // filter.
3115  final RexNode constraint = modifiableView.getConstraint(rexBuilder, delegateRowType);
3116  RelOptUtil.inferViewPredicates(projectMap, filters, constraint);
3117  final List<Pair<RexNode, String>> projects = new ArrayList<>();
3118  for (RelDataTypeField field : delegateRowType.getFieldList()) {
3119  RexNode node = projectMap.get(field.getIndex());
3120  if (node == null) {
3121  node = rexBuilder.makeNullLiteral(field.getType());
3122  }
3123  projects.add(Pair.of(
3124  rexBuilder.ensureType(field.getType(), node, false), field.getName()));
3125  }
3126 
3127  return relBuilder.push(source)
3128  .projectNamed(Pair.left(projects), Pair.right(projects), false)
3129  .filter(filters)
3130  .build();
3131  }
const rapidjson::Value & field(const rapidjson::Value &obj, const char field[]) noexcept
Definition: JsonAccessors.h:31
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ createToRelContext()

RelOptTable.ToRelContext org.apache.calcite.sql2rel.SqlToRelConverter.createToRelContext ( )
inlineprivate

Definition at line 3133 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.viewExpander.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.flattenTypes(), and org.apache.calcite.sql2rel.SqlToRelConverter.toRel().

3133  {
3134  return ViewExpanders.toRelContext(viewExpander, cluster);
3135  }
+ Here is the caller graph for this function:

◆ decorrelate()

RelNode org.apache.calcite.sql2rel.SqlToRelConverter.decorrelate ( SqlNode  query,
RelNode  rootRel 
)
inline

If sub-query is correlated and decorrelation is enabled, performs decorrelation.

Parameters
queryQuery
rootRelRoot relational expression
Returns
New root relational expression after decorrelation

Definition at line 473 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.checkConvertedType(), org.apache.calcite.sql2rel.SqlToRelConverter.decorrelateQuery(), org.apache.calcite.sql2rel.SqlToRelConverter.enableDecorrelation(), and run-benchmark-import.result.

473  {
474  if (!enableDecorrelation()) {
475  return rootRel;
476  }
477  final RelNode result = decorrelateQuery(rootRel);
478  if (result != rootRel) {
479  checkConvertedType(query, result);
480  }
481  return result;
482  }
void checkConvertedType(SqlNode query, RelNode result)
+ Here is the call graph for this function:

◆ decorrelateQuery()

RelNode org.apache.calcite.sql2rel.SqlToRelConverter.decorrelateQuery ( RelNode  rootRel)
inlineprotected

Definition at line 2958 of file SqlToRelConverter.java.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.decorrelate().

2958  {
2959  return RelDecorrelator.decorrelateQuery(rootRel, relBuilder);
2960  }
+ Here is the caller graph for this function:

◆ deriveAlias()

String org.apache.calcite.sql2rel.SqlToRelConverter.deriveAlias ( final SqlNode  node,
Collection< String >  aliases,
final int  ordinal 
)
inlineprivate

Definition at line 3760 of file SqlToRelConverter.java.

References Experimental.String, and org.apache.calcite.sql2rel.SqlToRelConverter.validator.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertSelectList().

3761  {
3762  String alias = validator.deriveAlias(node, ordinal);
3763  if ((alias == null) || aliases.contains(alias)) {
3764  String aliasBase = (alias == null) ? "EXPR$" : alias;
3765  for (int j = 0;; j++) {
3766  alias = aliasBase + j;
3767  if (!aliases.contains(alias)) {
3768  break;
3769  }
3770  }
3771  }
3772  aliases.add(alias);
3773  return alias;
3774  }
+ Here is the caller graph for this function:

◆ desc()

static boolean org.apache.calcite.sql2rel.SqlToRelConverter.desc ( RelFieldCollation.Direction  direction)
inlinestaticprivate

Definition at line 2941 of file SqlToRelConverter.java.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertMatchRecognize(), org.apache.calcite.sql2rel.SqlToRelConverter.convertOrderItem(), and org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.convertSortExpression().

2941  {
2942  switch (direction) {
2943  case DESCENDING:
2944  case STRICTLY_DESCENDING:
2945  return true;
2946  default:
2947  return false;
2948  }
2949  }
+ Here is the caller graph for this function:

◆ distinctify()

void org.apache.calcite.sql2rel.SqlToRelConverter.distinctify ( Blackboard  bb,
boolean  checkForDupExprs 
)
inlineprivate

Having translated 'SELECT ... FROM ... [GROUP BY ...] [HAVING ...]', adds a relational expression to make the results unique.

If the SELECT clause contains duplicate expressions, adds org.apache.calcite.rel.logical.LogicalProjects so that we are grouping on the minimal set of keys. The performance gain isn't huge, but it is difficult to detect these duplicate expressions later.

Parameters
bbBlackboard
checkForDupExprsCheck for duplicate expressions

Definition at line 669 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.createAggregate(), field(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.root, and org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.setRoot().

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertSelectImpl().

669  {
670  // Look for duplicate expressions in the project.
671  // Say we have 'select x, y, x, z'.
672  // Then dups will be {[2, 0]}
673  // and oldToNew will be {[0, 0], [1, 1], [2, 0], [3, 2]}
674  RelNode rel = bb.root;
675  if (checkForDupExprs && (rel instanceof LogicalProject)) {
676  LogicalProject project = (LogicalProject) rel;
677  final List<RexNode> projectExprs = project.getProjects();
678  final List<Integer> origins = new ArrayList<>();
679  int dupCount = 0;
680  for (int i = 0; i < projectExprs.size(); i++) {
681  int x = projectExprs.indexOf(projectExprs.get(i));
682  if (x >= 0 && x < i) {
683  origins.add(x);
684  ++dupCount;
685  } else {
686  origins.add(i);
687  }
688  }
689  if (dupCount == 0) {
690  distinctify(bb, false);
691  return;
692  }
693 
694  final Map<Integer, Integer> squished = new HashMap<>();
695  final List<RelDataTypeField> fields = rel.getRowType().getFieldList();
696  final List<Pair<RexNode, String>> newProjects = new ArrayList<>();
697  for (int i = 0; i < fields.size(); i++) {
698  if (origins.get(i) == i) {
699  squished.put(i, newProjects.size());
700  newProjects.add(RexInputRef.of2(i, fields));
701  }
702  }
703  rel = LogicalProject.create(rel, Pair.left(newProjects), Pair.right(newProjects));
704  bb.root = rel;
705  distinctify(bb, false);
706  rel = bb.root;
707 
708  // Create the expressions to reverse the mapping.
709  // Project($0, $1, $0, $2).
710  final List<Pair<RexNode, String>> undoProjects = new ArrayList<>();
711  for (int i = 0; i < fields.size(); i++) {
712  final int origin = origins.get(i);
713  RelDataTypeField field = fields.get(i);
714  undoProjects.add(
715  Pair.of((RexNode) new RexInputRef(squished.get(origin), field.getType()),
716  field.getName()));
717  }
718 
719  rel = LogicalProject.create(rel, Pair.left(undoProjects), Pair.right(undoProjects));
720  bb.setRoot(rel, false);
721 
722  return;
723  }
724 
725  // Usual case: all of the expressions in the SELECT clause are
726  // different.
727  final ImmutableBitSet groupSet =
728  ImmutableBitSet.range(rel.getRowType().getFieldCount());
729  rel = createAggregate(bb, groupSet, ImmutableList.of(groupSet), ImmutableList.of());
730 
731  bb.setRoot(rel, false);
732  }
const rapidjson::Value & field(const rapidjson::Value &obj, const char field[]) noexcept
Definition: JsonAccessors.h:31
void distinctify(Blackboard bb, boolean checkForDupExprs)
RelNode createAggregate(Blackboard bb, ImmutableBitSet groupSet, ImmutableList< ImmutableBitSet > groupSets, List< AggregateCall > aggCalls)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ enableDecorrelation()

boolean org.apache.calcite.sql2rel.SqlToRelConverter.enableDecorrelation ( )
inlineprotected

Definition at line 2952 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.config.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.decorrelate().

2952  {
2953  // disable sub-query decorrelation when needed.
2954  // e.g. if outer joins are not supported.
2955  return config.isDecorrelationEnabled();
2956  }
+ Here is the caller graph for this function:

◆ ensureSqlType()

RexNode org.apache.calcite.sql2rel.SqlToRelConverter.ensureSqlType ( RelDataType  type,
RexNode  node 
)
inlineprivate

Ensures that an expression has a given SqlTypeName, applying a cast if necessary. If the expression already has the right type family, returns the expression unchanged.

Definition at line 1414 of file SqlToRelConverter.java.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertInToOr().

1414  {
1415  if (type.getSqlTypeName() == node.getType().getSqlTypeName()
1416  || (type.getSqlTypeName() == SqlTypeName.VARCHAR
1417  && node.getType().getSqlTypeName() == SqlTypeName.CHAR)) {
1418  return node;
1419  }
1420  return rexBuilder.ensureType(type, node, true);
1421  }
+ Here is the caller graph for this function:

◆ extraSelectItems()

void org.apache.calcite.sql2rel.SqlToRelConverter.extraSelectItems ( Blackboard  bb,
SqlSelect  select,
List< RexNode >  exprList,
List< String >  nameList,
Collection< String >  aliasList,
List< SqlMonotonicity >  columnMonotonicityList 
)
inlineprotected

Adds extra select items. The default implementation adds nothing; derived classes may add columns to exprList, nameList, aliasList and columnMonotonicityList.

Parameters
bbBlackboard
selectSelect statement being translated
exprListList of expressions in select clause
nameListList of names, one per column
aliasListCollection of aliases that have been used already
columnMonotonicityListList of monotonicity, one per column

Definition at line 3753 of file SqlToRelConverter.java.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertSelectList().

3758  {}
+ Here is the caller graph for this function:

◆ findSubQueries()

void org.apache.calcite.sql2rel.SqlToRelConverter.findSubQueries ( Blackboard  bb,
SqlNode  node,
RelOptUtil.Logic  logic,
boolean  registerOnlyScalarSubQueries 
)
inlineprivate

Builds a list of all IN or EXISTS operators inside SQL parse tree. Does not traverse inside queries.

Parameters
bbblackboard
nodethe SQL parse tree
logicWhether the answer needs to be in full 3-valued logic (TRUE, FALSE, UNKNOWN) will be required, or whether we can accept an approximation (say representing UNKNOWN as FALSE)
registerOnlyScalarSubQueriesif set to true and the parse tree corresponds to a variation of a select node, only register it if it's a scalar sub-query

Definition at line 1627 of file SqlToRelConverter.java.

References ALL, and org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.registerSubQuery().

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.replaceSubQueries().

1630  {
1631  final SqlKind kind = node.getKind();
1632  switch (kind) {
1633  case EXISTS:
1634  case SELECT:
1635  case MULTISET_QUERY_CONSTRUCTOR:
1636  case MULTISET_VALUE_CONSTRUCTOR:
1637  case ARRAY_QUERY_CONSTRUCTOR:
1638  case CURSOR:
1639  case SCALAR_QUERY:
1640  if (!registerOnlyScalarSubQueries || (kind == SqlKind.SCALAR_QUERY)) {
1641  bb.registerSubQuery(node, RelOptUtil.Logic.TRUE_FALSE);
1642  }
1643  return;
1644  case IN:
1645  break;
1646  case NOT_IN:
1647  case NOT:
1648  logic = logic.negate();
1649  break;
1650  }
1651  if (node instanceof SqlCall) {
1652  switch (kind) {
1653  // Do no change logic for AND, IN and NOT IN expressions;
1654  // but do change logic for OR, NOT and others;
1655  // EXISTS was handled already.
1656  case AND:
1657  case IN:
1658  case NOT_IN:
1659  break;
1660  default:
1661  logic = RelOptUtil.Logic.TRUE_FALSE_UNKNOWN;
1662  break;
1663  }
1664  for (SqlNode operand : ((SqlCall) node).getOperandList()) {
1665  if (operand != null) {
1666  // In the case of an IN expression, locate scalar
1667  // sub-queries so we can convert them to constants
1668  findSubQueries(bb,
1669  operand,
1670  logic,
1671  kind == SqlKind.IN || kind == SqlKind.NOT_IN || kind == SqlKind.SOME
1672  || kind == SqlKind.ALL || registerOnlyScalarSubQueries);
1673  }
1674  }
1675  } else if (node instanceof SqlNodeList) {
1676  for (SqlNode child : (SqlNodeList) node) {
1677  findSubQueries(bb,
1678  child,
1679  logic,
1680  kind == SqlKind.IN || kind == SqlKind.NOT_IN || kind == SqlKind.SOME
1681  || kind == SqlKind.ALL || registerOnlyScalarSubQueries);
1682  }
1683  }
1684 
1685  // Now that we've located any scalar sub-queries inside the IN
1686  // expression, register the IN expression itself. We need to
1687  // register the scalar sub-queries first so they can be converted
1688  // before the IN expression is converted.
1689  switch (kind) {
1690  case IN:
1691  case NOT_IN:
1692  case SOME:
1693  case ALL:
1694  switch (logic) {
1695  case TRUE_FALSE_UNKNOWN:
1696  if (validator.getValidatedNodeType(node).isNullable()) {
1697  break;
1698  } else if (true) {
1699  break;
1700  }
1701  // fall through
1702  case UNKNOWN_AS_FALSE:
1703  logic = RelOptUtil.Logic.TRUE;
1704  }
1705  bb.registerSubQuery(node, logic);
1706  break;
1707  }
1708  }
const std::vector< std::shared_ptr< TestColumnDescriptor > > ALL
void findSubQueries(Blackboard bb, SqlNode node, RelOptUtil.Logic logic, boolean registerOnlyScalarSubQueries)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ flattenTypes()

RelNode org.apache.calcite.sql2rel.SqlToRelConverter.flattenTypes ( RelNode  rootRel,
boolean  restructure 
)
inline

Definition at line 459 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.createToRelContext().

459  {
460  RelStructuredTypeFlattener typeFlattener = new RelStructuredTypeFlattener(
461  relBuilder, rexBuilder, createToRelContext(), restructure);
462  return typeFlattener.rewrite(rootRel);
463  }
+ Here is the call graph for this function:

◆ gatherOrderExprs()

void org.apache.calcite.sql2rel.SqlToRelConverter.gatherOrderExprs ( Blackboard  bb,
SqlSelect  select,
SqlNodeList  orderList,
List< SqlNode >  extraOrderExprs,
List< RelFieldCollation >  collationList 
)
inlineprotected

Creates a list of collations required to implement the ORDER BY clause, if there is one. Populates extraOrderExprs with any sort expressions which are not in the select clause.

Parameters
bbScope within which to resolve identifiers
selectSelect clause. Never null, because we invent a dummy SELECT if ORDER BY is applied to a set operation (UNION etc.)
orderListOrder by clause, may be null
extraOrderExprsSort expressions which are not in the select clause (output)
collationListList of collations (output)

Definition at line 2847 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.convertOrderItem(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.root, and org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.top.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertSelectImpl().

2851  {
2852  // TODO: add validation rules to SqlValidator also
2853  assert bb.root != null : "precondition: child != null";
2854  assert select != null;
2855  if (orderList == null) {
2856  return;
2857  }
2858 
2859  if (!bb.top) {
2860  SqlNode offset = select.getOffset();
2861  if ((offset == null
2862  || (offset instanceof SqlLiteral
2863  && ((SqlLiteral) offset)
2864  .bigDecimalValue()
2865  .equals(BigDecimal.ZERO)))
2866  && select.getFetch() == null) {
2867  return;
2868  }
2869  }
2870 
2871  for (SqlNode orderItem : orderList) {
2872  collationList.add(convertOrderItem(select,
2873  orderItem,
2874  extraOrderExprs,
2875  RelFieldCollation.Direction.ASCENDING,
2876  RelFieldCollation.NullDirection.UNSPECIFIED));
2877  }
2878  }
RelFieldCollation convertOrderItem(SqlSelect select, SqlNode orderItem, List< SqlNode > extraExprs, RelFieldCollation.Direction direction, RelFieldCollation.NullDirection nullDirection)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ getCluster()

RelOptCluster org.apache.calcite.sql2rel.SqlToRelConverter.getCluster ( )
inline
Returns
the RelOptCluster in use.

Definition at line 334 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.cluster.

334  {
335  return cluster;
336  }

◆ getColumnMappings()

Set<RelColumnMapping> org.apache.calcite.sql2rel.SqlToRelConverter.getColumnMappings ( SqlOperator  op)
inlineprivate

Definition at line 2284 of file SqlToRelConverter.java.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertCollectionTable().

2284  {
2285  SqlReturnTypeInference rti = op.getReturnTypeInference();
2286  if (rti == null) {
2287  return null;
2288  }
2289  if (rti instanceof TableFunctionReturnTypeInference) {
2290  TableFunctionReturnTypeInference tfrti = (TableFunctionReturnTypeInference) rti;
2291  return tfrti.getColumnMappings();
2292  } else {
2293  return null;
2294  }
2295  }
+ Here is the caller graph for this function:

◆ getCorrelationUse()

CorrelationUse org.apache.calcite.sql2rel.SqlToRelConverter.getCorrelationUse ( Blackboard  bb,
final RelNode  r0 
)
inlineprivate

Definition at line 2361 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.DeferredLookup.bb, field(), org.apache.calcite.sql2rel.SqlToRelConverter.DeferredLookup.getFieldAccess(), org.apache.calcite.sql2rel.SqlToRelConverter.DeferredLookup.getOriginalRelName(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.getValidator(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.mapRootRelToFieldProjection, org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.root, org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.scope, and Experimental.String.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertWhere(), and org.apache.calcite.sql2rel.SqlToRelConverter.createJoin().

2361  {
2362  final Set<CorrelationId> correlatedVariables = RelOptUtil.getVariablesUsed(r0);
2363  if (correlatedVariables.isEmpty()) {
2364  return null;
2365  }
2366  final ImmutableBitSet.Builder requiredColumns = ImmutableBitSet.builder();
2367  final List<CorrelationId> correlNames = new ArrayList<>();
2368 
2369  // All correlations must refer the same namespace since correlation
2370  // produces exactly one correlation source.
2371  // The same source might be referenced by different variables since
2372  // DeferredLookups are not de-duplicated at create time.
2373  SqlValidatorNamespace prevNs = null;
2374 
2375  for (CorrelationId correlName : correlatedVariables) {
2376  DeferredLookup lookup = mapCorrelToDeferred.get(correlName);
2377  RexFieldAccess fieldAccess = lookup.getFieldAccess(correlName);
2378  String originalRelName = lookup.getOriginalRelName();
2379  String originalFieldName = fieldAccess.getField().getName();
2380 
2381  final SqlNameMatcher nameMatcher =
2382  bb.getValidator().getCatalogReader().nameMatcher();
2383  final SqlValidatorScope.ResolvedImpl resolved =
2384  new SqlValidatorScope.ResolvedImpl();
2385  lookup.bb.scope.resolve(
2386  ImmutableList.of(originalRelName), nameMatcher, false, resolved);
2387  assert resolved.count() == 1;
2388  final SqlValidatorScope.Resolve resolve = resolved.only();
2389  final SqlValidatorNamespace foundNs = resolve.namespace;
2390  final RelDataType rowType = resolve.rowType();
2391  final int childNamespaceIndex = resolve.path.steps().get(0).i;
2392  final SqlValidatorScope ancestorScope = resolve.scope;
2393  boolean correlInCurrentScope = bb.scope.isWithin(ancestorScope);
2394 
2395  if (!correlInCurrentScope) {
2396  continue;
2397  }
2398 
2399  if (prevNs == null) {
2400  prevNs = foundNs;
2401  } else {
2402  assert prevNs
2403  == foundNs : "All correlation variables should resolve"
2404  + " to the same namespace."
2405  + " Prev ns="
2406  + prevNs
2407  + ", new ns="
2408  + foundNs;
2409  }
2410 
2411  int namespaceOffset = 0;
2412  if (childNamespaceIndex > 0) {
2413  // If not the first child, need to figure out the width
2414  // of output types from all the preceding namespaces
2415  assert ancestorScope instanceof ListScope;
2416  List<SqlValidatorNamespace> children = ((ListScope) ancestorScope).getChildren();
2417 
2418  for (int i = 0; i < childNamespaceIndex; i++) {
2419  SqlValidatorNamespace child = children.get(i);
2420  namespaceOffset += child.getRowType().getFieldCount();
2421  }
2422  }
2423 
2424  RexFieldAccess topLevelFieldAccess = fieldAccess;
2425  while (topLevelFieldAccess.getReferenceExpr() instanceof RexFieldAccess) {
2426  topLevelFieldAccess = (RexFieldAccess) topLevelFieldAccess.getReferenceExpr();
2427  }
2428  final RelDataTypeField field = rowType.getFieldList().get(
2429  topLevelFieldAccess.getField().getIndex() - namespaceOffset);
2430  int pos = namespaceOffset + field.getIndex();
2431 
2432  assert field.getType() == topLevelFieldAccess.getField().getType();
2433 
2434  assert pos != -1;
2435 
2436  if (bb.mapRootRelToFieldProjection.containsKey(bb.root)) {
2437  // bb.root is an aggregate and only projects group by
2438  // keys.
2439  Map<Integer, Integer> exprProjection =
2440  bb.mapRootRelToFieldProjection.get(bb.root);
2441 
2442  // sub-query can reference group by keys projected from
2443  // the root of the outer relation.
2444  if (exprProjection.containsKey(pos)) {
2445  pos = exprProjection.get(pos);
2446  } else {
2447  // correl not grouped
2448  throw new AssertionError("Identifier '" + originalRelName + "."
2449  + originalFieldName + "' is not a group expr");
2450  }
2451  }
2452 
2453  requiredColumns.set(pos);
2454  correlNames.add(correlName);
2455  }
2456 
2457  if (correlNames.isEmpty()) {
2458  // None of the correlating variables originated in this scope.
2459  return null;
2460  }
2461 
2462  RelNode r = r0;
2463  if (correlNames.size() > 1) {
2464  // The same table was referenced more than once.
2465  // So we deduplicate.
2466  r = DeduplicateCorrelateVariables.go(
2467  rexBuilder, correlNames.get(0), Util.skip(correlNames), r0);
2468  // Add new node to leaves.
2469  leaves.add(r);
2470  }
2471  return new CorrelationUse(correlNames.get(0), requiredColumns.build(), r);
2472  }
const rapidjson::Value & field(const rapidjson::Value &obj, const char field[]) noexcept
Definition: JsonAccessors.h:31
final Map< CorrelationId, DeferredLookup > mapCorrelToDeferred
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ getDynamicParamCount()

int org.apache.calcite.sql2rel.SqlToRelConverter.getDynamicParamCount ( )
inline

Returns the number of dynamic parameters encountered during translation; this must only be called after convertQuery.

Returns
number of dynamic parameters

Definition at line 351 of file SqlToRelConverter.java.

351  {
352  return dynamicParamSqlNodes.size();
353  }
final List< SqlDynamicParam > dynamicParamSqlNodes

◆ getDynamicParamCountInExplain()

int org.apache.calcite.sql2rel.SqlToRelConverter.getDynamicParamCountInExplain ( boolean  increment)
inline

Returns the current count of the number of dynamic parameters in an EXPLAIN PLAN statement.

Parameters
incrementif true, increment the count
Returns
the current count before the optional increment

Definition at line 376 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.explainParamCount.

376  {
377  int retVal = explainParamCount;
378  if (increment) {
380  }
381  return retVal;
382  }

◆ getDynamicParamType()

RelDataType org.apache.calcite.sql2rel.SqlToRelConverter.getDynamicParamType ( int  index)
inline

Returns the type inferred for a dynamic parameter.

Parameters
index0-based index of dynamic parameter
Returns
inferred type, never null

Definition at line 361 of file SqlToRelConverter.java.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertDynamicParam().

361  {
362  SqlNode sqlNode = dynamicParamSqlNodes.get(index);
363  if (sqlNode == null) {
364  throw Util.needToImplement("dynamic param type inference");
365  }
366  return validator.getValidatedNodeType(sqlNode);
367  }
final List< SqlDynamicParam > dynamicParamSqlNodes
+ Here is the caller graph for this function:

◆ getInitializerFactory()

InitializerExpressionFactory org.apache.calcite.sql2rel.SqlToRelConverter.getInitializerFactory ( SqlValidatorTable  validatorTable)
inlineprivate

Definition at line 3274 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.unwrap().

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertColumnList().

3275  {
3276  // We might unwrap a null instead of a InitializerExpressionFactory.
3277  final Table table = unwrap(validatorTable, Table.class);
3278  if (table != null) {
3279  InitializerExpressionFactory f = unwrap(table, InitializerExpressionFactory.class);
3280  if (f != null) {
3281  return f;
3282  }
3283  }
3284  return NullInitializerExpressionFactory.INSTANCE;
3285  }
static< T > T unwrap(Object o, Class< T > clazz)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ getInSubqueryThreshold()

int org.apache.calcite.sql2rel.SqlToRelConverter.getInSubqueryThreshold ( )
inlineprotected

Gets the list size threshold under which convertInToOr is used. Lists of this size or greater will instead be converted to use a join against an inline table (org.apache.calcite.rel.logical.LogicalValues) rather than a predicate. A threshold of 0 forces usage of an inline table in all cases; a threshold of Integer.MAX_VALUE forces usage of OR in all cases

Returns
threshold, default DEFAULT_IN_SUB_QUERY_THRESHOLD

Definition at line 1434 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.config.

1434  {
1435  return config.getInSubQueryThreshold();
1436  }

◆ getMapConvertedNonCorrSubqs()

Map<SqlNode, RexNode> org.apache.calcite.sql2rel.SqlToRelConverter.getMapConvertedNonCorrSubqs ( )
inline
Returns
mapping of non-correlated sub-queries that have been converted to the constants that they evaluate to

Definition at line 388 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.mapConvertedNonCorrSubqs.

388  {
390  }
final Map< SqlNode, RexNode > mapConvertedNonCorrSubqs

◆ getRexBuilder()

RexBuilder org.apache.calcite.sql2rel.SqlToRelConverter.getRexBuilder ( )
inline

Returns the row-expression builder.

Definition at line 341 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.rexBuilder.

341  {
342  return rexBuilder;
343  }

◆ getSystemFields()

List<RelDataTypeField> org.apache.calcite.sql2rel.SqlToRelConverter.getSystemFields ( )
inlineprotected

Returns a list of fields to be prefixed to each relational expression.

Returns
List of system fields

Definition at line 2522 of file SqlToRelConverter.java.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.setRoot().

2522  {
2523  return Collections.emptyList();
2524  }
+ Here is the caller graph for this function:

◆ getTargetTable()

RelOptTable org.apache.calcite.sql2rel.SqlToRelConverter.getTargetTable ( SqlNode  call)
inlineprotected

Definition at line 3172 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.catalogReader.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.collectInsertTargets(), org.apache.calcite.sql2rel.SqlToRelConverter.convertColumnList(), org.apache.calcite.sql2rel.SqlToRelConverter.convertDelete(), org.apache.calcite.sql2rel.SqlToRelConverter.convertInsert(), org.apache.calcite.sql2rel.SqlToRelConverter.convertMerge(), and org.apache.calcite.sql2rel.SqlToRelConverter.convertUpdate().

3172  {
3173  final SqlValidatorNamespace targetNs = validator.getNamespace(call);
3174  if (targetNs.isWrapperFor(SqlValidatorImpl.DmlNamespace.class)) {
3175  final SqlValidatorImpl.DmlNamespace dmlNamespace =
3176  targetNs.unwrap(SqlValidatorImpl.DmlNamespace.class);
3177  return SqlValidatorUtil.getRelOptTable(dmlNamespace, catalogReader, null, null);
3178  }
3179  final SqlValidatorNamespace resolvedNamespace = targetNs.resolve();
3180  return SqlValidatorUtil.getRelOptTable(resolvedNamespace, catalogReader, null, null);
3181  }
+ Here is the caller graph for this function:

◆ isOrdered()

static boolean org.apache.calcite.sql2rel.SqlToRelConverter.isOrdered ( SqlNode  query)
inlinestatic

Definition at line 584 of file SqlToRelConverter.java.

References anonymous_namespace{UpdateMetadataTest.cpp}.query.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertQuery().

584  {
585  switch (query.getKind()) {
586  case SELECT:
587  return ((SqlSelect) query).getOrderList() != null
588  && ((SqlSelect) query).getOrderList().size() > 0;
589  case WITH:
590  return isOrdered(((SqlWith) query).body);
591  case ORDER_BY:
592  return ((SqlOrderBy) query).orderList.size() > 0;
593  default:
594  return false;
595  }
596  }
+ Here is the caller graph for this function:

◆ isRowConstructor()

boolean org.apache.calcite.sql2rel.SqlToRelConverter.isRowConstructor ( SqlNode  node)
inlineprivate

Definition at line 1605 of file SqlToRelConverter.java.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertRowConstructor(), and org.apache.calcite.sql2rel.SqlToRelConverter.convertRowValues().

1605  {
1606  if (!(node.getKind() == SqlKind.ROW)) {
1607  return false;
1608  }
1609  SqlCall call = (SqlCall) node;
1610  return call.getOperator().getName().equalsIgnoreCase("row");
1611  }
+ Here is the caller graph for this function:

◆ isStream()

static boolean org.apache.calcite.sql2rel.SqlToRelConverter.isStream ( SqlNode  query)
inlinestaticprivate

Definition at line 579 of file SqlToRelConverter.java.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertQuery().

579  {
580  return query instanceof SqlSelect
581  && ((SqlSelect) query).isKeywordPresent(SqlSelectKeyword.STREAM);
582  }
+ Here is the caller graph for this function:

◆ isSubQueryNonCorrelated()

boolean org.apache.calcite.sql2rel.SqlToRelConverter.isSubQueryNonCorrelated ( RelNode  subq,
Blackboard  bb 
)
inlineprivate

Determines whether a sub-query is non-correlated. Note that a non-correlated sub-query can contain correlated references, provided those references do not reference select statements that are parents of the sub-query.

Parameters
subqthe sub-query
bbblackboard used while converting the sub-query, i.e., the blackboard of the parent query of this sub-query
Returns
true if the sub-query is non-correlated

Definition at line 2485 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.DeferredLookup.bb, org.apache.calcite.sql2rel.SqlToRelConverter.DeferredLookup.getOriginalRelName(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.scope, and Experimental.String.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertNonCorrelatedSubQuery().

2485  {
2486  Set<CorrelationId> correlatedVariables = RelOptUtil.getVariablesUsed(subq);
2487  for (CorrelationId correlName : correlatedVariables) {
2488  DeferredLookup lookup = mapCorrelToDeferred.get(correlName);
2489  String originalRelName = lookup.getOriginalRelName();
2490 
2491  final SqlNameMatcher nameMatcher =
2492  lookup.bb.scope.getValidator().getCatalogReader().nameMatcher();
2493  final SqlValidatorScope.ResolvedImpl resolved =
2494  new SqlValidatorScope.ResolvedImpl();
2495  lookup.bb.scope.resolve(
2496  ImmutableList.of(originalRelName), nameMatcher, false, resolved);
2497 
2498  SqlValidatorScope ancestorScope = resolved.only().scope;
2499 
2500  // If the correlated reference is in a scope that's "above" the
2501  // sub-query, then this is a correlated sub-query.
2502  SqlValidatorScope parentScope = bb.scope;
2503  do {
2504  if (ancestorScope == parentScope) {
2505  return false;
2506  }
2507  if (parentScope instanceof DelegatingScope) {
2508  parentScope = ((DelegatingScope) parentScope).getParent();
2509  } else {
2510  break;
2511  }
2512  } while (parentScope != null);
2513  }
2514  return true;
2515  }
final Map< CorrelationId, DeferredLookup > mapCorrelToDeferred
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ isTrimUnusedFields()

boolean org.apache.calcite.sql2rel.SqlToRelConverter.isTrimUnusedFields ( )
inline

Returns whether to trim unused fields as part of the conversion process.

Returns
Whether to trim unused fields

Definition at line 2968 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.config, and org.apache.calcite.sql2rel.SqlToRelConverter.isTrimUnusedFields().

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.isTrimUnusedFields(), and org.apache.calcite.sql2rel.SqlToRelConverter.trimUnusedFields().

2968  {
2969  return config.isTrimUnusedFields();
2970  }
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ negate()

SqlQuantifyOperator org.apache.calcite.sql2rel.SqlToRelConverter.negate ( SqlQuantifyOperator  operator)
inlineprivate

Definition at line 4512 of file SqlToRelConverter.java.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.convertExpression().

4512  {
4513  assert operator.kind == SqlKind.ALL;
4514  return SqlStdOperatorTable.some(operator.comparisonKind.negateNullSafe());
4515  }
+ Here is the caller graph for this function:

◆ newFieldTrimmer()

RelFieldTrimmer org.apache.calcite.sql2rel.SqlToRelConverter.newFieldTrimmer ( )
inlineprotected

Creates a RelFieldTrimmer.

Returns
Field trimmer

Definition at line 531 of file SqlToRelConverter.java.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.trimUnusedFields().

531  {
532  return new RelFieldTrimmer(validator, relBuilder);
533  }
+ Here is the caller graph for this function:

◆ pushDownNotForIn()

static SqlNode org.apache.calcite.sql2rel.SqlToRelConverter.pushDownNotForIn ( SqlValidatorScope  scope,
SqlNode  sqlNode 
)
inlinestaticprivate

Push down all the NOT logical operators into any IN/NOT IN operators.

Parameters
scopeScope where
sqlNode
occurs
sqlNodethe root node from which to look for NOT operators
Returns
the transformed SqlNode representation with NOT pushed down.

Definition at line 823 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.containsInOperator(), and org.apache.calcite.sql2rel.SqlToRelConverter.reg().

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertWhere(), and org.apache.calcite.sql2rel.SqlToRelConverter.createAggImpl().

823  {
824  if (!(sqlNode instanceof SqlCall) || !containsInOperator(sqlNode)) {
825  return sqlNode;
826  }
827  final SqlCall sqlCall = (SqlCall) sqlNode;
828  switch (sqlCall.getKind()) {
829  case AND:
830  case OR:
831  final List<SqlNode> operands = new ArrayList<>();
832  for (SqlNode operand : sqlCall.getOperandList()) {
833  operands.add(pushDownNotForIn(scope, operand));
834  }
835  final SqlCall newCall =
836  sqlCall.getOperator().createCall(sqlCall.getParserPosition(), operands);
837  return reg(scope, newCall);
838 
839  case NOT:
840  assert sqlCall.operand(0) instanceof SqlCall;
841  final SqlCall call = sqlCall.operand(0);
842  switch (sqlCall.operand(0).getKind()) {
843  case CASE:
844  final SqlCase caseNode = (SqlCase) call;
845  final SqlNodeList thenOperands = new SqlNodeList(SqlParserPos.ZERO);
846 
847  for (SqlNode thenOperand : caseNode.getThenOperands()) {
848  final SqlCall not =
849  SqlStdOperatorTable.NOT.createCall(SqlParserPos.ZERO, thenOperand);
850  thenOperands.add(pushDownNotForIn(scope, reg(scope, not)));
851  }
852  SqlNode elseOperand = caseNode.getElseOperand();
853  if (!SqlUtil.isNull(elseOperand)) {
854  // "not(unknown)" is "unknown", so no need to simplify
855  final SqlCall not =
856  SqlStdOperatorTable.NOT.createCall(SqlParserPos.ZERO, elseOperand);
857  elseOperand = pushDownNotForIn(scope, reg(scope, not));
858  }
859 
860  return reg(scope,
861  SqlStdOperatorTable.CASE.createCall(SqlParserPos.ZERO,
862  caseNode.getValueOperand(),
863  caseNode.getWhenOperands(),
864  thenOperands,
865  elseOperand));
866 
867  case AND:
868  final List<SqlNode> orOperands = new ArrayList<>();
869  for (SqlNode operand : call.getOperandList()) {
870  orOperands.add(pushDownNotForIn(scope,
871  reg(scope,
872  SqlStdOperatorTable.NOT.createCall(
873  SqlParserPos.ZERO, operand))));
874  }
875  return reg(scope,
876  SqlStdOperatorTable.OR.createCall(SqlParserPos.ZERO, orOperands));
877 
878  case OR:
879  final List<SqlNode> andOperands = new ArrayList<>();
880  for (SqlNode operand : call.getOperandList()) {
881  andOperands.add(pushDownNotForIn(scope,
882  reg(scope,
883  SqlStdOperatorTable.NOT.createCall(
884  SqlParserPos.ZERO, operand))));
885  }
886  return reg(scope,
887  SqlStdOperatorTable.AND.createCall(SqlParserPos.ZERO, andOperands));
888 
889  case NOT:
890  assert call.operandCount() == 1;
891  return pushDownNotForIn(scope, call.operand(0));
892 
893  case NOT_IN:
894  return reg(scope,
895  SqlStdOperatorTable.IN.createCall(
896  SqlParserPos.ZERO, call.getOperandList()));
897 
898  case IN:
899  return reg(scope,
900  SqlStdOperatorTable.NOT_IN.createCall(
901  SqlParserPos.ZERO, call.getOperandList()));
902  }
903  }
904  return sqlNode;
905  }
static SqlNode pushDownNotForIn(SqlValidatorScope scope, SqlNode sqlNode)
static SqlNode reg(SqlValidatorScope scope, SqlNode e)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ reg()

static SqlNode org.apache.calcite.sql2rel.SqlToRelConverter.reg ( SqlValidatorScope  scope,
SqlNode  e 
)
inlinestaticprivate

Registers with the validator a SqlNode that has been created during the Sql-to-Rel process.

Definition at line 911 of file SqlToRelConverter.java.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.pushDownNotForIn().

911  {
912  scope.getValidator().deriveType(scope, e);
913  return e;
914  }
+ Here is the caller graph for this function:

◆ replaceSubQueries()

void org.apache.calcite.sql2rel.SqlToRelConverter.replaceSubQueries ( final Blackboard  bb,
final SqlNode  expr,
RelOptUtil.Logic  logic 
)
inlineprivate

Definition at line 952 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.findSubQueries(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.subQueryList, and org.apache.calcite.sql2rel.SqlToRelConverter.substituteSubQuery().

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertCollectionTable(), org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(), org.apache.calcite.sql2rel.SqlToRelConverter.convertJoinCondition(), org.apache.calcite.sql2rel.SqlToRelConverter.convertMatchRecognize(), org.apache.calcite.sql2rel.SqlToRelConverter.convertSelectList(), org.apache.calcite.sql2rel.SqlToRelConverter.convertUpdate(), org.apache.calcite.sql2rel.SqlToRelConverter.convertValuesImpl(), org.apache.calcite.sql2rel.SqlToRelConverter.convertWhere(), and org.apache.calcite.sql2rel.SqlToRelConverter.createAggImpl().

953  {
954  findSubQueries(bb, expr, logic, false);
955  for (SubQuery node : bb.subQueryList) {
956  substituteSubQuery(bb, node);
957  }
958  }
void substituteSubQuery(Blackboard bb, SubQuery subQuery)
void findSubQueries(Blackboard bb, SqlNode node, RelOptUtil.Logic logic, boolean registerOnlyScalarSubQueries)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ requiredCollation()

RelCollation org.apache.calcite.sql2rel.SqlToRelConverter.requiredCollation ( RelNode  r)
inlineprivate

Definition at line 598 of file SqlToRelConverter.java.

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertQuery().

598  {
599  if (r instanceof Sort) {
600  return ((Sort) r).collation;
601  }
602  if (r instanceof Project) {
603  return requiredCollation(((Project) r).getInput());
604  }
605  if (r instanceof Delta) {
606  return requiredCollation(((Delta) r).getInput());
607  }
608  throw new AssertionError();
609  }
+ Here is the caller graph for this function:

◆ setDynamicParamCountInExplain()

void org.apache.calcite.sql2rel.SqlToRelConverter.setDynamicParamCountInExplain ( int  explainParamCount)
inline

Sets the number of dynamic parameters in the current EXPLAIN PLAN statement.

Parameters
explainParamCountnumber of dynamic parameters in the statement

Definition at line 420 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.config, and org.apache.calcite.sql2rel.SqlToRelConverter.explainParamCount.

420  {
421  assert config.isExplain();
423  }

◆ setSubQueryConverter()

void org.apache.calcite.sql2rel.SqlToRelConverter.setSubQueryConverter ( SubQueryConverter  converter)
inline

Sets a new SubQueryConverter. To have any effect, this must be called before any convert method.

Parameters
converternew SubQueryConverter

Definition at line 410 of file SqlToRelConverter.java.

410  {
411  subQueryConverter = converter;
412  }

◆ snapshotTemporalTable()

void org.apache.calcite.sql2rel.SqlToRelConverter.snapshotTemporalTable ( Blackboard  bb,
SqlCall  call 
)
inlineprivate

Definition at line 2270 of file SqlToRelConverter.java.

References org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.convertExpression(), org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.root, and org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.setRoot().

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom().

2270  {
2271  final SqlSnapshot snapshot = (SqlSnapshot) call;
2272  final RexNode period = bb.convertExpression(snapshot.getPeriod());
2273 
2274  // convert inner query, could be a table name or a derived table
2275  SqlNode expr = snapshot.getTableRef();
2276  convertFrom(bb, expr);
2277  final TableScan scan = (TableScan) bb.root;
2278 
2279  final RelNode snapshotRel = relBuilder.push(scan).snapshot(period).build();
2280 
2281  bb.setRoot(snapshotRel, false);
2282  }
void convertFrom(Blackboard bb, SqlNode from)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ substituteSubQuery()

void org.apache.calcite.sql2rel.SqlToRelConverter.substituteSubQuery ( Blackboard  bb,
SubQuery  subQuery 
)
inlineprivate

Definition at line 960 of file SqlToRelConverter.java.

References ALL, run-benchmark-import.args, org.apache.calcite.sql2rel.SqlToRelConverter.config, org.apache.calcite.sql2rel.SqlToRelConverter.containsNullLiteral(), org.apache.calcite.sql2rel.SqlToRelConverter.convertCursor(), org.apache.calcite.sql2rel.SqlToRelConverter.convertExists(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.convertExpression(), org.apache.calcite.sql2rel.SqlToRelConverter.convertInToOr(), org.apache.calcite.sql2rel.SqlToRelConverter.convertMultisets(), org.apache.calcite.sql2rel.SqlToRelConverter.convertNonCorrelatedSubQuery(), org.apache.calcite.sql2rel.SqlToRelConverter.convertQueryOrInList(), org.apache.calcite.sql2rel.SqlToRelConverter.convertToSingleValueSubq(), org.apache.calcite.sql2rel.SqlToRelConverter.createBlackboard(), Double, org.apache.calcite.sql2rel.SqlToRelConverter.SubQuery.expr, join(), org.apache.calcite.sql2rel.SqlToRelConverter.SubQuery.logic, org.apache.calcite.sql2rel.SqlToRelConverter.SubQuery.node, anonymous_namespace{UpdateMetadataTest.cpp}.query, org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.register(), org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.root, org.apache.calcite.sql2rel.SqlToRelConverter.Blackboard.setRoot(), and org.apache.calcite.sql2rel.SqlToRelConverter.translateIn().

Referenced by org.apache.calcite.sql2rel.SqlToRelConverter.replaceSubQueries().

960  {
961  final RexNode expr = subQuery.expr;
962  if (expr != null) {
963  // Already done.
964  return;
965  }
966 
967  final SqlBasicCall call;
968  final RelNode rel;
969  final SqlNode query;
970  final RelOptUtil.Exists converted;
971  switch (subQuery.node.getKind()) {
972  case CURSOR:
973  convertCursor(bb, subQuery);
974  return;
975 
976  case MULTISET_QUERY_CONSTRUCTOR:
977  case MULTISET_VALUE_CONSTRUCTOR:
978  case ARRAY_QUERY_CONSTRUCTOR:
979  rel = convertMultisets(ImmutableList.of(subQuery.node), bb);
980  subQuery.expr = bb.register(rel, JoinRelType.INNER);
981  return;
982 
983  case IN:
984  case NOT_IN:
985  case SOME:
986  case ALL:
987  call = (SqlBasicCall) subQuery.node;
988  query = call.operand(1);
989  if (!config.isExpand() && !(query instanceof SqlNodeList)) {
990  return;
991  }
992  final SqlNode leftKeyNode = call.operand(0);
993 
994  final List<RexNode> leftKeys;
995  switch (leftKeyNode.getKind()) {
996  case ROW:
997  leftKeys = new ArrayList<>();
998  for (SqlNode sqlExpr : ((SqlBasicCall) leftKeyNode).getOperandList()) {
999  leftKeys.add(bb.convertExpression(sqlExpr));
1000  }
1001  break;
1002  default:
1003  leftKeys = ImmutableList.of(bb.convertExpression(leftKeyNode));
1004  }
1005 
1006  if (query instanceof SqlNodeList) {
1007  SqlNodeList valueList = (SqlNodeList) query;
1008  if (!containsNullLiteral(valueList)
1009  && valueList.size() < config.getInSubQueryThreshold()) {
1010  // We're under the threshold, so convert to OR.
1011  subQuery.expr = convertInToOr(
1012  bb, leftKeys, valueList, (SqlInOperator) call.getOperator());
1013  return;
1014  }
1015 
1016  // Otherwise, let convertExists translate
1017  // values list into an inline table for the
1018  // reference to Q below.
1019  }
1020 
1021  // Project out the search columns from the left side
1022 
1023  // Q1:
1024  // "select from emp where emp.deptno in (select col1 from T)"
1025  //
1026  // is converted to</