Search in sources :

Example 6 with SqlWriterConfig

use of org.apache.calcite.sql.SqlWriterConfig in project calcite by apache.

the class PigConverter method pigToSql.

/**
 * Converts a Pig script to a list of SQL statements.
 *
 * @param pigQuery Pig script
 * @param sqlDialect Dialect of SQL language
 * @throws IOException Exception during parsing or translating Pig
 */
public List<String> pigToSql(String pigQuery, SqlDialect sqlDialect) throws IOException {
    final SqlWriterConfig config = SqlPrettyWriter.config().withQuoteAllIdentifiers(false).withAlwaysUseParentheses(false).withSelectListItemsOnSeparateLines(false).withIndentation(2).withDialect(sqlDialect);
    final SqlPrettyWriter writer = new SqlPrettyWriter(config);
    return pigToSql(pigQuery, writer);
}
Also used : SqlPrettyWriter(org.apache.calcite.sql.pretty.SqlPrettyWriter) SqlWriterConfig(org.apache.calcite.sql.SqlWriterConfig)

Example 7 with SqlWriterConfig

use of org.apache.calcite.sql.SqlWriterConfig in project calcite by apache.

the class ServerDdlExecutor method populate.

/**
 * Populates the table called {@code name} by executing {@code query}.
 */
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 StringBuilder buf = new StringBuilder();
        final SqlWriterConfig writerConfig = SqlPrettyWriter.config().withAlwaysUseParentheses(false);
        final SqlPrettyWriter w = new SqlPrettyWriter(writerConfig, buf);
        buf.append("INSERT INTO ");
        name.unparse(w, 0, 0);
        buf.append(' ');
        query.unparse(w, 0, 0);
        final String sql = buf.toString();
        final SqlNode query1 = planner.parse(sql);
        final SqlNode query2 = planner.validate(query1);
        final RelRoot r = planner.rel(query2);
        final PreparedStatement prepare = context.getRelRunner().prepareStatement(r.rel);
        int rowCount = prepare.executeUpdate();
        Util.discard(rowCount);
        prepare.close();
    } catch (SqlParseException | ValidationException | RelConversionException | SQLException e) {
        throw Util.throwAsRuntime(e);
    }
}
Also used : ValidationException(org.apache.calcite.tools.ValidationException) SqlParseException(org.apache.calcite.sql.parser.SqlParseException) SQLException(java.sql.SQLException) SqlWriterConfig(org.apache.calcite.sql.SqlWriterConfig) RelRoot(org.apache.calcite.rel.RelRoot) PreparedStatement(java.sql.PreparedStatement) NlsString(org.apache.calcite.util.NlsString) RelConversionException(org.apache.calcite.tools.RelConversionException) SqlPrettyWriter(org.apache.calcite.sql.pretty.SqlPrettyWriter) Planner(org.apache.calcite.tools.Planner) FrameworkConfig(org.apache.calcite.tools.FrameworkConfig) SqlNode(org.apache.calcite.sql.SqlNode)

Example 8 with SqlWriterConfig

use of org.apache.calcite.sql.SqlWriterConfig in project calcite by apache.

the class CassandraSchema method addMaterializedViews.

/**
 * Adds all materialized views defined in the schema to this column family.
 */
private void addMaterializedViews() {
    // Close the hook used to get us here
    hook.close();
    for (ViewMetadata view : getKeyspace().getViews().values()) {
        String tableName = view.getBaseTable().asInternal();
        StringBuilder queryBuilder = new StringBuilder("SELECT ");
        // Add all the selected columns to the query
        String columnsList = view.getColumns().values().stream().map(c -> c.getName().asInternal()).collect(Collectors.joining(", "));
        queryBuilder.append(columnsList);
        queryBuilder.append(" FROM ").append(tableName);
        // Get the where clause from the system schema
        String whereQuery = "SELECT where_clause from system_schema.views " + "WHERE keyspace_name='" + keyspace + "' AND view_name='" + view.getName().asInternal() + "'";
        Row whereClauseRow = Objects.requireNonNull(session.execute(whereQuery).one());
        queryBuilder.append(" WHERE ").append(whereClauseRow.getString(0));
        // Parse and unparse the view query to get properly quoted field names
        String query = queryBuilder.toString();
        SqlParser.Config parserConfig = SqlParser.config().withUnquotedCasing(Casing.UNCHANGED);
        SqlSelect parsedQuery;
        try {
            parsedQuery = (SqlSelect) SqlParser.create(query, parserConfig).parseQuery();
        } catch (SqlParseException e) {
            LOGGER.warn("Could not parse query {} for CQL view {}.{}", query, keyspace, view.getName().asInternal());
            continue;
        }
        final StringBuilder buf = new StringBuilder(query.length());
        final SqlWriterConfig config = SqlPrettyWriter.config().withAlwaysUseParentheses(true);
        final SqlWriter writer = new SqlPrettyWriter(config, buf);
        parsedQuery.unparse(writer, 0, 0);
        query = buf.toString();
        // Add the view for this query
        String viewName = "$" + getTableNames().size();
        SchemaPlus schema = parentSchema.getSubSchema(name);
        if (schema == null) {
            throw new IllegalStateException("Cannot find schema " + name + " in parent schema " + parentSchema.getName());
        }
        CalciteSchema calciteSchema = CalciteSchema.from(schema);
        List<String> viewPath = calciteSchema.path(viewName);
        schema.add(viewName, MaterializedViewTable.create(calciteSchema, query, null, viewPath, view.getName().asInternal(), true));
    }
}
Also used : RelDataTypeImpl(org.apache.calcite.rel.type.RelDataTypeImpl) IntStream(java.util.stream.IntStream) RelDataTypeFactory(org.apache.calcite.rel.type.RelDataTypeFactory) SqlWriterConfig(org.apache.calcite.sql.SqlWriterConfig) CqlIdentifier(com.datastax.oss.driver.api.core.CqlIdentifier) ListType(com.datastax.oss.driver.api.core.type.ListType) ClusteringOrder(com.datastax.oss.driver.api.core.metadata.schema.ClusteringOrder) ViewMetadata(com.datastax.oss.driver.api.core.metadata.schema.ViewMetadata) ArrayList(java.util.ArrayList) CqlSession(com.datastax.oss.driver.api.core.CqlSession) Pair(org.apache.calcite.util.Pair) Map(java.util.Map) AbstractSchema(org.apache.calcite.schema.impl.AbstractSchema) SqlSelect(org.apache.calcite.sql.SqlSelect) RelDataTypeSystem(org.apache.calcite.rel.type.RelDataTypeSystem) SqlTypeFactoryImpl(org.apache.calcite.sql.type.SqlTypeFactoryImpl) Row(com.datastax.oss.driver.api.core.cql.Row) RelDataType(org.apache.calcite.rel.type.RelDataType) TableMetadata(com.datastax.oss.driver.api.core.metadata.schema.TableMetadata) MaterializedViewTable(org.apache.calcite.schema.impl.MaterializedViewTable) RelationMetadata(com.datastax.oss.driver.api.core.metadata.schema.RelationMetadata) SchemaPlus(org.apache.calcite.schema.SchemaPlus) SqlWriter(org.apache.calcite.sql.SqlWriter) Logger(org.slf4j.Logger) CalciteSchema(org.apache.calcite.jdbc.CalciteSchema) SqlPrettyWriter(org.apache.calcite.sql.pretty.SqlPrettyWriter) SqlTypeName(org.apache.calcite.sql.type.SqlTypeName) MapType(com.datastax.oss.driver.api.core.type.MapType) ImmutableMap(com.google.common.collect.ImmutableMap) TupleType(com.datastax.oss.driver.api.core.type.TupleType) Collection(java.util.Collection) Casing(org.apache.calcite.avatica.util.Casing) DataType(com.datastax.oss.driver.api.core.type.DataType) Table(org.apache.calcite.schema.Table) RelFieldCollation(org.apache.calcite.rel.RelFieldCollation) RelProtoDataType(org.apache.calcite.rel.type.RelProtoDataType) Collectors(java.util.stream.Collectors) ColumnMetadata(com.datastax.oss.driver.api.core.metadata.schema.ColumnMetadata) Objects(java.util.Objects) KeyspaceMetadata(com.datastax.oss.driver.api.core.metadata.schema.KeyspaceMetadata) List(java.util.List) SqlParser(org.apache.calcite.sql.parser.SqlParser) CalciteTrace(org.apache.calcite.util.trace.CalciteTrace) Optional(java.util.Optional) SetType(com.datastax.oss.driver.api.core.type.SetType) SqlParseException(org.apache.calcite.sql.parser.SqlParseException) Hook(org.apache.calcite.runtime.Hook) SqlWriter(org.apache.calcite.sql.SqlWriter) SqlParseException(org.apache.calcite.sql.parser.SqlParseException) SqlParser(org.apache.calcite.sql.parser.SqlParser) SchemaPlus(org.apache.calcite.schema.SchemaPlus) SqlWriterConfig(org.apache.calcite.sql.SqlWriterConfig) SqlSelect(org.apache.calcite.sql.SqlSelect) CalciteSchema(org.apache.calcite.jdbc.CalciteSchema) SqlPrettyWriter(org.apache.calcite.sql.pretty.SqlPrettyWriter) Row(com.datastax.oss.driver.api.core.cql.Row) ViewMetadata(com.datastax.oss.driver.api.core.metadata.schema.ViewMetadata)

Aggregations

SqlWriterConfig (org.apache.calcite.sql.SqlWriterConfig)8 SqlPrettyWriter (org.apache.calcite.sql.pretty.SqlPrettyWriter)7 SqlNode (org.apache.calcite.sql.SqlNode)3 ImmutableMap (com.google.common.collect.ImmutableMap)2 Collection (java.util.Collection)2 List (java.util.List)2 Map (java.util.Map)2 Collectors (java.util.stream.Collectors)2 IntStream (java.util.stream.IntStream)2 SqlCall (org.apache.calcite.sql.SqlCall)2 SqlDialect (org.apache.calcite.sql.SqlDialect)2 SqlSelect (org.apache.calcite.sql.SqlSelect)2 AnsiSqlDialect (org.apache.calcite.sql.dialect.AnsiSqlDialect)2 SqlParseException (org.apache.calcite.sql.parser.SqlParseException)2 CqlIdentifier (com.datastax.oss.driver.api.core.CqlIdentifier)1 CqlSession (com.datastax.oss.driver.api.core.CqlSession)1 Row (com.datastax.oss.driver.api.core.cql.Row)1 ClusteringOrder (com.datastax.oss.driver.api.core.metadata.schema.ClusteringOrder)1 ColumnMetadata (com.datastax.oss.driver.api.core.metadata.schema.ColumnMetadata)1 KeyspaceMetadata (com.datastax.oss.driver.api.core.metadata.schema.KeyspaceMetadata)1