Search in sources :

Example 1 with CreateMaterializedView

use of com.facebook.presto.sql.tree.CreateMaterializedView in project presto by prestodb.

the class TestSqlParser method testCreateMaterializedView.

@Test
public void testCreateMaterializedView() {
    Query query = simpleQuery(selectList(new AllColumns()), table(QualifiedName.of("t")));
    assertStatement("CREATE MATERIALIZED VIEW mv" + " AS SELECT * FROM t", new CreateMaterializedView(Optional.empty(), QualifiedName.of("mv"), query, false, ImmutableList.of(), Optional.empty()));
    assertStatement("CREATE MATERIALIZED VIEW mv COMMENT 'A simple materialized view'" + " AS SELECT * FROM t", new CreateMaterializedView(Optional.empty(), QualifiedName.of("mv"), query, false, ImmutableList.of(), Optional.of("A simple materialized view")));
    assertStatement("CREATE MATERIALIZED VIEW IF NOT EXISTS mv COMMENT 'A simple materialized view'" + " AS SELECT * FROM t", new CreateMaterializedView(Optional.empty(), QualifiedName.of("mv"), query, true, ImmutableList.of(), Optional.of("A simple materialized view")));
    List<Property> properties = ImmutableList.of(new Property(new Identifier("partitioned_by"), new ArrayConstructor(ImmutableList.of(new StringLiteral("ds")))));
    assertStatement("CREATE MATERIALIZED VIEW IF NOT EXISTS mv COMMENT 'A simple materialized view'" + " WITH (partitioned_by = ARRAY ['ds'])" + " AS SELECT * FROM t", new CreateMaterializedView(Optional.empty(), QualifiedName.of("mv"), query, true, properties, Optional.of("A simple materialized view")));
    List<Property> properties1 = ImmutableList.of(new Property(new Identifier("partitioned_by"), new ArrayConstructor(ImmutableList.of(new StringLiteral("ds")))), new Property(new Identifier("retention_days"), new LongLiteral("90")));
    assertStatement("CREATE MATERIALIZED VIEW IF NOT EXISTS mv COMMENT 'A simple materialized view'" + " WITH (partitioned_by = ARRAY ['ds'], retention_days = 90)" + " AS SELECT * FROM t", new CreateMaterializedView(Optional.empty(), QualifiedName.of("mv"), query, true, properties1, Optional.of("A simple materialized view")));
}
Also used : CreateMaterializedView(com.facebook.presto.sql.tree.CreateMaterializedView) Identifier(com.facebook.presto.sql.tree.Identifier) QueryUtil.quotedIdentifier(com.facebook.presto.sql.QueryUtil.quotedIdentifier) Query(com.facebook.presto.sql.tree.Query) QueryUtil.simpleQuery(com.facebook.presto.sql.QueryUtil.simpleQuery) WithQuery(com.facebook.presto.sql.tree.WithQuery) StringLiteral(com.facebook.presto.sql.tree.StringLiteral) LongLiteral(com.facebook.presto.sql.tree.LongLiteral) ArrayConstructor(com.facebook.presto.sql.tree.ArrayConstructor) AllColumns(com.facebook.presto.sql.tree.AllColumns) Property(com.facebook.presto.sql.tree.Property) Test(org.testng.annotations.Test)

Example 2 with CreateMaterializedView

use of com.facebook.presto.sql.tree.CreateMaterializedView in project presto by prestodb.

the class CreateMaterializedViewTask method execute.

@Override
public ListenableFuture<?> execute(CreateMaterializedView statement, TransactionManager transactionManager, Metadata metadata, AccessControl accessControl, Session session, List<Expression> parameters, WarningCollector warningCollector) {
    QualifiedObjectName viewName = createQualifiedObjectName(session, statement, statement.getName());
    Optional<TableHandle> viewHandle = metadata.getTableHandle(session, viewName);
    if (viewHandle.isPresent()) {
        if (!statement.isNotExists()) {
            throw new SemanticException(MATERIALIZED_VIEW_ALREADY_EXISTS, statement, "Materialized view '%s' already exists", viewName);
        }
        return immediateFuture(null);
    }
    accessControl.checkCanCreateTable(session.getRequiredTransactionId(), session.getIdentity(), session.getAccessControlContext(), viewName);
    accessControl.checkCanCreateView(session.getRequiredTransactionId(), session.getIdentity(), session.getAccessControlContext(), viewName);
    Analyzer analyzer = new Analyzer(session, metadata, sqlParser, accessControl, Optional.empty(), parameters, warningCollector);
    Analysis analysis = analyzer.analyze(statement);
    ConnectorId connectorId = metadata.getCatalogHandle(session, viewName.getCatalogName()).orElseThrow(() -> new PrestoException(NOT_FOUND, "Catalog does not exist: " + viewName.getCatalogName()));
    List<ColumnMetadata> columnMetadata = analysis.getOutputDescriptor(statement.getQuery()).getVisibleFields().stream().map(field -> new ColumnMetadata(field.getName().get(), field.getType())).collect(toImmutableList());
    Map<String, Expression> sqlProperties = mapFromProperties(statement.getProperties());
    Map<String, Object> properties = metadata.getTablePropertyManager().getProperties(connectorId, viewName.getCatalogName(), sqlProperties, session, metadata, parameters);
    ConnectorTableMetadata viewMetadata = new ConnectorTableMetadata(toSchemaTableName(viewName), columnMetadata, properties, statement.getComment());
    String sql = getFormattedSql(statement.getQuery(), sqlParser, Optional.of(parameters));
    List<SchemaTableName> baseTables = analysis.getTableNodes().stream().map(table -> {
        QualifiedObjectName tableName = createQualifiedObjectName(session, table, table.getName());
        if (!viewName.getCatalogName().equals(tableName.getCatalogName())) {
            throw new SemanticException(NOT_SUPPORTED, statement, "Materialized view %s created from a base table in a different catalog %s is not supported.", viewName, tableName);
        }
        return toSchemaTableName(tableName);
    }).distinct().collect(toImmutableList());
    MaterializedViewColumnMappingExtractor extractor = new MaterializedViewColumnMappingExtractor(analysis, session);
    ConnectorMaterializedViewDefinition viewDefinition = new ConnectorMaterializedViewDefinition(sql, viewName.getSchemaName(), viewName.getObjectName(), baseTables, Optional.of(session.getUser()), extractor.getMaterializedViewColumnMappings(), extractor.getMaterializedViewDirectColumnMappings(), extractor.getBaseTablesOnOuterJoinSide(), Optional.empty());
    try {
        metadata.createMaterializedView(session, viewName.getCatalogName(), viewMetadata, viewDefinition, statement.isNotExists());
    } catch (PrestoException e) {
        // connectors are not required to handle the ignoreExisting flag
        if (!e.getErrorCode().equals(ALREADY_EXISTS.toErrorCode()) || !statement.isNotExists()) {
            throw e;
        }
    }
    return immediateFuture(null);
}
Also used : WarningCollector(com.facebook.presto.spi.WarningCollector) Analyzer(com.facebook.presto.sql.analyzer.Analyzer) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) NOT_FOUND(com.facebook.presto.spi.StandardErrorCode.NOT_FOUND) PrestoException(com.facebook.presto.spi.PrestoException) SemanticException(com.facebook.presto.sql.analyzer.SemanticException) Inject(javax.inject.Inject) SchemaTableName(com.facebook.presto.spi.SchemaTableName) ALREADY_EXISTS(com.facebook.presto.spi.StandardErrorCode.ALREADY_EXISTS) NodeUtils.mapFromProperties(com.facebook.presto.sql.NodeUtils.mapFromProperties) Map(java.util.Map) Objects.requireNonNull(java.util.Objects.requireNonNull) QualifiedObjectName(com.facebook.presto.common.QualifiedObjectName) ConnectorMaterializedViewDefinition(com.facebook.presto.spi.ConnectorMaterializedViewDefinition) TableHandle(com.facebook.presto.spi.TableHandle) TransactionManager(com.facebook.presto.transaction.TransactionManager) ConnectorTableMetadata(com.facebook.presto.spi.ConnectorTableMetadata) Futures.immediateFuture(com.google.common.util.concurrent.Futures.immediateFuture) MetadataUtil.toSchemaTableName(com.facebook.presto.metadata.MetadataUtil.toSchemaTableName) Session(com.facebook.presto.Session) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) MaterializedViewColumnMappingExtractor(com.facebook.presto.sql.analyzer.MaterializedViewColumnMappingExtractor) NOT_SUPPORTED(com.facebook.presto.sql.analyzer.SemanticErrorCode.NOT_SUPPORTED) SqlParser(com.facebook.presto.sql.parser.SqlParser) CreateMaterializedView(com.facebook.presto.sql.tree.CreateMaterializedView) SqlFormatterUtil.getFormattedSql(com.facebook.presto.sql.SqlFormatterUtil.getFormattedSql) List(java.util.List) ColumnMetadata(com.facebook.presto.spi.ColumnMetadata) Expression(com.facebook.presto.sql.tree.Expression) MetadataUtil.createQualifiedObjectName(com.facebook.presto.metadata.MetadataUtil.createQualifiedObjectName) MATERIALIZED_VIEW_ALREADY_EXISTS(com.facebook.presto.sql.analyzer.SemanticErrorCode.MATERIALIZED_VIEW_ALREADY_EXISTS) Analysis(com.facebook.presto.sql.analyzer.Analysis) Optional(java.util.Optional) ConnectorId(com.facebook.presto.spi.ConnectorId) Metadata(com.facebook.presto.metadata.Metadata) AccessControl(com.facebook.presto.security.AccessControl) ColumnMetadata(com.facebook.presto.spi.ColumnMetadata) ConnectorMaterializedViewDefinition(com.facebook.presto.spi.ConnectorMaterializedViewDefinition) PrestoException(com.facebook.presto.spi.PrestoException) Analyzer(com.facebook.presto.sql.analyzer.Analyzer) SchemaTableName(com.facebook.presto.spi.SchemaTableName) MetadataUtil.toSchemaTableName(com.facebook.presto.metadata.MetadataUtil.toSchemaTableName) QualifiedObjectName(com.facebook.presto.common.QualifiedObjectName) MetadataUtil.createQualifiedObjectName(com.facebook.presto.metadata.MetadataUtil.createQualifiedObjectName) MaterializedViewColumnMappingExtractor(com.facebook.presto.sql.analyzer.MaterializedViewColumnMappingExtractor) Expression(com.facebook.presto.sql.tree.Expression) Analysis(com.facebook.presto.sql.analyzer.Analysis) TableHandle(com.facebook.presto.spi.TableHandle) ConnectorTableMetadata(com.facebook.presto.spi.ConnectorTableMetadata) SemanticException(com.facebook.presto.sql.analyzer.SemanticException) ConnectorId(com.facebook.presto.spi.ConnectorId)

Example 3 with CreateMaterializedView

use of com.facebook.presto.sql.tree.CreateMaterializedView in project presto by prestodb.

the class MaterializedViewColumnMappingExtractor method getColumnMappings.

private static Map<String, Map<SchemaTableName, String>> getColumnMappings(Analysis analysis, Map<TableColumn, Set<TableColumn>> columnMappings) {
    checkState(analysis.getStatement() instanceof CreateMaterializedView, "Only support the computation of column mappings when analyzing CreateMaterializedView");
    ImmutableMap.Builder<String, Map<SchemaTableName, String>> fullColumnMappings = ImmutableMap.builder();
    Map<String, TableColumn> originalColumnMappings = getOriginalColumnsFromAnalysis(analysis);
    for (Map.Entry<String, TableColumn> columnMapping : originalColumnMappings.entrySet()) {
        String viewColumn = columnMapping.getKey();
        TableColumn originalBaseColumn = columnMapping.getValue();
        Map<SchemaTableName, String> fullBaseColumns = columnMappings.getOrDefault(originalBaseColumn, ImmutableSet.of(originalBaseColumn)).stream().collect(toImmutableMap(e -> e.getTableName(), e -> e.getColumnName()));
        fullColumnMappings.put(viewColumn, fullBaseColumns);
    }
    return fullColumnMappings.build();
}
Also used : Table(com.facebook.presto.sql.tree.Table) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) TableColumn(com.facebook.presto.spi.ConnectorMaterializedViewDefinition.TableColumn) SchemaTableName(com.facebook.presto.spi.SchemaTableName) MaterializedViewUtils.transitiveClosure(com.facebook.presto.sql.MaterializedViewUtils.transitiveClosure) SetOperation(com.facebook.presto.sql.tree.SetOperation) Map(java.util.Map) Objects.requireNonNull(java.util.Objects.requireNonNull) ImmutableSet(com.google.common.collect.ImmutableSet) MetadataUtil.toSchemaTableName(com.facebook.presto.metadata.MetadataUtil.toSchemaTableName) Query(com.facebook.presto.sql.tree.Query) ImmutableMap(com.google.common.collect.ImmutableMap) Session(com.facebook.presto.Session) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Set(java.util.Set) NOT_SUPPORTED(com.facebook.presto.sql.analyzer.SemanticErrorCode.NOT_SUPPORTED) ComparisonExpression(com.facebook.presto.sql.tree.ComparisonExpression) Preconditions.checkState(com.google.common.base.Preconditions.checkState) CreateMaterializedView(com.facebook.presto.sql.tree.CreateMaterializedView) List(java.util.List) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) MetadataUtil.createQualifiedObjectName(com.facebook.presto.metadata.MetadataUtil.createQualifiedObjectName) INNER(com.facebook.presto.sql.tree.Join.Type.INNER) Optional(java.util.Optional) Collections(java.util.Collections) CreateMaterializedView(com.facebook.presto.sql.tree.CreateMaterializedView) HashMap(java.util.HashMap) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) TableColumn(com.facebook.presto.spi.ConnectorMaterializedViewDefinition.TableColumn) SchemaTableName(com.facebook.presto.spi.SchemaTableName) MetadataUtil.toSchemaTableName(com.facebook.presto.metadata.MetadataUtil.toSchemaTableName) ImmutableMap(com.google.common.collect.ImmutableMap) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap)

Example 4 with CreateMaterializedView

use of com.facebook.presto.sql.tree.CreateMaterializedView in project presto by prestodb.

the class TestCreateMaterializedViewTask method testCreateMaterializedViewNotExistsTrue.

@Test
public void testCreateMaterializedViewNotExistsTrue() {
    SqlParser parser = new SqlParser();
    String sql = String.format("CREATE MATERIALIZED VIEW IF NOT EXISTS %s AS SELECT 2021 AS col_0 FROM %s", MATERIALIZED_VIEW_A, TABLE_A);
    CreateMaterializedView statement = (CreateMaterializedView) parser.createStatement(sql, ParsingOptions.builder().build());
    QueryStateMachine stateMachine = QueryStateMachine.begin(sql, Optional.empty(), testSession, URI.create("fake://uri"), new ResourceGroupId("test"), Optional.empty(), false, transactionManager, accessControl, executorService, metadata, WarningCollector.NOOP);
    WarningCollector warningCollector = stateMachine.getWarningCollector();
    CreateMaterializedViewTask createMaterializedViewTask = new CreateMaterializedViewTask(parser);
    getFutureValue(createMaterializedViewTask.execute(statement, transactionManager, metadata, accessControl, testSession, emptyList(), warningCollector));
    assertEquals(metadata.getCreateMaterializedViewCallCount(), 1);
}
Also used : CreateMaterializedView(com.facebook.presto.sql.tree.CreateMaterializedView) ResourceGroupId(com.facebook.presto.spi.resourceGroups.ResourceGroupId) SqlParser(com.facebook.presto.sql.parser.SqlParser) WarningCollector(com.facebook.presto.spi.WarningCollector) Test(org.testng.annotations.Test)

Example 5 with CreateMaterializedView

use of com.facebook.presto.sql.tree.CreateMaterializedView in project presto by prestodb.

the class TestCreateMaterializedViewTask method testCreateMaterializedViewExistsFalse.

@Test
public void testCreateMaterializedViewExistsFalse() {
    SqlParser parser = new SqlParser();
    String sql = String.format("CREATE MATERIALIZED VIEW %s AS SELECT 2021 AS col_0 FROM %s", MATERIALIZED_VIEW_B, TABLE_A);
    CreateMaterializedView statement = (CreateMaterializedView) parser.createStatement(sql, ParsingOptions.builder().build());
    QueryStateMachine stateMachine = QueryStateMachine.begin(sql, Optional.empty(), testSession, URI.create("fake://uri"), new ResourceGroupId("test"), Optional.empty(), false, transactionManager, accessControl, executorService, metadata, WarningCollector.NOOP);
    WarningCollector warningCollector = stateMachine.getWarningCollector();
    try {
        getFutureValue(new CreateMaterializedViewTask(parser).execute(statement, transactionManager, metadata, accessControl, testSession, emptyList(), warningCollector));
        fail("expected exception");
    } catch (RuntimeException e) {
        // Expected
        assertTrue(e instanceof PrestoException);
        PrestoException prestoException = (PrestoException) e;
        assertEquals(prestoException.getErrorCode(), ALREADY_EXISTS.toErrorCode());
    }
    assertEquals(metadata.getCreateMaterializedViewCallCount(), 0);
}
Also used : CreateMaterializedView(com.facebook.presto.sql.tree.CreateMaterializedView) ResourceGroupId(com.facebook.presto.spi.resourceGroups.ResourceGroupId) SqlParser(com.facebook.presto.sql.parser.SqlParser) PrestoException(com.facebook.presto.spi.PrestoException) WarningCollector(com.facebook.presto.spi.WarningCollector) Test(org.testng.annotations.Test)

Aggregations

CreateMaterializedView (com.facebook.presto.sql.tree.CreateMaterializedView)5 WarningCollector (com.facebook.presto.spi.WarningCollector)3 SqlParser (com.facebook.presto.sql.parser.SqlParser)3 Test (org.testng.annotations.Test)3 Session (com.facebook.presto.Session)2 MetadataUtil.createQualifiedObjectName (com.facebook.presto.metadata.MetadataUtil.createQualifiedObjectName)2 MetadataUtil.toSchemaTableName (com.facebook.presto.metadata.MetadataUtil.toSchemaTableName)2 PrestoException (com.facebook.presto.spi.PrestoException)2 SchemaTableName (com.facebook.presto.spi.SchemaTableName)2 ResourceGroupId (com.facebook.presto.spi.resourceGroups.ResourceGroupId)2 NOT_SUPPORTED (com.facebook.presto.sql.analyzer.SemanticErrorCode.NOT_SUPPORTED)2 Query (com.facebook.presto.sql.tree.Query)2 ImmutableList.toImmutableList (com.google.common.collect.ImmutableList.toImmutableList)2 List (java.util.List)2 Map (java.util.Map)2 Objects.requireNonNull (java.util.Objects.requireNonNull)2 Optional (java.util.Optional)2 QualifiedObjectName (com.facebook.presto.common.QualifiedObjectName)1 Metadata (com.facebook.presto.metadata.Metadata)1 AccessControl (com.facebook.presto.security.AccessControl)1