Search in sources :

Example 6 with SqlValidator

use of org.apache.calcite.sql.validate.SqlValidator in project calcite by apache.

the class CalcitePrepareImpl method prepare2_.

<T> CalciteSignature<T> prepare2_(Context context, Query<T> query, Type elementType, long maxRowCount, CalciteCatalogReader catalogReader, RelOptPlanner planner) {
    final JavaTypeFactory typeFactory = context.getTypeFactory();
    final EnumerableRel.Prefer prefer;
    if (elementType == Object[].class) {
        prefer = EnumerableRel.Prefer.ARRAY;
    } else {
        prefer = EnumerableRel.Prefer.CUSTOM;
    }
    final Convention resultConvention = enableBindable ? BindableConvention.INSTANCE : EnumerableConvention.INSTANCE;
    final CalcitePreparingStmt preparingStmt = new CalcitePreparingStmt(this, context, catalogReader, typeFactory, context.getRootSchema(), prefer, planner, resultConvention, createConvertletTable());
    final RelDataType x;
    final Prepare.PreparedResult preparedResult;
    final Meta.StatementType statementType;
    if (query.sql != null) {
        final CalciteConnectionConfig config = context.config();
        final SqlParser.ConfigBuilder parserConfig = createParserConfig().setQuotedCasing(config.quotedCasing()).setUnquotedCasing(config.unquotedCasing()).setQuoting(config.quoting()).setConformance(config.conformance()).setCaseSensitive(config.caseSensitive());
        final SqlParserImplFactory parserFactory = config.parserFactory(SqlParserImplFactory.class, null);
        if (parserFactory != null) {
            parserConfig.setParserFactory(parserFactory);
        }
        SqlParser parser = createParser(query.sql, parserConfig);
        SqlNode sqlNode;
        try {
            sqlNode = parser.parseStmt();
            statementType = getStatementType(sqlNode.getKind());
        } catch (SqlParseException e) {
            throw new RuntimeException("parse failed: " + e.getMessage(), e);
        }
        Hook.PARSE_TREE.run(new Object[] { query.sql, sqlNode });
        if (sqlNode.getKind().belongsTo(SqlKind.DDL)) {
            executeDdl(context, sqlNode);
            return new CalciteSignature<>(query.sql, ImmutableList.<AvaticaParameter>of(), ImmutableMap.<String, Object>of(), null, ImmutableList.<ColumnMetaData>of(), Meta.CursorFactory.OBJECT, null, ImmutableList.<RelCollation>of(), -1, null, Meta.StatementType.OTHER_DDL);
        }
        final SqlValidator validator = createSqlValidator(context, catalogReader);
        validator.setIdentifierExpansion(true);
        validator.setDefaultNullCollation(config.defaultNullCollation());
        preparedResult = preparingStmt.prepareSql(sqlNode, Object.class, validator, true);
        switch(sqlNode.getKind()) {
            case INSERT:
            case DELETE:
            case UPDATE:
            case EXPLAIN:
                // FIXME: getValidatedNodeType is wrong for DML
                x = RelOptUtil.createDmlRowType(sqlNode.getKind(), typeFactory);
                break;
            default:
                x = validator.getValidatedNodeType(sqlNode);
        }
    } else if (query.queryable != null) {
        x = context.getTypeFactory().createType(elementType);
        preparedResult = preparingStmt.prepareQueryable(query.queryable, x);
        statementType = getStatementType(preparedResult);
    } else {
        assert query.rel != null;
        x = query.rel.getRowType();
        preparedResult = preparingStmt.prepareRel(query.rel);
        statementType = getStatementType(preparedResult);
    }
    final List<AvaticaParameter> parameters = new ArrayList<>();
    final RelDataType parameterRowType = preparedResult.getParameterRowType();
    for (RelDataTypeField field : parameterRowType.getFieldList()) {
        RelDataType type = field.getType();
        parameters.add(new AvaticaParameter(false, getPrecision(type), getScale(type), getTypeOrdinal(type), getTypeName(type), getClassName(type), field.getName()));
    }
    RelDataType jdbcType = makeStruct(typeFactory, x);
    final List<List<String>> originList = preparedResult.getFieldOrigins();
    final List<ColumnMetaData> columns = getColumnMetaDataList(typeFactory, x, jdbcType, originList);
    Class resultClazz = null;
    if (preparedResult instanceof Typed) {
        resultClazz = (Class) ((Typed) preparedResult).getElementType();
    }
    final Meta.CursorFactory cursorFactory = preparingStmt.resultConvention == BindableConvention.INSTANCE ? Meta.CursorFactory.ARRAY : Meta.CursorFactory.deduce(columns, resultClazz);
    // noinspection unchecked
    final Bindable<T> bindable = preparedResult.getBindable(cursorFactory);
    return new CalciteSignature<>(query.sql, parameters, preparingStmt.internalParameters, jdbcType, columns, cursorFactory, context.getRootSchema(), preparedResult instanceof Prepare.PreparedResultImpl ? ((Prepare.PreparedResultImpl) preparedResult).collations : ImmutableList.<RelCollation>of(), maxRowCount, bindable, statementType);
}
Also used : Meta(org.apache.calcite.avatica.Meta) ArrayList(java.util.ArrayList) RelDataType(org.apache.calcite.rel.type.RelDataType) AvaticaParameter(org.apache.calcite.avatica.AvaticaParameter) Typed(org.apache.calcite.runtime.Typed) SqlValidator(org.apache.calcite.sql.validate.SqlValidator) JavaTypeFactory(org.apache.calcite.adapter.java.JavaTypeFactory) CalcitePrepare(org.apache.calcite.jdbc.CalcitePrepare) SqlParserImplFactory(org.apache.calcite.sql.parser.SqlParserImplFactory) ArrayList(java.util.ArrayList) ImmutableIntList(org.apache.calcite.util.ImmutableIntList) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) ColumnMetaData(org.apache.calcite.avatica.ColumnMetaData) EnumerableRel(org.apache.calcite.adapter.enumerable.EnumerableRel) SqlNode(org.apache.calcite.sql.SqlNode) SqlParseException(org.apache.calcite.sql.parser.SqlParseException) CalciteConnectionConfig(org.apache.calcite.config.CalciteConnectionConfig) SqlParser(org.apache.calcite.sql.parser.SqlParser) BindableConvention(org.apache.calcite.interpreter.BindableConvention) Convention(org.apache.calcite.plan.Convention) EnumerableConvention(org.apache.calcite.adapter.enumerable.EnumerableConvention) RelDataTypeField(org.apache.calcite.rel.type.RelDataTypeField) RelCollation(org.apache.calcite.rel.RelCollation)

Example 7 with SqlValidator

use of org.apache.calcite.sql.validate.SqlValidator in project calcite by apache.

the class SetopOperandTypeChecker method checkOperandTypes.

public boolean checkOperandTypes(SqlCallBinding callBinding, boolean throwOnFailure) {
    assert callBinding.getOperandCount() == 2 : "setops are binary (for now)";
    final RelDataType[] argTypes = new RelDataType[callBinding.getOperandCount()];
    int colCount = -1;
    final SqlValidator validator = callBinding.getValidator();
    for (int i = 0; i < argTypes.length; i++) {
        final RelDataType argType = argTypes[i] = callBinding.getOperandType(i);
        if (!argType.isStruct()) {
            if (throwOnFailure) {
                throw new AssertionError("setop arg must be a struct");
            } else {
                return false;
            }
        }
        // Each operand must have the same number of columns.
        final List<RelDataTypeField> fields = argType.getFieldList();
        if (i == 0) {
            colCount = fields.size();
            continue;
        }
        if (fields.size() != colCount) {
            if (throwOnFailure) {
                SqlNode node = callBinding.operand(i);
                if (node instanceof SqlSelect) {
                    node = ((SqlSelect) node).getSelectList();
                }
                throw validator.newValidationError(node, RESOURCE.columnCountMismatchInSetop(callBinding.getOperator().getName()));
            } else {
                return false;
            }
        }
    }
    // column j.
    for (int i = 0; i < colCount; i++) {
        final int i2 = i;
        final RelDataType type = callBinding.getTypeFactory().leastRestrictive(new AbstractList<RelDataType>() {

            public RelDataType get(int index) {
                return argTypes[index].getFieldList().get(i2).getType();
            }

            public int size() {
                return argTypes.length;
            }
        });
        if (type == null) {
            if (throwOnFailure) {
                SqlNode field = SqlUtil.getSelectListItem(callBinding.operand(0), i);
                throw validator.newValidationError(field, // 1-based
                RESOURCE.columnTypeMismatchInSetop(// 1-based
                i + 1, callBinding.getOperator().getName()));
            } else {
                return false;
            }
        }
    }
    return true;
}
Also used : RelDataTypeField(org.apache.calcite.rel.type.RelDataTypeField) SqlSelect(org.apache.calcite.sql.SqlSelect) SqlValidator(org.apache.calcite.sql.validate.SqlValidator) RelDataType(org.apache.calcite.rel.type.RelDataType) SqlNode(org.apache.calcite.sql.SqlNode)

Example 8 with SqlValidator

use of org.apache.calcite.sql.validate.SqlValidator in project calcite by apache.

the class SqlValidatorTest method testRewriteWithoutIdentifierExpansion.

@Test
public void testRewriteWithoutIdentifierExpansion() {
    SqlValidator validator = tester.getValidator();
    validator.setIdentifierExpansion(false);
    tester.checkRewrite(validator, "select * from dept", "SELECT *\n" + "FROM `DEPT`");
}
Also used : SqlValidator(org.apache.calcite.sql.validate.SqlValidator) Test(org.junit.Test)

Example 9 with SqlValidator

use of org.apache.calcite.sql.validate.SqlValidator in project calcite by apache.

the class SqlValidatorTest method testRewriteWithIdentifierExpansion.

@Test
public void testRewriteWithIdentifierExpansion() {
    SqlValidator validator = tester.getValidator();
    validator.setIdentifierExpansion(true);
    tester.checkRewrite(validator, "select * from dept", "SELECT `DEPT`.`DEPTNO`, `DEPT`.`NAME`\n" + "FROM `CATALOG`.`SALES`.`DEPT` AS `DEPT`");
}
Also used : SqlValidator(org.apache.calcite.sql.validate.SqlValidator) Test(org.junit.Test)

Example 10 with SqlValidator

use of org.apache.calcite.sql.validate.SqlValidator in project calcite by apache.

the class SqlValidatorTest method testCoalesceWithoutRewrite.

@Test
public void testCoalesceWithoutRewrite() {
    SqlValidator validator = tester.getValidator();
    validator.setCallRewrite(false);
    if (validator.shouldExpandIdentifiers()) {
        tester.checkRewrite(validator, "select coalesce(deptno, empno) from emp", "SELECT COALESCE(`EMP`.`DEPTNO`, `EMP`.`EMPNO`)\n" + "FROM `CATALOG`.`SALES`.`EMP` AS `EMP`");
    } else {
        tester.checkRewrite(validator, "select coalesce(deptno, empno) from emp", "SELECT COALESCE(`DEPTNO`, `EMPNO`)\n" + "FROM `EMP`");
    }
}
Also used : SqlValidator(org.apache.calcite.sql.validate.SqlValidator) Test(org.junit.Test)

Aggregations

SqlValidator (org.apache.calcite.sql.validate.SqlValidator)31 SqlNode (org.apache.calcite.sql.SqlNode)17 Test (org.junit.Test)11 RelDataType (org.apache.calcite.rel.type.RelDataType)8 RelDataTypeField (org.apache.calcite.rel.type.RelDataTypeField)4 SqlValidatorScope (org.apache.calcite.sql.validate.SqlValidatorScope)4 ImmutableList (com.google.common.collect.ImmutableList)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 RelDataTypeFactory (org.apache.calcite.rel.type.RelDataTypeFactory)3 SqlCall (org.apache.calcite.sql.SqlCall)3 SqlParseException (org.apache.calcite.sql.parser.SqlParseException)3 JavaTypeFactory (org.apache.calcite.adapter.java.JavaTypeFactory)2 RelRoot (org.apache.calcite.rel.RelRoot)2 SqlIdentifier (org.apache.calcite.sql.SqlIdentifier)2 SqlIntervalLiteral (org.apache.calcite.sql.SqlIntervalLiteral)2 SqlSelect (org.apache.calcite.sql.SqlSelect)2 SqlParser (org.apache.calcite.sql.parser.SqlParser)2 RESOURCE (com.hazelcast.jet.sql.impl.parse.ParserResource.RESOURCE)1 HazelcastTable (com.hazelcast.jet.sql.impl.schema.HazelcastTable)1