org.apache.calcite.sql.dialect.CalciteSqlDialect Java Examples

The following examples show how to use org.apache.calcite.sql.dialect.CalciteSqlDialect. 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 File: ServerDdlExecutor.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Executes a {@code CREATE VIEW} command. */
public void execute(SqlCreateView create,
    CalcitePrepare.Context context) {
  final Pair<CalciteSchema, String> pair =
      schema(context, true, create.name);
  final SchemaPlus schemaPlus = pair.left.plus();
  for (Function function : schemaPlus.getFunctions(pair.right)) {
    if (function.getParameters().isEmpty()) {
      if (!create.getReplace()) {
        throw SqlUtil.newContextException(create.name.getParserPosition(),
            RESOURCE.viewExists(pair.right));
      }
      pair.left.removeFunction(pair.right);
    }
  }
  final SqlNode q = renameColumns(create.columnList, create.query);
  final String sql = q.toSqlString(CalciteSqlDialect.DEFAULT).getSql();
  final ViewTableMacro viewTableMacro =
      ViewTable.viewMacro(schemaPlus, sql, pair.left.path(null),
          context.getObjectPath(), false);
  final TranslatableTable x = viewTableMacro.apply(ImmutableList.of());
  Util.discard(x);
  schemaPlus.add(pair.right, viewTableMacro);
}
 
Example #2
Source File: ExtensionDdlExecutor.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** 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(
          Objects.requireNonNull(
              Schemas.subSchema(context.getRootSchema(),
                  context.getDefaultSchemaPath())).plus())
      .build();
  final Planner planner = Frameworks.getPlanner(config);
  try {
    final StringBuilder buf = new StringBuilder();
    final SqlPrettyWriter w =
        new SqlPrettyWriter(
            SqlPrettyWriter.config()
                .withDialect(CalciteSqlDialect.DEFAULT)
                .withAlwaysUseParentheses(false),
            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().prepare(r.rel);
    int rowCount = prepare.executeUpdate();
    Util.discard(rowCount);
    prepare.close();
  } catch (SqlParseException | ValidationException
      | RelConversionException | SQLException e) {
    throw new RuntimeException(e);
  }
}
 
Example #3
Source File: Smalls.java    From calcite with Apache License 2.0 5 votes vote down vote up
public static TranslatableTable str(Object o, Object p) {
  assertThat(RexLiteral.validConstant(o, Litmus.THROW), is(true));
  assertThat(RexLiteral.validConstant(p, Litmus.THROW), is(true));
  return new ViewTable(Object.class, typeFactory ->
      typeFactory.builder().add("c", SqlTypeName.VARCHAR, 100).build(),
      "values " + CalciteSqlDialect.DEFAULT.quoteStringLiteral(o.toString())
          + ", " + CalciteSqlDialect.DEFAULT.quoteStringLiteral(p.toString()),
      ImmutableList.of(), Arrays.asList("view"));
}
 
Example #4
Source File: UtilTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Tests SQL builders.
 */
@Test void testSqlBuilder() {
  final SqlBuilder buf = new SqlBuilder(CalciteSqlDialect.DEFAULT);
  assertEquals(0, buf.length());
  buf.append("select ");
  assertEquals("select ", buf.getSql());

  buf.identifier("x");
  assertEquals("select \"x\"", buf.getSql());

  buf.append(", ");
  buf.identifier("y", "a b");
  assertEquals("select \"x\", \"y\".\"a b\"", buf.getSql());

  final SqlString sqlString = buf.toSqlString();
  assertEquals(CalciteSqlDialect.DEFAULT, sqlString.getDialect());
  assertEquals(buf.getSql(), sqlString.getSql());

  assertTrue(buf.getSql().length() > 0);
  assertEquals(buf.getSqlAndClear(), sqlString.getSql());
  assertEquals(0, buf.length());

  buf.clear();
  assertEquals(0, buf.length());

  buf.literal("can't get no satisfaction");
  assertEquals("'can''t get no satisfaction'", buf.getSqlAndClear());

  buf.literal(new Timestamp(0));
  assertEquals("TIMESTAMP '1970-01-01 00:00:00'", buf.getSqlAndClear());

  buf.clear();
  assertEquals(0, buf.length());

  buf.append("hello world");
  assertEquals(2, buf.indexOf("l"));
  assertEquals(-1, buf.indexOf("z"));
  assertEquals(9, buf.indexOf("l", 5));
}
 
Example #5
Source File: ServerDdlExecutor.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Executes a {@code CREATE MATERIALIZED VIEW} command. */
public void execute(SqlCreateMaterializedView create,
    CalcitePrepare.Context context) {
  final Pair<CalciteSchema, String> pair = schema(context, true, create.name);
  if (pair.left.plus().getTable(pair.right) != null) {
    // Materialized view exists.
    if (!create.ifNotExists) {
      // They did not specify IF NOT EXISTS, so give error.
      throw SqlUtil.newContextException(create.name.getParserPosition(),
          RESOURCE.tableExists(pair.right));
    }
    return;
  }
  final SqlNode q = renameColumns(create.columnList, create.query);
  final String sql = q.toSqlString(CalciteSqlDialect.DEFAULT).getSql();
  final List<String> schemaPath = pair.left.path(null);
  final ViewTableMacro viewTableMacro =
      ViewTable.viewMacro(pair.left.plus(), sql, schemaPath,
          context.getObjectPath(), false);
  final TranslatableTable x = viewTableMacro.apply(ImmutableList.of());
  final RelDataType rowType = x.getRowType(context.getTypeFactory());

  // Table does not exist. Create it.
  final MaterializedViewTable table =
      new MaterializedViewTable(pair.right, RelDataTypeImpl.proto(rowType));
  pair.left.add(pair.right, table);
  populate(create.name, create.query, context);
  table.key =
      MaterializationService.instance().defineMaterialization(pair.left, null,
          sql, schemaPath, pair.right, true, true);
}
 
Example #6
Source File: FlinkDDLDataTypeTest.java    From flink with Apache License 2.0 5 votes vote down vote up
public SqlDialect createSqlDialect() {
	return new CalciteSqlDialect(SqlDialect.EMPTY_CONTEXT
		.withQuotedCasing(parserConfig.unquotedCasing())
		.withConformance(parserConfig.conformance())
		.withUnquotedCasing(parserConfig.unquotedCasing())
		.withIdentifierQuoteString(parserConfig.quoting().string));
}
 
Example #7
Source File: SqlToOperationConverter.java    From flink with Apache License 2.0 5 votes vote down vote up
private String getQuotedSqlString(SqlNode sqlNode) {
	SqlParser.Config parserConfig = flinkPlanner.config().getParserConfig();
	SqlDialect dialect = new CalciteSqlDialect(SqlDialect.EMPTY_CONTEXT
		.withQuotedCasing(parserConfig.unquotedCasing())
		.withConformance(parserConfig.conformance())
		.withUnquotedCasing(parserConfig.unquotedCasing())
		.withIdentifierQuoteString(parserConfig.quoting().string));
	return sqlNode.toSqlString(dialect).getSql();
}
 
Example #8
Source File: SqlToOperationConverter.java    From flink with Apache License 2.0 5 votes vote down vote up
private String getQuotedSqlString(SqlNode sqlNode) {
	SqlParser.Config parserConfig = flinkPlanner.config().getParserConfig();
	SqlDialect dialect = new CalciteSqlDialect(SqlDialect.EMPTY_CONTEXT
		.withQuotedCasing(parserConfig.unquotedCasing())
		.withConformance(parserConfig.conformance())
		.withUnquotedCasing(parserConfig.unquotedCasing())
		.withIdentifierQuoteString(parserConfig.quoting().string));
	return sqlNode.toSqlString(dialect).getSql();
}
 
Example #9
Source File: SqlToOperationConverter.java    From flink with Apache License 2.0 5 votes vote down vote up
/** convert ALTER TABLE statement. */
private Operation convertAlterTable(SqlAlterTable sqlAlterTable) {
	UnresolvedIdentifier unresolvedIdentifier = UnresolvedIdentifier.of(sqlAlterTable.fullTableName());
	ObjectIdentifier tableIdentifier = catalogManager.qualifyIdentifier(unresolvedIdentifier);
	if (sqlAlterTable instanceof SqlAlterTableRename) {
		UnresolvedIdentifier newUnresolvedIdentifier =
			UnresolvedIdentifier.of(((SqlAlterTableRename) sqlAlterTable).fullNewTableName());
		ObjectIdentifier newTableIdentifier = catalogManager.qualifyIdentifier(newUnresolvedIdentifier);
		return new AlterTableRenameOperation(tableIdentifier, newTableIdentifier);
	} else if (sqlAlterTable instanceof SqlAlterTableProperties) {
		Optional<CatalogManager.TableLookupResult> optionalCatalogTable = catalogManager.getTable(tableIdentifier);
		if (optionalCatalogTable.isPresent() && !optionalCatalogTable.get().isTemporary()) {
			CatalogTable originalCatalogTable = (CatalogTable) optionalCatalogTable.get().getTable();
			Map<String, String> properties = new HashMap<>();
			properties.putAll(originalCatalogTable.getProperties());
			((SqlAlterTableProperties) sqlAlterTable).getPropertyList().getList().forEach(p ->
				properties.put(((SqlTableOption) p).getKeyString(), ((SqlTableOption) p).getValueString()));
			CatalogTable catalogTable = new CatalogTableImpl(
				originalCatalogTable.getSchema(),
				originalCatalogTable.getPartitionKeys(),
				properties,
				originalCatalogTable.getComment());
			return new AlterTablePropertiesOperation(tableIdentifier, catalogTable);
		} else {
			throw new ValidationException(String.format("Table %s doesn't exist or is a temporary table.",
				tableIdentifier.toString()));
		}
	} else {
		throw new ValidationException(
				String.format("[%s] needs to implement",
						sqlAlterTable.toSqlString(CalciteSqlDialect.DEFAULT)));
	}
}
 
Example #10
Source File: TestSQLConverter.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Test
public void testPassSemicolon() {
  ParserConfig config = new ParserConfig(ParserConfig.QUOTING, 100);
  SqlNode node = SqlConverter.parseSingleStatementImpl("select * from t1;", config, false);
  assertEquals("SELECT *\n" +
    "FROM \"t1\"", node.toSqlString(CalciteSqlDialect.DEFAULT).getSql());
}
 
Example #11
Source File: FlinkDDLDataTypeTest.java    From flink with Apache License 2.0 5 votes vote down vote up
private SqlDialect getSqlDialect() {
	return new CalciteSqlDialect(SqlDialect.EMPTY_CONTEXT
		.withQuotedCasing(Casing.UNCHANGED)
		.withConformance(conformance)
		.withUnquotedCasing(Casing.UNCHANGED)
		.withIdentifierQuoteString("`"));
}
 
Example #12
Source File: SqlPrettyWriter.java    From calcite with Apache License 2.0 4 votes vote down vote up
/** Creates a {@link SqlWriterConfig} with Calcite's SQL dialect. */
public static SqlWriterConfig config() {
  return ImmutableBeans.create(SqlWriterConfig.class)
      .withDialect(CalciteSqlDialect.DEFAULT);
}
 
Example #13
Source File: SqlDialectFactoryImpl.java    From calcite with Apache License 2.0 4 votes vote down vote up
/** Returns a basic dialect for a given product, or null if none is known. */
static SqlDialect simple(SqlDialect.DatabaseProduct databaseProduct) {
  switch (databaseProduct) {
  case ACCESS:
    return AccessSqlDialect.DEFAULT;
  case BIG_QUERY:
    return BigQuerySqlDialect.DEFAULT;
  case CALCITE:
    return CalciteSqlDialect.DEFAULT;
  case CLICKHOUSE:
    return ClickHouseSqlDialect.DEFAULT;
  case DB2:
    return Db2SqlDialect.DEFAULT;
  case DERBY:
    return DerbySqlDialect.DEFAULT;
  case FIREBIRD:
    return FirebirdSqlDialect.DEFAULT;
  case H2:
    return H2SqlDialect.DEFAULT;
  case HIVE:
    return HiveSqlDialect.DEFAULT;
  case HSQLDB:
    return HsqldbSqlDialect.DEFAULT;
  case INFOBRIGHT:
    return InfobrightSqlDialect.DEFAULT;
  case INFORMIX:
    return InformixSqlDialect.DEFAULT;
  case INGRES:
    return IngresSqlDialect.DEFAULT;
  case INTERBASE:
    return InterbaseSqlDialect.DEFAULT;
  case JETHRO:
    throw new RuntimeException("Jethro does not support simple creation");
  case LUCIDDB:
    return LucidDbSqlDialect.DEFAULT;
  case MSSQL:
    return MssqlSqlDialect.DEFAULT;
  case MYSQL:
    return MysqlSqlDialect.DEFAULT;
  case NEOVIEW:
    return NeoviewSqlDialect.DEFAULT;
  case NETEZZA:
    return NetezzaSqlDialect.DEFAULT;
  case ORACLE:
    return OracleSqlDialect.DEFAULT;
  case PARACCEL:
    return ParaccelSqlDialect.DEFAULT;
  case PHOENIX:
    return PhoenixSqlDialect.DEFAULT;
  case POSTGRESQL:
    return PostgresqlSqlDialect.DEFAULT;
  case PRESTO:
    return PrestoSqlDialect.DEFAULT;
  case REDSHIFT:
    return RedshiftSqlDialect.DEFAULT;
  case SYBASE:
    return SybaseSqlDialect.DEFAULT;
  case TERADATA:
    return TeradataSqlDialect.DEFAULT;
  case VERTICA:
    return VerticaSqlDialect.DEFAULT;
  case SPARK:
    return SparkSqlDialect.DEFAULT;
  case SQLSTREAM:
  case UNKNOWN:
  default:
    return null;
  }
}
 
Example #14
Source File: SqlSampleSpec.java    From calcite with Apache License 2.0 4 votes vote down vote up
public String toString() {
  return "SUBSTITUTE("
      + CalciteSqlDialect.DEFAULT.quoteStringLiteral(name)
      + ")";
}
 
Example #15
Source File: Smalls.java    From calcite with Apache License 2.0 4 votes vote down vote up
public static TranslatableTable strView(String s) {
  return new ViewTable(Object.class, typeFactory ->
      typeFactory.builder().add("c", SqlTypeName.VARCHAR, 100).build(),
      "values (" + CalciteSqlDialect.DEFAULT.quoteStringLiteral(s) + ")",
      ImmutableList.of(), Arrays.asList("view"));
}
 
Example #16
Source File: SqlSampleSpec.java    From Bats with Apache License 2.0 4 votes vote down vote up
public String toString() {
  return "SUBSTITUTE("
      + CalciteSqlDialect.DEFAULT.quoteStringLiteral(name)
      + ")";
}
 
Example #17
Source File: ExtensionDdlExecutor.java    From calcite with Apache License 2.0 4 votes vote down vote up
/** Executes a {@code CREATE TABLE} command. Called via reflection. */
public void execute(SqlCreateTable create, CalcitePrepare.Context context) {
  final CalciteSchema schema =
      Schemas.subSchema(context.getRootSchema(),
          context.getDefaultSchemaPath());
  final JavaTypeFactory typeFactory = context.getTypeFactory();
  final RelDataType queryRowType;
  if (create.query != null) {
    // A bit of a hack: pretend it's a view, to get its row type
    final String sql =
        create.query.toSqlString(CalciteSqlDialect.DEFAULT).getSql();
    final ViewTableMacro viewTableMacro =
        ViewTable.viewMacro(schema.plus(), sql, schema.path(null),
            context.getObjectPath(), false);
    final TranslatableTable x = viewTableMacro.apply(ImmutableList.of());
    queryRowType = x.getRowType(typeFactory);

    if (create.columnList != null
        && queryRowType.getFieldCount() != create.columnList.size()) {
      throw SqlUtil.newContextException(create.columnList.getParserPosition(),
          RESOURCE.columnCountMismatch());
    }
  } else {
    queryRowType = null;
  }
  final RelDataTypeFactory.Builder builder = typeFactory.builder();
  if (create.columnList != null) {
    final SqlValidator validator = new ContextSqlValidator(context, false);
    create.forEachNameType((name, typeSpec) ->
        builder.add(name.getSimple(), typeSpec.deriveType(validator, true)));
  } else {
    if (queryRowType == null) {
      // "CREATE TABLE t" is invalid; because there is no "AS query" we need
      // a list of column names and types, "CREATE TABLE t (INT c)".
      throw SqlUtil.newContextException(create.name.getParserPosition(),
          RESOURCE.createTableRequiresColumnList());
    }
    builder.addAll(queryRowType.getFieldList());
  }
  final RelDataType rowType = builder.build();
  schema.add(create.name.getSimple(),
      new MutableArrayTable(create.name.getSimple(),
          RelDataTypeImpl.proto(rowType)));
  if (create.query != null) {
    populate(create.name, create.query, context);
  }
}
 
Example #18
Source File: SqlDialectFactoryImpl.java    From Bats with Apache License 2.0 4 votes vote down vote up
/** Returns a basic dialect for a given product, or null if none is known. */
static SqlDialect simple(SqlDialect.DatabaseProduct databaseProduct) {
  switch (databaseProduct) {
  case ACCESS:
    return AccessSqlDialect.DEFAULT;
  case BIG_QUERY:
    return BigQuerySqlDialect.DEFAULT;
  case CALCITE:
    return CalciteSqlDialect.DEFAULT;
  case DB2:
    return Db2SqlDialect.DEFAULT;
  case DERBY:
    return DerbySqlDialect.DEFAULT;
  case FIREBIRD:
    return FirebirdSqlDialect.DEFAULT;
  case H2:
    return H2SqlDialect.DEFAULT;
  case HIVE:
    return HiveSqlDialect.DEFAULT;
  case HSQLDB:
    return HsqldbSqlDialect.DEFAULT;
  case INFOBRIGHT:
    return InfobrightSqlDialect.DEFAULT;
  case INFORMIX:
    return InformixSqlDialect.DEFAULT;
  case INGRES:
    return IngresSqlDialect.DEFAULT;
  case INTERBASE:
    return InterbaseSqlDialect.DEFAULT;
  case JETHRO:
    throw new RuntimeException("Jethro does not support simple creation");
  case LUCIDDB:
    return LucidDbSqlDialect.DEFAULT;
  case MSSQL:
    return MssqlSqlDialect.DEFAULT;
  case MYSQL:
    return MysqlSqlDialect.DEFAULT;
  case NEOVIEW:
    return NeoviewSqlDialect.DEFAULT;
  case NETEZZA:
    return NetezzaSqlDialect.DEFAULT;
  case ORACLE:
    return OracleSqlDialect.DEFAULT;
  case PARACCEL:
    return ParaccelSqlDialect.DEFAULT;
  case PHOENIX:
    return PhoenixSqlDialect.DEFAULT;
  case POSTGRESQL:
    return PostgresqlSqlDialect.DEFAULT;
  case REDSHIFT:
    return RedshiftSqlDialect.DEFAULT;
  case SYBASE:
    return SybaseSqlDialect.DEFAULT;
  case TERADATA:
    return TeradataSqlDialect.DEFAULT;
  case VERTICA:
    return VerticaSqlDialect.DEFAULT;
  case SPARK:
    return SparkSqlDialect.DEFAULT;
  case SQLSTREAM:
  case UNKNOWN:
  default:
    return null;
  }
}