Search in sources :

Example 1 with SqlPrettyWriter

use of org.apache.calcite.sql.pretty.SqlPrettyWriter in project calcite by apache.

the class JdbcTable method generateSql.

SqlString generateSql() {
    final SqlNodeList selectList = new SqlNodeList(Collections.singletonList(SqlIdentifier.star(SqlParserPos.ZERO)), SqlParserPos.ZERO);
    SqlSelect node = new SqlSelect(SqlParserPos.ZERO, SqlNodeList.EMPTY, selectList, tableName(), null, null, null, null, null, null, null);
    final SqlPrettyWriter writer = new SqlPrettyWriter(jdbcSchema.dialect);
    node.unparse(writer, 0, 0);
    return writer.toSqlString();
}
Also used : SqlSelect(org.apache.calcite.sql.SqlSelect) SqlPrettyWriter(org.apache.calcite.sql.pretty.SqlPrettyWriter) SqlNodeList(org.apache.calcite.sql.SqlNodeList)

Example 2 with SqlPrettyWriter

use of org.apache.calcite.sql.pretty.SqlPrettyWriter in project calcite by apache.

the class SqlPrettyWriterTest method testDefault.

@Test
public void testDefault() throws Exception {
    final SqlPrettyWriter prettyWriter = new SqlPrettyWriter(AnsiSqlDialect.DEFAULT);
    checkSimple(prettyWriter, "${desc}", "${formatted}");
}
Also used : SqlPrettyWriter(org.apache.calcite.sql.pretty.SqlPrettyWriter) Test(org.junit.Test)

Example 3 with SqlPrettyWriter

use of org.apache.calcite.sql.pretty.SqlPrettyWriter in project calcite by apache.

the class SqlOperatorBaseTest method testArgumentBounds.

/**
 * Test that calls all operators with all possible argument types, and for
 * each type, with a set of tricky values.
 */
@Test
public void testArgumentBounds() {
    if (!CalciteAssert.ENABLE_SLOW) {
        return;
    }
    final SqlValidatorImpl validator = (SqlValidatorImpl) tester.getValidator();
    final SqlValidatorScope scope = validator.getEmptyScope();
    final RelDataTypeFactory typeFactory = validator.getTypeFactory();
    final Builder builder = new Builder(typeFactory);
    builder.add0(SqlTypeName.BOOLEAN, true, false);
    builder.add0(SqlTypeName.TINYINT, 0, 1, -3, Byte.MAX_VALUE, Byte.MIN_VALUE);
    builder.add0(SqlTypeName.SMALLINT, 0, 1, -4, Short.MAX_VALUE, Short.MIN_VALUE);
    builder.add0(SqlTypeName.INTEGER, 0, 1, -2, Integer.MIN_VALUE, Integer.MAX_VALUE);
    builder.add0(SqlTypeName.BIGINT, 0, 1, -5, Integer.MAX_VALUE, Long.MAX_VALUE, Long.MIN_VALUE);
    builder.add1(SqlTypeName.VARCHAR, 11, "", " ", "hello world");
    builder.add1(SqlTypeName.CHAR, 5, "", "e", "hello");
    builder.add0(SqlTypeName.TIMESTAMP, 0L, DateTimeUtils.MILLIS_PER_DAY);
    for (SqlOperator op : SqlStdOperatorTable.instance().getOperatorList()) {
        switch(op.getKind()) {
            // can't handle the flag argument
            case TRIM:
            case EXISTS:
                continue;
        }
        switch(op.getSyntax()) {
            case SPECIAL:
                continue;
        }
        final SqlOperandTypeChecker typeChecker = op.getOperandTypeChecker();
        if (typeChecker == null) {
            continue;
        }
        final SqlOperandCountRange range = typeChecker.getOperandCountRange();
        for (int n = range.getMin(), max = range.getMax(); n <= max; n++) {
            final List<List<ValueType>> argValues = Collections.nCopies(n, builder.values);
            for (final List<ValueType> args : Linq4j.product(argValues)) {
                SqlNodeList nodeList = new SqlNodeList(SqlParserPos.ZERO);
                int nullCount = 0;
                for (ValueType arg : args) {
                    if (arg.value == null) {
                        ++nullCount;
                    }
                    nodeList.add(arg.node);
                }
                final SqlCall call = op.createCall(nodeList);
                final SqlCallBinding binding = new SqlCallBinding(validator, scope, call);
                if (!typeChecker.checkOperandTypes(binding, false)) {
                    continue;
                }
                final SqlPrettyWriter writer = new SqlPrettyWriter(CalciteSqlDialect.DEFAULT);
                op.unparse(writer, call, 0, 0);
                final String s = writer.toSqlString().toString();
                if (s.startsWith("OVERLAY(") || s.contains(" / 0") || s.matches("MOD\\(.*, 0\\)")) {
                    continue;
                }
                final Strong.Policy policy = Strong.policy(op.kind);
                try {
                    if (nullCount > 0 && policy == Strong.Policy.ANY) {
                        tester.checkNull(s);
                    } else {
                        final String query;
                        if (op instanceof SqlAggFunction) {
                            if (op.requiresOrder()) {
                                query = "SELECT " + s + " OVER () FROM (VALUES (1))";
                            } else {
                                query = "SELECT " + s + " FROM (VALUES (1))";
                            }
                        } else {
                            query = SqlTesterImpl.buildQuery(s);
                        }
                        tester.check(query, SqlTests.ANY_TYPE_CHECKER, SqlTests.ANY_PARAMETER_CHECKER, SqlTests.ANY_RESULT_CHECKER);
                    }
                } catch (Error e) {
                    System.out.println(s + ": " + e.getMessage());
                    throw e;
                } catch (Exception e) {
                    System.out.println("Failed: " + s + ": " + e.getMessage());
                }
            }
        }
    }
}
Also used : SqlValidatorScope(org.apache.calcite.sql.validate.SqlValidatorScope) SqlOperator(org.apache.calcite.sql.SqlOperator) SqlCall(org.apache.calcite.sql.SqlCall) TimestampString(org.apache.calcite.util.TimestampString) SqlString(org.apache.calcite.sql.util.SqlString) SqlAggFunction(org.apache.calcite.sql.SqlAggFunction) Strong(org.apache.calcite.plan.Strong) SQLException(java.sql.SQLException) SqlOperandCountRange(org.apache.calcite.sql.SqlOperandCountRange) SqlValidatorImpl(org.apache.calcite.sql.validate.SqlValidatorImpl) RelDataTypeFactory(org.apache.calcite.rel.type.RelDataTypeFactory) SqlCallBinding(org.apache.calcite.sql.SqlCallBinding) SqlPrettyWriter(org.apache.calcite.sql.pretty.SqlPrettyWriter) SqlNodeList(org.apache.calcite.sql.SqlNodeList) SqlOperandTypeChecker(org.apache.calcite.sql.type.SqlOperandTypeChecker) List(java.util.List) ArrayList(java.util.ArrayList) SqlNodeList(org.apache.calcite.sql.SqlNodeList) SqlLimitsTest(org.apache.calcite.test.SqlLimitsTest) Test(org.junit.Test)

Example 4 with SqlPrettyWriter

use of org.apache.calcite.sql.pretty.SqlPrettyWriter in project calcite by apache.

the class SqlDdlNodes method populate.

/**
 * Populates the table called {@code name} by executing {@code query}.
 */
protected static void populate(SqlIdentifier name, SqlNode query, CalcitePrepare.Context context) {
    // Generate, prepare and execute an "INSERT INTO table query" statement.
    // (It's a bit inefficient that we convert from SqlNode to SQL and back
    // again.)
    final FrameworkConfig config = Frameworks.newConfigBuilder().defaultSchema(context.getRootSchema().plus()).build();
    final Planner planner = Frameworks.getPlanner(config);
    try {
        final StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw);
        final SqlPrettyWriter w = new SqlPrettyWriter(CalciteSqlDialect.DEFAULT, false, pw);
        pw.print("INSERT INTO ");
        name.unparse(w, 0, 0);
        pw.print(" ");
        query.unparse(w, 0, 0);
        pw.flush();
        final String sql = sw.toString();
        final SqlNode query1 = planner.parse(sql);
        final SqlNode query2 = planner.validate(query1);
        final RelRoot r = planner.rel(query2);
        final PreparedStatement prepare = context.getRelRunner().prepare(r.rel);
        int rowCount = prepare.executeUpdate();
        Util.discard(rowCount);
        prepare.close();
    } catch (SqlParseException | ValidationException | RelConversionException | SQLException e) {
        throw new RuntimeException(e);
    }
}
Also used : ValidationException(org.apache.calcite.tools.ValidationException) SqlParseException(org.apache.calcite.sql.parser.SqlParseException) SQLException(java.sql.SQLException) RelRoot(org.apache.calcite.rel.RelRoot) PreparedStatement(java.sql.PreparedStatement) RelConversionException(org.apache.calcite.tools.RelConversionException) StringWriter(java.io.StringWriter) SqlPrettyWriter(org.apache.calcite.sql.pretty.SqlPrettyWriter) Planner(org.apache.calcite.tools.Planner) FrameworkConfig(org.apache.calcite.tools.FrameworkConfig) PrintWriter(java.io.PrintWriter) SqlNode(org.apache.calcite.sql.SqlNode)

Example 5 with SqlPrettyWriter

use of org.apache.calcite.sql.pretty.SqlPrettyWriter in project calcite by apache.

the class IntervalSqlType method generateTypeString.

// ~ Methods ----------------------------------------------------------------
protected void generateTypeString(StringBuilder sb, boolean withDetail) {
    sb.append("INTERVAL ");
    final SqlDialect dialect = AnsiSqlDialect.DEFAULT;
    final SqlPrettyWriter writer = new SqlPrettyWriter(dialect);
    writer.setAlwaysUseParentheses(false);
    writer.setSelectListItemsOnSeparateLines(false);
    writer.setIndentation(0);
    intervalQualifier.unparse(writer, 0, 0);
    final String sql = writer.toString();
    sb.append(new SqlString(dialect, sql).getSql());
}
Also used : SqlPrettyWriter(org.apache.calcite.sql.pretty.SqlPrettyWriter) AnsiSqlDialect(org.apache.calcite.sql.dialect.AnsiSqlDialect) SqlDialect(org.apache.calcite.sql.SqlDialect) SqlString(org.apache.calcite.sql.util.SqlString) SqlString(org.apache.calcite.sql.util.SqlString)

Aggregations

SqlPrettyWriter (org.apache.calcite.sql.pretty.SqlPrettyWriter)22 Test (org.junit.Test)13 SqlNode (org.apache.calcite.sql.SqlNode)7 PrintWriter (java.io.PrintWriter)3 StringWriter (java.io.StringWriter)3 SqlString (org.apache.calcite.sql.util.SqlString)3 SQLException (java.sql.SQLException)2 ArrayList (java.util.ArrayList)2 SqlIdentifier (org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.sql.SqlIdentifier)2 SqlNode (org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.sql.SqlNode)2 SqlWriter (org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.sql.SqlWriter)2 SqlPrettyWriter (org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.sql.pretty.SqlPrettyWriter)2 SqlCall (org.apache.calcite.sql.SqlCall)2 SqlNodeList (org.apache.calcite.sql.SqlNodeList)2 SqlSelect (org.apache.calcite.sql.SqlSelect)2 SqlWriter (org.apache.calcite.sql.SqlWriter)2 SqlParseException (org.apache.calcite.sql.parser.SqlParseException)2 ColumnMetadata (com.datastax.driver.core.ColumnMetadata)1 MaterializedViewMetadata (com.datastax.driver.core.MaterializedViewMetadata)1 MappingField (com.hazelcast.sql.impl.schema.MappingField)1