Skip to content

Add support for View Refresh operation #25906

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jul 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ statement
SET PROPERTIES propertyAssignments #setMaterializedViewProperties
| DROP VIEW (IF EXISTS)? qualifiedName #dropView
| ALTER VIEW from=qualifiedName RENAME TO to=qualifiedName #renameView
| ALTER VIEW viewName=qualifiedName REFRESH #refreshView
| CALL qualifiedName '(' (callArgument (',' callArgument)*)? ')' #call
| CREATE (OR REPLACE)? functionSpecification #createFunction
| DROP FUNCTION (IF EXISTS)? functionDeclaration #dropFunction
Expand Down
148 changes: 148 additions & 0 deletions core/trino-main/src/main/java/io/trino/execution/RefreshViewTask.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.execution;

import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.inject.Inject;
import io.trino.Session;
import io.trino.execution.warnings.WarningCollector;
import io.trino.metadata.Metadata;
import io.trino.metadata.QualifiedObjectName;
import io.trino.metadata.ViewColumn;
import io.trino.metadata.ViewDefinition;
import io.trino.security.AccessControl;
import io.trino.security.ViewAccessControl;
import io.trino.spi.security.GroupProvider;
import io.trino.spi.security.Identity;
import io.trino.sql.PlannerContext;
import io.trino.sql.analyzer.Analysis;
import io.trino.sql.analyzer.AnalyzerFactory;
import io.trino.sql.parser.SqlParser;
import io.trino.sql.tree.Expression;
import io.trino.sql.tree.RefreshView;
import io.trino.sql.tree.Statement;

import java.util.List;
import java.util.Map;
import java.util.Optional;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static com.google.common.util.concurrent.Futures.immediateVoidFuture;
import static io.trino.metadata.MetadataUtil.createQualifiedObjectName;
import static io.trino.spi.StandardErrorCode.TABLE_NOT_FOUND;
import static io.trino.sql.analyzer.SemanticExceptions.semanticException;
import static java.util.Objects.requireNonNull;

public class RefreshViewTask
implements DataDefinitionTask<RefreshView>
{
private final PlannerContext plannerContext;
private final AccessControl accessControl;
private final GroupProvider groupProvider;
private final SqlParser sqlParser;
private final AnalyzerFactory analyzerFactory;

@Inject
public RefreshViewTask(
PlannerContext plannerContext,
AccessControl accessControl,
GroupProvider groupProvider,
SqlParser sqlParser,
AnalyzerFactory analyzerFactory)
{
this.plannerContext = requireNonNull(plannerContext, "plannerContext is null");
this.accessControl = requireNonNull(accessControl, "accessControl is null");
this.groupProvider = requireNonNull(groupProvider, "groupProvider is null");
this.sqlParser = requireNonNull(sqlParser, "sqlParser is null");
this.analyzerFactory = requireNonNull(analyzerFactory, "analyzerFactory is null");
}

@Override
public String getName()
{
return "REFRESH VIEW";
}

@Override
public ListenableFuture<Void> execute(
RefreshView refreshView,
QueryStateMachine stateMachine,
List<Expression> parameters,
WarningCollector warningCollector)
{
Metadata metadata = plannerContext.getMetadata();
Session session = stateMachine.getSession();
QualifiedObjectName viewName = createQualifiedObjectName(session, refreshView, refreshView.getName());

ViewDefinition viewDefinition = metadata.getView(session, viewName)
.orElseThrow(() -> semanticException(TABLE_NOT_FOUND, refreshView, "View '%s' not found", viewName));

accessControl.checkCanRefreshView(session.toSecurityContext(), viewName);

Identity identity = session.getIdentity();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that ideally the view definition should always be refreshed by the same identity that initially created the view.
I understand it is not possible in the current model because we don't keep this information for the "run as invoker" views. Refreshing the view by the same identity who would run the view is the second best option imo.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would like to retain the secuirty mode for refresh like we do for execution - Ideally the same could be enforced via access control mechansim as well.

Refreshing the view by the same identity who would run the view is the second best option imo.

Can you explain it a bit.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would like to retain the secuirty mode for refresh like we do for execution

It is not obvious to me that we should refresh in the same mode as we execute the view.
To keep the view semantics as close to the original as possible, we should re-define it as the original creator. This is not always possible though, since we lose the original creator info in case of the "run as invoker" views.
I think that ideally we should decouple the view creator from the "run as identity". For now, we can just refresh as the "executing" identity. What do you think?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To keep the view semantics as close to the original as possible, we should re-define it as the original creator.

I agree with this - we should redfine it via the owner identity.

For now, we can just refresh as the "executing" identity. What do you think?

But it wouldn;t work for the definer views right ? Let’s say if we have an access to the table only for the owner and accessing/refreshing via executing identity might not fail to refresh the views.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. The refresh can fail when run by a non-owner. I was thinking of a hypothetical situation when the view semantics actually differs for the owner and the executing identity -- for example if there was a mechanism to hide some columns from some users. If a random user refreshed the view, everyone would get their subset of columns.

This is why I said we should always refresh as the owner.
Do you know what it takes to do so?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for example if there was a mechanism to hide some columns from some users

But the same would happen for executing the views as well right ? Today a user could create a view SELECT * ... which has 10 columns with invoker mode and now when another user praveen access them it would fail with column mismatch. It is more of an invoker mode limitation which is being seen here.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, I think we're getting to the same point. I the owner refreshes the view, we get the original intended semantics. If another user refreshes the view, they will impose their semantics not only for themselves but also for everyone who will execute that view later.

Regarding the current implementation: the view is refreshed

  • by the owner for "definer" views
  • by the current identity for "invoker" views

We want it to be always the owner. But the issue is that for "invoker" views we don't know who the owner is.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We want it to be always the owner. But the issue is that for "invoker" views we don't know who the owner is.

Yes - either we need to disable refreshing those views and maybe we could set authorization to set the owner and run them once again.

AccessControl viewAccessControl = accessControl;

if (!viewDefinition.isRunAsInvoker()) {
checkArgument(viewDefinition.getRunAsIdentity().isPresent(), "View owner detail is missing");
Identity owner = viewDefinition.getRunAsIdentity().get();
identity = Identity.from(owner)
.withGroups(groupProvider.getGroups(owner.getUser()))
.build();
// View owner does not need GRANT OPTION to grant access themselves
if (!owner.getUser().equals(session.getIdentity().getUser())) {
viewAccessControl = new ViewAccessControl(accessControl);
}
}

Session viewSession = session.createViewSession(viewDefinition.getCatalog(), viewDefinition.getSchema(), identity, viewDefinition.getPath());

Statement viewDefinitionSql = sqlParser.createStatement(viewDefinition.getOriginalSql());

Analysis analysis = analyzerFactory.createAnalyzer(
viewSession,
parameters,
viewAccessControl,
ImmutableMap.of(),
stateMachine.getWarningCollector(),
stateMachine.getPlanOptimizersStatsCollector())
.analyze(viewDefinitionSql);

Map<String, String> columnComments =
viewDefinition.getColumns()
.stream()
.filter(viewColumn -> viewColumn.comment().isPresent())
.collect(toImmutableMap(ViewColumn::name, viewColumn -> viewColumn.comment().get()));

List<ViewColumn> columns = analysis.getOutputDescriptor(viewDefinitionSql)
.getVisibleFields().stream()
.map(field -> new ViewColumn(field.getName().get(), field.getType().getTypeId(), Optional.ofNullable(columnComments.get(field.getName().get()))))
.collect(toImmutableList());

ViewDefinition viewDefinitionWithNewColumns = new ViewDefinition(
viewDefinition.getOriginalSql(),
viewDefinition.getCatalog(),
viewDefinition.getSchema(),
columns,
viewDefinition.getComment(),
viewDefinition.getRunAsIdentity(),
viewDefinition.getPath());

metadata.refreshView(session, viewName, viewDefinitionWithNewColumns);

return immediateVoidFuture();
}
}
5 changes: 5 additions & 0 deletions core/trino-main/src/main/java/io/trino/metadata/Metadata.java
Original file line number Diff line number Diff line change
Expand Up @@ -513,6 +513,11 @@ Optional<ConnectorOutputMetadata> finishRefreshMaterializedView(
*/
void renameView(Session session, QualifiedObjectName existingViewName, QualifiedObjectName newViewName);

/**
* Refreshes the view definition.
*/
void refreshView(Session session, QualifiedObjectName viewName, ViewDefinition definition);

/**
* Drops the specified view.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1585,6 +1585,15 @@ public void renameView(Session session, QualifiedObjectName source, QualifiedObj
}
}

@Override
public void refreshView(Session session, QualifiedObjectName viewName, ViewDefinition definition)
{
CatalogMetadata catalogMetadata = getCatalogMetadataForWrite(session, viewName.catalogName());
CatalogHandle catalogHandle = catalogMetadata.getCatalogHandle();
ConnectorMetadata metadata = catalogMetadata.getMetadata(session);
metadata.refreshView(session.toConnectorSession(catalogHandle), viewName.asSchemaTableName(), definition.toConnectorViewDefinition());
}

@Override
public void dropView(Session session, QualifiedObjectName viewName)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,13 @@ public interface AccessControl
*/
void checkCanRenameView(SecurityContext context, QualifiedObjectName viewName, QualifiedObjectName newViewName);

/**
* Check if identity is allowed to refresh the specified view.
*
* @throws AccessDeniedException if not allowed
*/
void checkCanRefreshView(SecurityContext context, QualifiedObjectName viewName);

/**
* Check if identity is allowed to drop the specified view.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -797,6 +797,19 @@ public void checkCanRenameView(SecurityContext securityContext, QualifiedObjectN
catalogAuthorizationCheck(viewName.catalogName(), securityContext, (control, context) -> control.checkCanRenameView(context, viewName.asSchemaTableName(), newViewName.asSchemaTableName()));
}

@Override
public void checkCanRefreshView(SecurityContext securityContext, QualifiedObjectName viewName)
{
requireNonNull(securityContext, "securityContext is null");
requireNonNull(viewName, "viewName is null");

checkCanAccessCatalog(securityContext, viewName.catalogName());

systemAuthorizationCheck(control -> control.checkCanRefreshView(securityContext.toSystemSecurityContext(), viewName.asCatalogSchemaTableName()));

catalogAuthorizationCheck(viewName.catalogName(), securityContext, (control, context) -> control.checkCanRefreshView(context, viewName.asSchemaTableName()));
}

@Override
public void checkCanDropView(SecurityContext securityContext, QualifiedObjectName viewName)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,9 @@ public void checkCanCreateView(SecurityContext context, QualifiedObjectName view
@Override
public void checkCanRenameView(SecurityContext context, QualifiedObjectName viewName, QualifiedObjectName newViewName) {}

@Override
public void checkCanRefreshView(SecurityContext context, QualifiedObjectName viewName) {}

@Override
public void checkCanDropView(SecurityContext context, QualifiedObjectName viewName) {}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@
import static io.trino.spi.security.AccessDeniedException.denyKillQuery;
import static io.trino.spi.security.AccessDeniedException.denyReadSystemInformationAccess;
import static io.trino.spi.security.AccessDeniedException.denyRefreshMaterializedView;
import static io.trino.spi.security.AccessDeniedException.denyRefreshView;
import static io.trino.spi.security.AccessDeniedException.denyRenameColumn;
import static io.trino.spi.security.AccessDeniedException.denyRenameMaterializedView;
import static io.trino.spi.security.AccessDeniedException.denyRenameSchema;
Expand Down Expand Up @@ -344,6 +345,12 @@ public void checkCanRenameView(SecurityContext context, QualifiedObjectName view
denyRenameView(viewName.toString(), newViewName.toString());
}

@Override
public void checkCanRefreshView(SecurityContext context, QualifiedObjectName viewName)
{
denyRefreshView(viewName.toString());
}

@Override
public void checkCanDropView(SecurityContext context, QualifiedObjectName viewName)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,12 @@ public void checkCanRenameView(SecurityContext context, QualifiedObjectName view
delegate().checkCanRenameView(context, viewName, newViewName);
}

@Override
public void checkCanRefreshView(SecurityContext context, QualifiedObjectName viewName)
{
delegate().checkCanRefreshView(context, viewName);
}

@Override
public void checkCanDropView(SecurityContext context, QualifiedObjectName viewName)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,13 @@ public void checkCanRenameView(ConnectorSecurityContext context, SchemaTableName
accessControl.checkCanRenameView(securityContext, getQualifiedObjectName(viewName), getQualifiedObjectName(viewName));
}

@Override
public void checkCanRefreshView(ConnectorSecurityContext context, SchemaTableName viewName)
{
checkArgument(context == null, "context must be null");
accessControl.checkCanRefreshView(securityContext, getQualifiedObjectName(viewName));
}

@Override
public void checkCanDropView(ConnectorSecurityContext context, SchemaTableName viewName)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
import io.trino.execution.GrantTask;
import io.trino.execution.PrepareTask;
import io.trino.execution.QueryExecution.QueryExecutionFactory;
import io.trino.execution.RefreshViewTask;
import io.trino.execution.RenameColumnTask;
import io.trino.execution.RenameMaterializedViewTask;
import io.trino.execution.RenameSchemaTask;
Expand Down Expand Up @@ -99,6 +100,7 @@
import io.trino.sql.tree.Grant;
import io.trino.sql.tree.GrantRoles;
import io.trino.sql.tree.Prepare;
import io.trino.sql.tree.RefreshView;
import io.trino.sql.tree.RenameColumn;
import io.trino.sql.tree.RenameMaterializedView;
import io.trino.sql.tree.RenameSchema;
Expand Down Expand Up @@ -170,6 +172,7 @@ public void configure(Binder binder)
bindDataDefinitionTask(binder, executionBinder, Grant.class, GrantTask.class);
bindDataDefinitionTask(binder, executionBinder, GrantRoles.class, GrantRolesTask.class);
bindDataDefinitionTask(binder, executionBinder, Prepare.class, PrepareTask.class);
bindDataDefinitionTask(binder, executionBinder, RefreshView.class, RefreshViewTask.class);
bindDataDefinitionTask(binder, executionBinder, RenameColumn.class, RenameColumnTask.class);
bindDataDefinitionTask(binder, executionBinder, RenameMaterializedView.class, RenameMaterializedViewTask.class);
bindDataDefinitionTask(binder, executionBinder, RenameSchema.class, RenameSchemaTask.class);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import io.trino.Session;
import io.trino.execution.querystats.PlanOptimizersStatsCollector;
import io.trino.execution.warnings.WarningCollector;
import io.trino.security.AccessControl;
import io.trino.sql.rewrite.StatementRewrite;
import io.trino.sql.tree.Expression;
import io.trino.sql.tree.NodeRef;
Expand Down Expand Up @@ -60,4 +61,24 @@ public Analyzer createAnalyzer(
tracer,
statementRewrite);
}

public Analyzer createAnalyzer(
Session session,
List<Expression> parameters,
AccessControl accessControl,
Map<NodeRef<Parameter>, Expression> parameterLookup,
WarningCollector warningCollector,
PlanOptimizersStatsCollector planOptimizersStatsCollector)
{
return new Analyzer(
session,
this,
statementAnalyzerFactory.withSpecializedAccessControl(accessControl),
parameters,
parameterLookup,
warningCollector,
planOptimizersStatsCollector,
tracer,
statementRewrite);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,7 @@
import io.trino.sql.tree.QueryPeriod;
import io.trino.sql.tree.QuerySpecification;
import io.trino.sql.tree.RefreshMaterializedView;
import io.trino.sql.tree.RefreshView;
import io.trino.sql.tree.Relation;
import io.trino.sql.tree.RenameColumn;
import io.trino.sql.tree.RenameMaterializedView;
Expand Down Expand Up @@ -689,6 +690,12 @@ protected Scope visitInsert(Insert insert, Optional<Scope> scope)
return createAndAssignScope(insert, scope, Field.newUnqualified("rows", BIGINT));
}

@Override
protected Scope visitRefreshView(RefreshView node, Optional<Scope> scope)
{
return createAndAssignScope(node, scope);
}

@Override
protected Scope visitRefreshMaterializedView(RefreshMaterializedView refreshMaterializedView, Optional<Scope> scope)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,15 @@ public void checkCanRenameView(SecurityContext context, QualifiedObjectName view
}
}

@Override
public void checkCanRefreshView(SecurityContext context, QualifiedObjectName viewName)
{
Span span = startSpan("checkCanRefreshView");
try (var _ = scopedSpan(span)) {
delegate.checkCanRefreshView(context, viewName);
}
}

@Override
public void checkCanDropView(SecurityContext context, QualifiedObjectName viewName)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -798,6 +798,15 @@ public void setViewAuthorization(ConnectorSession session, SchemaTableName viewN
}
}

@Override
public void refreshView(ConnectorSession session, SchemaTableName viewName, ConnectorViewDefinition definition)
{
Span span = startSpan("refreshView", viewName);
try (var _ = scopedSpan(span)) {
delegate.refreshView(session, viewName, definition);
}
}

@Override
public void dropView(ConnectorSession session, SchemaTableName viewName)
{
Expand Down
Loading