Java Code Examples for org.apache.calcite.sql.SqlNodeList#get()

The following examples show how to use org.apache.calcite.sql.SqlNodeList#get() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: Bats   File: SqlImplementor.java    License: Apache License 2.0 6 votes vote down vote up
private boolean hasNestedAggregations(LogicalAggregate rel) {
    if (node instanceof SqlSelect) {
        final SqlNodeList selectList = ((SqlSelect) node).getSelectList();
        if (selectList != null) {
            final Set<Integer> aggregatesArgs = new HashSet<>();
            for (AggregateCall aggregateCall : rel.getAggCallList()) {
                aggregatesArgs.addAll(aggregateCall.getArgList());
            }
            for (int aggregatesArg : aggregatesArgs) {
                if (selectList.get(aggregatesArg) instanceof SqlBasicCall) {
                    final SqlBasicCall call = (SqlBasicCall) selectList.get(aggregatesArg);
                    for (SqlNode operand : call.getOperands()) {
                        if (operand instanceof SqlCall
                                && ((SqlCall) operand).getOperator() instanceof SqlAggFunction) {
                            return true;
                        }
                    }
                }
            }
        }
    }
    return false;
}
 
Example 2
Source Project: Flink-CEPplus   File: SqlValidatorImpl.java    License: Apache License 2.0 6 votes vote down vote up
public SqlNodeList expandStar(
	SqlNodeList selectList,
	SqlSelect select,
	boolean includeSystemVars) {
	final List<SqlNode> list = new ArrayList<>();
	final List<Map.Entry<String, RelDataType>> types = new ArrayList<>();
	for (int i = 0; i < selectList.size(); i++) {
		final SqlNode selectItem = selectList.get(i);
		final RelDataType originalType = getValidatedNodeTypeIfKnown(selectItem);
		expandSelectItem(
			selectItem,
			select,
			Util.first(originalType, unknownType),
			list,
			catalogReader.nameMatcher().createSet(),
			types,
			includeSystemVars);
	}
	getRawSelectScope(select).setExpandedSelectList(list);
	return new SqlNodeList(list, SqlParserPos.ZERO);
}
 
Example 3
Source Project: flink   File: SqlValidatorImpl.java    License: Apache License 2.0 6 votes vote down vote up
public SqlNodeList expandStar(
	SqlNodeList selectList,
	SqlSelect select,
	boolean includeSystemVars) {
	final List<SqlNode> list = new ArrayList<>();
	final List<Map.Entry<String, RelDataType>> types = new ArrayList<>();
	for (int i = 0; i < selectList.size(); i++) {
		final SqlNode selectItem = selectList.get(i);
		final RelDataType originalType = getValidatedNodeTypeIfKnown(selectItem);
		expandSelectItem(
			selectItem,
			select,
			Util.first(originalType, unknownType),
			list,
			catalogReader.nameMatcher().createSet(),
			types,
			includeSystemVars);
	}
	getRawSelectScope(select).setExpandedSelectList(list);
	return new SqlNodeList(list, SqlParserPos.ZERO);
}
 
Example 4
Source Project: flink   File: SqlValidatorImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the <code>ordinal</code>th item in the select list.
 */
private SqlNode nthSelectItem(int ordinal, final SqlParserPos pos) {
	// TODO: Don't expand the list every time. Maybe keep an expanded
	// version of each expression -- select lists and identifiers -- in
	// the validator.

	SqlNodeList expandedSelectList =
		expandStar(
			select.getSelectList(),
			select,
			false);
	SqlNode expr = expandedSelectList.get(ordinal);
	expr = stripAs(expr);
	if (expr instanceof SqlIdentifier) {
		expr = getScope().fullyQualify((SqlIdentifier) expr).identifier;
	}

	// Create a copy of the expression with the position of the order
	// item.
	return expr.clone(pos);
}
 
Example 5
Source Project: calcite   File: SelectScope.java    License: Apache License 2.0 6 votes vote down vote up
public SqlMonotonicity getMonotonicity(SqlNode expr) {
  SqlMonotonicity monotonicity = expr.getMonotonicity(this);
  if (monotonicity != SqlMonotonicity.NOT_MONOTONIC) {
    return monotonicity;
  }

  // TODO: compare fully qualified names
  final SqlNodeList orderList = getOrderList();
  if (orderList.size() > 0) {
    SqlNode order0 = orderList.get(0);
    monotonicity = SqlMonotonicity.INCREASING;
    if ((order0 instanceof SqlCall)
        && (((SqlCall) order0).getOperator()
        == SqlStdOperatorTable.DESC)) {
      monotonicity = monotonicity.reverse();
      order0 = ((SqlCall) order0).operand(0);
    }
    if (expr.equalsDeep(order0, Litmus.IGNORE)) {
      return monotonicity;
    }
  }

  return SqlMonotonicity.NOT_MONOTONIC;
}
 
Example 6
Source Project: calcite   File: SqlBasicVisitor.java    License: Apache License 2.0 5 votes vote down vote up
public R visit(SqlNodeList nodeList) {
  R result = null;
  for (int i = 0; i < nodeList.size(); i++) {
    SqlNode node = nodeList.get(i);
    result = node.accept(this);
  }
  return result;
}
 
Example 7
Source Project: Flink-CEPplus   File: SqlValidatorImpl.java    License: Apache License 2.0 5 votes vote down vote up
private void registerSubQueries(
	SqlValidatorScope parentScope,
	SqlNode node) {
	if (node == null) {
		return;
	}
	if (node.getKind().belongsTo(SqlKind.QUERY)
		|| node.getKind() == SqlKind.MULTISET_QUERY_CONSTRUCTOR
		|| node.getKind() == SqlKind.MULTISET_VALUE_CONSTRUCTOR) {
		registerQuery(parentScope, null, node, node, null, false);
	} else if (node instanceof SqlCall) {
		validateNodeFeature(node);
		SqlCall call = (SqlCall) node;
		for (int i = 0; i < call.operandCount(); i++) {
			registerOperandSubQueries(parentScope, call, i);
		}
	} else if (node instanceof SqlNodeList) {
		SqlNodeList list = (SqlNodeList) node;
		for (int i = 0, count = list.size(); i < count; i++) {
			SqlNode listNode = list.get(i);
			if (listNode.getKind().belongsTo(SqlKind.QUERY)) {
				listNode =
					SqlStdOperatorTable.SCALAR_QUERY.createCall(
						listNode.getParserPosition(),
						listNode);
				list.set(i, listNode);
			}
			registerSubQueries(parentScope, listNode);
		}
	} else {
		// atomic node -- can be ignored
	}
}
 
Example 8
Source Project: flink   File: SqlValidatorImpl.java    License: Apache License 2.0 5 votes vote down vote up
private void registerSubQueries(
	SqlValidatorScope parentScope,
	SqlNode node) {
	if (node == null) {
		return;
	}
	if (node.getKind().belongsTo(SqlKind.QUERY)
		|| node.getKind() == SqlKind.MULTISET_QUERY_CONSTRUCTOR
		|| node.getKind() == SqlKind.MULTISET_VALUE_CONSTRUCTOR) {
		registerQuery(parentScope, null, node, node, null, false);
	} else if (node instanceof SqlCall) {
		validateNodeFeature(node);
		SqlCall call = (SqlCall) node;
		for (int i = 0; i < call.operandCount(); i++) {
			registerOperandSubQueries(parentScope, call, i);
		}
	} else if (node instanceof SqlNodeList) {
		SqlNodeList list = (SqlNodeList) node;
		for (int i = 0, count = list.size(); i < count; i++) {
			SqlNode listNode = list.get(i);
			if (listNode.getKind().belongsTo(SqlKind.QUERY)) {
				listNode =
					SqlStdOperatorTable.SCALAR_QUERY.createCall(
						listNode.getParserPosition(),
						listNode);
				list.set(i, listNode);
			}
			registerSubQueries(parentScope, listNode);
		}
	} else {
		// atomic node -- can be ignored
	}
}
 
Example 9
@Override
public SqlNode visit(SqlNodeList nodeList) {
    for (int i = 0; i < nodeList.size(); i++) {
        SqlNode node = nodeList.get(i);
        if (node instanceof SqlWithItem) {
            SqlWithItem item = (SqlWithItem) node;
            item.query.accept(this);
        }
    }
    return null;
}
 
Example 10
Source Project: AthenaX   File: Validator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Validate there is only one SqlSelect construct in the lists of queries
 * and it is the last construct.
 */
@VisibleForTesting
void validateExactlyOnceSelect(SqlNodeList query) {
  Preconditions.checkArgument(query.size() > 0);
  SqlNode last = query.get(query.size() - 1);
  long n = StreamSupport.stream(query.spliterator(), false)
      .filter(x -> x instanceof SqlSelect)
      .count();
  Preconditions.checkArgument(n == 1 && last instanceof SqlSelect,
      "Only one top-level SELECT statement is allowed");
  statement = (SqlSelect) last;
}
 
Example 11
Source Project: flink   File: SqlAlterHiveTableSerDe.java    License: Apache License 2.0 5 votes vote down vote up
private static SqlNodeList appendPrefix(SqlNodeList propList) {
	if (propList != null) {
		for (int i = 0; i < propList.size(); i++) {
			SqlTableOption tableOption = (SqlTableOption) propList.get(i);
			if (!tableOption.getKeyString().equals(ALTER_TABLE_OP)) {
				String key = HiveTableRowFormat.SERDE_INFO_PROP_PREFIX + tableOption.getKeyString();
				tableOption = HiveDDLUtils.toTableOption(key, tableOption.getValue(), tableOption.getParserPosition());
				propList.set(i, tableOption);
			}
		}
	}
	return propList;
}
 
Example 12
Source Project: kylin   File: CalciteParser.java    License: Apache License 2.0 5 votes vote down vote up
public static SqlNode getOnlySelectNode(String sql) {
    SqlNodeList selectList = null;
    try {
        selectList = ((SqlSelect) CalciteParser.parse(sql)).getSelectList();
    } catch (SqlParseException e) {
        throw new RuntimeException(
                "Failed to parse expression \'" + sql + "\', please make sure the expression is valid", e);
    }

    Preconditions.checkArgument(selectList.size() == 1,
            "Expression is invalid because size of select list exceeds one");

    return selectList.get(0);
}
 
Example 13
Source Project: Bats   File: SqlImplementor.java    License: Apache License 2.0 4 votes vote down vote up
/** Once you have a Result of implementing a child relational expression,
 * call this method to create a Builder to implement the current relational
 * expression by adding additional clauses to the SQL query.
 *
 * <p>You need to declare which clauses you intend to add. If the clauses
 * are "later", you can add to the same query. For example, "GROUP BY" comes
 * after "WHERE". But if they are the same or earlier, this method will
 * start a new SELECT that wraps the previous result.
 *
 * <p>When you have called
 * {@link Builder#setSelect(SqlNodeList)},
 * {@link Builder#setWhere(SqlNode)} etc. call
 * {@link Builder#result(SqlNode, Collection, RelNode, Map)}
 * to fix the new query.
 *
 * @param rel Relational expression being implemented
 * @param clauses Clauses that will be generated to implement current
 *                relational expression
 * @return A builder
 */
public Builder builder(RelNode rel, Clause... clauses) {
    final Clause maxClause = maxClause();
    boolean needNew = false;
    // If old and new clause are equal and belong to below set,
    // then new SELECT wrap is not required
    Set<Clause> nonWrapSet = ImmutableSet.of(Clause.SELECT);
    for (Clause clause : clauses) {
        if (maxClause.ordinal() > clause.ordinal() || (maxClause == clause && !nonWrapSet.contains(clause))) {
            needNew = true;
        }
    }
    if (rel instanceof LogicalAggregate && !dialect.supportsNestedAggregations()
            && hasNestedAggregations((LogicalAggregate) rel)) {
        needNew = true;
    }

    SqlSelect select;
    FluentListUtils.FluentList<Clause> clauseList = FluentListUtils.list();
    if (needNew) {
        select = subSelect();
    } else {
        select = asSelect();
        clauseList.addAll(this.clauses);
    }
    clauseList.appendAll(clauses);
    Context newContext;
    final SqlNodeList selectList = select.getSelectList();
    if (selectList != null) {
        newContext = new Context(dialect, selectList.size()) {
            @Override
            public SqlNode field(int ordinal) {
                final SqlNode selectItem = selectList.get(ordinal);
                switch (selectItem.getKind()) {
                case AS:
                    return ((SqlCall) selectItem).operand(0);
                }
                return selectItem;
            }
        };
    } else {
        boolean qualified = !dialect.hasImplicitTableAlias() || aliases.size() > 1;
        // basically, we did a subSelect() since needNew is set and neededAlias is not null
        // now, we need to make sure that we need to update the alias context.
        // if our aliases map has a single element: <neededAlias, rowType>,
        // then we don't need to rewrite the alias but otherwise, it should be updated.
        if (needNew && neededAlias != null && (aliases.size() != 1 || !aliases.containsKey(neededAlias))) {
            final Map<String, RelDataType> newAliases = ImmutableMap.of(neededAlias,
                    rel.getInput(0).getRowType());
            newContext = aliasContext(newAliases, qualified);
        } else {
            newContext = aliasContext(aliases, qualified);
        }
    }
    return new Builder(rel, clauseList, select, newContext, needNew ? null : aliases);
}
 
Example 14
Source Project: calcite   File: AbstractTypeCoercion.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Cast column at index {@code index} to target type.
 *
 * @param scope      Validator scope for the node list
 * @param nodeList   Column node list
 * @param index      Index of column
 * @param targetType Target type to cast to
 */
protected boolean coerceColumnType(
    SqlValidatorScope scope,
    SqlNodeList nodeList,
    int index,
    RelDataType targetType) {
  // Transform the JavaType to SQL type because the SqlDataTypeSpec
  // does not support deriving JavaType yet.
  if (RelDataTypeFactoryImpl.isJavaType(targetType)) {
    targetType = ((JavaTypeFactory) factory).toSql(targetType);
  }

  // This will happen when there is a star/dynamic-star column in the select list,
  // and the source is values expression, i.e. `select * from (values(1, 2, 3))`.
  // There is no need to coerce the column type, only remark
  // the inferred row type has changed, we will then add in type coercion
  // when expanding star/dynamic-star.

  // See SqlToRelConverter#convertSelectList for details.
  if (index >= nodeList.getList().size()) {
    // Can only happen when there is a star(*) in the column,
    // just return true.
    return true;
  }

  final SqlNode node = nodeList.get(index);
  if (node instanceof SqlDynamicParam) {
    // Do not support implicit type coercion for dynamic param.
    return false;
  }
  if (node instanceof SqlIdentifier) {
    // Do not expand a star/dynamic table col.
    SqlIdentifier node1 = (SqlIdentifier) node;
    if (node1.isStar()) {
      return true;
    } else if (DynamicRecordType.isDynamicStarColName(Util.last(node1.names))) {
      // Should support implicit cast for dynamic table.
      return false;
    }
  }

  if (node instanceof SqlCall) {
    SqlCall node2 = (SqlCall) node;
    if (node2.getOperator().kind == SqlKind.AS) {
      final SqlNode operand = node2.operand(0);
      if (!needToCast(scope, operand, targetType)) {
        return false;
      }
      RelDataType targetType2 = syncAttributes(validator.deriveType(scope, operand), targetType);
      final SqlNode casted = castTo(operand, targetType2);
      node2.setOperand(0, casted);
      updateInferredType(casted, targetType2);
      return true;
    }
  }
  if (!needToCast(scope, node, targetType)) {
    return false;
  }
  RelDataType targetType3 = syncAttributes(validator.deriveType(scope, node), targetType);
  final SqlNode node3 = castTo(node, targetType3);
  nodeList.set(index, node3);
  updateInferredType(node3, targetType3);
  return true;
}
 
Example 15
Source Project: calcite   File: SqlImplementor.java    License: Apache License 2.0 4 votes vote down vote up
/** Once you have a Result of implementing a child relational expression,
 * call this method to create a Builder to implement the current relational
 * expression by adding additional clauses to the SQL query.
 *
 * <p>You need to declare which clauses you intend to add. If the clauses
 * are "later", you can add to the same query. For example, "GROUP BY" comes
 * after "WHERE". But if they are the same or earlier, this method will
 * start a new SELECT that wraps the previous result.
 *
 * <p>When you have called
 * {@link Builder#setSelect(SqlNodeList)},
 * {@link Builder#setWhere(SqlNode)} etc. call
 * {@link Builder#result(SqlNode, Collection, RelNode, Map)}
 * to fix the new query.
 *
 * @param rel Relational expression being implemented
 * @param clauses Clauses that will be generated to implement current
 *                relational expression
 * @return A builder
 */
public Builder builder(RelNode rel, Clause... clauses) {
  final boolean needNew = needNewSubQuery(rel, clauses);
  SqlSelect select;
  Expressions.FluentList<Clause> clauseList = Expressions.list();
  if (needNew) {
    select = subSelect();
  } else {
    select = asSelect();
    clauseList.addAll(this.clauses);
  }
  clauseList.appendAll(clauses);
  final Context newContext;
  Map<String, RelDataType> newAliases = null;
  final SqlNodeList selectList = select.getSelectList();
  if (selectList != null) {
    newContext = new Context(dialect, selectList.size()) {
      public SqlNode field(int ordinal) {
        final SqlNode selectItem = selectList.get(ordinal);
        switch (selectItem.getKind()) {
        case AS:
          return ((SqlCall) selectItem).operand(0);
        }
        return selectItem;
      }

      @Override public SqlNode orderField(int ordinal) {
        // If the field expression is an unqualified column identifier
        // and matches a different alias, use an ordinal.
        // For example, given
        //    SELECT deptno AS empno, empno AS x FROM emp ORDER BY emp.empno
        // we generate
        //    SELECT deptno AS empno, empno AS x FROM emp ORDER BY 2
        // "ORDER BY empno" would give incorrect result;
        // "ORDER BY x" is acceptable but is not preferred.
        final SqlNode node = field(ordinal);
        if (node instanceof SqlIdentifier
            && ((SqlIdentifier) node).isSimple()) {
          final String name = ((SqlIdentifier) node).getSimple();
          for (Ord<SqlNode> selectItem : Ord.zip(selectList)) {
            if (selectItem.i != ordinal) {
              final String alias =
                  SqlValidatorUtil.getAlias(selectItem.e, -1);
              if (name.equalsIgnoreCase(alias)) {
                return SqlLiteral.createExactNumeric(
                    Integer.toString(ordinal + 1), SqlParserPos.ZERO);
              }
            }
          }
        }
        return node;
      }
    };
  } else {
    boolean qualified =
        !dialect.hasImplicitTableAlias() || aliases.size() > 1;
    // basically, we did a subSelect() since needNew is set and neededAlias is not null
    // now, we need to make sure that we need to update the alias context.
    // if our aliases map has a single element:  <neededAlias, rowType>,
    // then we don't need to rewrite the alias but otherwise, it should be updated.
    if (needNew
        && neededAlias != null
        && (aliases.size() != 1 || !aliases.containsKey(neededAlias))) {
      newAliases =
          ImmutableMap.of(neededAlias, rel.getInput(0).getRowType());
      newContext = aliasContext(newAliases, qualified);
    } else {
      newContext = aliasContext(aliases, qualified);
    }
  }
  return new Builder(rel, clauseList, select, newContext, isAnon(),
      needNew && !aliases.containsKey(neededAlias) ? newAliases : aliases);
}
 
Example 16
Source Project: dremio-oss   File: SqlImplementor.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Once you have a Result of implementing a child relational expression,
 * call this method to create a Builder to implement the current relational
 * expression by adding additional clauses to the SQL query.
 *
 * <p>You need to declare which clauses you intend to add. If the clauses
 * are "later", you can add to the same query. For example, "GROUP BY" comes
 * after "WHERE". But if they are the same or earlier, this method will
 * start a new SELECT that wraps the previous result.
 *
 * <p>When you have called
 * {@link Builder#setSelect(SqlNodeList)},
 * {@link Builder#setWhere(SqlNode)} etc. call
 * {@link Builder#result(SqlNode, Collection, RelNode, Map)}
 * to fix the new query.
 *
 * @param rel     Relational expression being implemented
 * @param clauses Clauses that will be generated to implement current
 *                relational expression
 * @return A builder
 */
public Builder builder(RelNode rel, Clause... clauses) {
  final Clause maxClause = maxClause();
  boolean needNew = false;
  // If old and new clause are equal and belong to below set,
  // then new SELECT wrap is not required
  Set<Clause> nonWrapSet = ImmutableSet.of(Clause.SELECT);
  for (Clause clause : clauses) {
    if (maxClause.ordinal() > clause.ordinal()
      || (maxClause == clause && !nonWrapSet.contains(clause))) {
      needNew = true;
    }
  }
  if (rel instanceof LogicalAggregate
    && !dialect.supportsNestedAggregations()
    && hasNestedAggregations((LogicalAggregate) rel)) {
    needNew = true;
  }

  SqlSelect select;
  Expressions.FluentList<Clause> clauseList = Expressions.list();
  if (needNew) {
    select = subSelect();
  } else {
    select = asSelect();
    clauseList.addAll(this.clauses);
  }
  clauseList.appendAll(clauses);
  Context newContext;
  final SqlNodeList selectList = select.getSelectList();
  if (selectList != null) {
    newContext = new Context(selectList.size()) {
      @Override
      public SqlNode field(int ordinal) {
        final SqlNode selectItem = selectList.get(ordinal);
        switch (selectItem.getKind()) {
          case AS:
            return ((SqlCall) selectItem).operand(0);
        }
        return selectItem;
      }
    };
  } else {
    boolean qualified =
      !dialect.hasImplicitTableAlias() || aliases.size() > 1;
    // basically, we did a subSelect() since needNew is set and neededAlias is not null
    // now, we need to make sure that we need to update the alias context.
    // if our aliases map has a single element:  <neededAlias, rowType>,
    // then we don't need to rewrite the alias but otherwise, it should be updated.
    if (needNew
      && neededAlias != null
      && (aliases.size() != 1 || !aliases.containsKey(neededAlias))) {
      final Map<String, RelDataType> newAliases =
        ImmutableMap.of(neededAlias, rel.getInput(0).getRowType());
      newContext = aliasContext(newAliases, qualified);
    } else {
      newContext = aliasContext(aliases, qualified);
    }
  }
  return new Builder(rel, clauseList, select, newContext,
    needNew ? null : aliases);
}
 
Example 17
Source Project: quark   File: QuarkDDLExecutor.java    License: Apache License 2.0 4 votes vote down vote up
public int executeAlterDataSource(SqlAlterQuarkDataSource sqlNode) throws SQLException {
  DBI dbi = getDbi();
  DataSourceDAO dataSourceDAO = dbi.onDemand(DataSourceDAO.class);
  JdbcSourceDAO jdbcDAO = dbi.onDemand(JdbcSourceDAO.class);
  QuboleDbSourceDAO quboleDAO = dbi.onDemand(QuboleDbSourceDAO.class);
  DataSource dataSource = jdbcDAO.findByName(sqlNode.getIdentifier().getSimple(),
      connection.getDSSet().getId());
  if (dataSource == null) {
    dataSource = quboleDAO.findByName(sqlNode.getIdentifier().getSimple(),
        connection.getDSSet().getId());
  }
  if (dataSource == null) {
    return 0;
  }
  SqlNodeList rowList = sqlNode.getSourceExpressionList();
  int i = 0;
  for (SqlNode node : sqlNode.getTargetColumnList()) {
    if (node instanceof SqlIdentifier) {
      switch (((SqlIdentifier) node).getSimple()) {
        case "name":
          dataSource.setName(rowList.get(i).toString());
          break;
        case "type":
          dataSource.setType(rowList.get(i).toString());
          break;
        case "url":
          dataSource.setUrl(rowList.get(i).toString());
          break;
        case "ds_set_id":
          break;
        case "datasource_type":
          dataSource.setDatasourceType(rowList.get(i).toString());
          break;
        case "username":
          if (dataSource instanceof JdbcSource) {
            ((JdbcSource) dataSource)
                .setUsername(rowList.get(i).toString());
          }
          break;
        case "password":
          if (dataSource instanceof JdbcSource) {
            ((JdbcSource) dataSource)
                .setPassword(rowList.get(i).toString());
          }
          break;
        case "dbtap_id":
          if (dataSource instanceof QuboleDbSource) {
            if (rowList.get(i) instanceof SqlNumericLiteral) {
              ((QuboleDbSource) dataSource).setDbTapId(
                  ((SqlNumericLiteral) rowList.get(i)).intValue(true));
            } else {
              throw new SQLException("Incorrect argument type to variable"
                  + " 'dbtap_id'");
            }
          }
          break;
        case "auth_token":
          if (dataSource instanceof QuboleDbSource) {
            ((QuboleDbSource) dataSource)
                .setAuthToken(rowList.get(i).toString());
          }
          break;
        default:
          throw new SQLException("Unknown parameter: " + ((SqlIdentifier) node).getSimple());
      }
      i++;
    }
  }

  Encrypt encrypt;
  if (Boolean.parseBoolean(info.getProperty("encrypt", "false"))) {
    encrypt = new AESEncrypt(info.getProperty("encryptionKey"));
  } else {
    encrypt = new NoopEncrypt();
  }
  if (dataSource instanceof JdbcSource) {
    return jdbcDAO.update((JdbcSource) dataSource, dataSourceDAO, encrypt);
  } else {
    return quboleDAO.update((QuboleDbSource) dataSource, dataSourceDAO, encrypt);
  }
}
 
Example 18
Source Project: quark   File: QuarkDDLExecutor.java    License: Apache License 2.0 4 votes vote down vote up
private int executeCreateDataSource(SqlCreateQuarkDataSource sqlNode) throws SQLException {
  DBI dbi = getDbi();

  Map<String, Object> commonColumns = new HashMap<>();
  Map<String, Object> dbSpecificColumns = new HashMap<>();
  DataSourceDAO dataSourceDAO = dbi.onDemand(DataSourceDAO.class);
  JdbcSourceDAO jdbcSourceDAO = null;
  QuboleDbSourceDAO quboleDbSourceDAO = null;

  int i = 0;
  SqlNodeList rowList = sqlNode.getSourceExpressionList();
  for (SqlNode node : sqlNode.getTargetColumnList()) {
    if (node instanceof SqlIdentifier) {
      switch (((SqlIdentifier) node).getSimple()) {
        case "type":
          commonColumns.put("type", rowList.get(i).toString());
          break;
        case "url":
          commonColumns.put("url", rowList.get(i).toString());
          break;
        case "ds_set_id":
          break;
        case "datasource_type":
          if (rowList.get(i).toString().toUpperCase().equals("JDBC")) {
            jdbcSourceDAO = dbi.onDemand(JdbcSourceDAO.class);
          } else if (rowList.get(i).toString().toUpperCase().equals("QUBOLEDB")) {
            quboleDbSourceDAO = dbi.onDemand(QuboleDbSourceDAO.class);
          } else {
            throw new SQLException("Incorrect argument type <" + rowList.get(i).toString()
                + "> to variable 'datasource_type'");
          }
          commonColumns.put("datasource_type", rowList.get(i).toString());
          break;
        case "username":
          dbSpecificColumns.put("username", rowList.get(i).toString());
          break;
        case "password":
          dbSpecificColumns.put("password", rowList.get(i).toString());
          break;
        case "dbtap_id":
          if (rowList.get(i) instanceof SqlNumericLiteral) {
            dbSpecificColumns.put("dbtap_id",
                ((SqlNumericLiteral) rowList.get(i)).intValue(true));
          } else {
            throw new SQLException("Incorrect argument type to variable"
                + " 'dbtap_id'");
          }
          break;
        case "auth_token":
          dbSpecificColumns.put("auth_token", rowList.get(i).toString());
          break;
        default:
          throw new SQLException("Unknown parameter: " + ((SqlIdentifier) node).getSimple());
      }
      i++;
    }
  }

  Encrypt encrypt;
  if (Boolean.parseBoolean(info.getProperty("encrypt", "false"))) {
    encrypt = new AESEncrypt(info.getProperty("encryptionKey"));
  } else {
    encrypt = new NoopEncrypt();
  }

  if ((jdbcSourceDAO == null && quboleDbSourceDAO == null)
      || (jdbcSourceDAO != null && quboleDbSourceDAO != null)) {
    throw new RuntimeException("Need to pass exact values to create"
        + " data source of type jdbc or quboleDb");
  } else if (jdbcSourceDAO != null) {
    return dataSourceDAO.insertJDBC((String) sqlNode.getIdentifier().getSimple(),
        (String) commonColumns.get("type"),
        (String) commonColumns.get("url"),
        connection.getDSSet().getId(),
        (String) commonColumns.get("datasource_type"),
        jdbcSourceDAO,
        (String) dbSpecificColumns.get("username"),
        (dbSpecificColumns.get("password") == null) ? ""
            : (String) dbSpecificColumns.get("password"),
        encrypt);
  } else {
    return dataSourceDAO.insertQuboleDB((String) sqlNode.getIdentifier().getSimple(),
        (String) commonColumns.get("type"),
        (String) commonColumns.get("url"),
        connection.getDSSet().getId(),
        (String) commonColumns.get("datasource_type"),
        quboleDbSourceDAO,
        (int) dbSpecificColumns.get("dbtap_id"),
        (String) dbSpecificColumns.get("auth_token"),
        encrypt);
  }
}
 
Example 19
Source Project: quark   File: QuarkDDLExecutor.java    License: Apache License 2.0 4 votes vote down vote up
public int executeAlterView(SqlAlterQuarkView sqlNode) throws SQLException {
  DBI dbi = getDbi();
  ViewDAO viewDAO = dbi.onDemand(ViewDAO.class);

  View view = viewDAO.findByName(sqlNode.getIdentifier().getSimple(),
      connection.getDSSet().getId());
  if (view == null) {
    return 0;
  }

  SqlNodeList rowList = sqlNode.getSourceExpressionList();
  int i = 0;
  for (SqlNode node : sqlNode.getTargetColumnList()) {
    if (node instanceof SqlIdentifier) {
      switch (((SqlIdentifier) node).getSimple()) {
        case "name":
          view.setName(rowList.get(i).toString());
          break;
        case "description":
          view.setDescription(rowList.get(i).toString());
          break;
        case "query":
          view.setQuery(rowList.get(i).toString());
          break;
        case "schema_name":
          view.setSchema(rowList.get(i).toString());
          break;
        case "table_name":
          view.setTable(rowList.get(i).toString());
          break;
        case "ds_set_id":
          if (rowList.get(i) instanceof SqlNumericLiteral) {
            view.setDsSetId(((SqlNumericLiteral) rowList.get(i)).longValue(true));
          } else {
            throw new SQLException("Incorrect argument type to variable 'ds_set_id'");
          }
          break;
        case "cost":
          if (rowList.get(i) instanceof SqlNumericLiteral) {
            view.setCost(((SqlNumericLiteral) rowList.get(i)).longValue(true));
          } else {
            throw new SQLException("Incorrect argument type to variable 'cost'");
          }
          break;
        case "destination_id":
          if (rowList.get(i) instanceof SqlNumericLiteral) {
            view.setDestinationId(((SqlNumericLiteral) rowList.get(i)).longValue(true));
          } else {
            throw new SQLException("Incorrect argument type to variable 'destination_id'");
          }
          break;
        default:
          throw new SQLException("Unknown parameter: " + ((SqlIdentifier) node).getSimple());
      }
      i++;
    }
  }

  return viewDAO.update(view, connection.getDSSet().getId());
}
 
Example 20
Source Project: quark   File: RelToSqlConverter.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Once you have a Result of implementing a child relational expression,
 * call this method to create a Builder to implement the current relational
 * expression by adding additional clauses to the SQL query.
 * <p></p>
 * <p>You need to declare which clauses you intend to add. If the clauses
 * are "later", you can add to the same query. For example, "GROUP BY" comes
 * after "WHERE". But if they are the same or earlier, this method will
 * start a new SELECT that wraps the previous result.</p>
 * <p>When you have called
 * {@link Builder#setSelect(org.apache.calcite.sql.SqlNodeList)},
 * {@link Builder#setWhere(org.apache.calcite.sql.SqlNode)} etc. call
 * {@link Builder#result(org.apache.calcite.sql.SqlNode, java.util.Collection, org.apache.calcite.rel.RelNode)}
 * to fix the new query.</p>
 *
 * @param rel     Relational expression being implemented
 * @param clauses Clauses that will be generated to implement current
 *                relational expression
 * @return A builder
 */
public Builder builder(RelNode rel, Clause... clauses) {
  final Clause maxClause = maxClause();
  boolean needNew = false;
  for (Clause clause : clauses) {
    if (maxClause.ordinal() >= clause.ordinal()) {
      needNew = true;
    }
  }
  SqlSelect select;
  Expressions.FluentList<Clause> clauseList = Expressions.list();
  if (needNew) {
    select = subSelect();
  } else {
    select = asSelect();
    clauseList.addAll(this.clauses);
  }
  clauseList.appendAll(clauses);
  Context newContext;
  final SqlNodeList selectList = select.getSelectList();
  if (selectList != null) {
    newContext = new Context(selectList.size()) {

      @Override
      public SqlNode field(int ordinal) {
        return field(ordinal, false);
      }

      @Override
      public SqlNode field(int ordinal, boolean useAlias) {
        final SqlNode selectItem = selectList.get(ordinal);
        switch (selectItem.getKind()) {
          case AS:
            if (useAlias) {
              return ((SqlCall) selectItem).operand(1);
            } else {
              return ((SqlCall) selectItem).operand(0);
            }
        }
        return selectItem;
      }
    };
  } else {
    newContext = new AliasContext(aliases, aliases.size() > 1);
  }
  return new Builder(rel, clauseList, select, newContext);
}