Skip to content

Add support for table level branching #25152

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

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from
Draft
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
28 changes: 21 additions & 7 deletions core/trino-grammar/src/main/antlr4/io/trino/grammar/sql/SqlBase.g4
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,10 @@ statement
(COMMENT string)?
(WITH properties)? #createTable
| DROP TABLE (IF EXISTS)? qualifiedName #dropTable
| INSERT INTO qualifiedName columnAliases? rootQuery #insertInto
| DELETE FROM qualifiedName (WHERE booleanExpression)? #delete
| INSERT INTO qualifiedName ('@' branch=identifier)?
columnAliases? rootQuery #insertInto
| DELETE FROM qualifiedName ('@' branch=identifier)?
(WHERE booleanExpression)? #delete
| TRUNCATE TABLE qualifiedName #truncateTable
| COMMENT ON TABLE qualifiedName IS (string | NULL) #commentTable
| COMMENT ON VIEW qualifiedName IS (string | NULL) #commentView
Expand Down Expand Up @@ -117,6 +119,13 @@ statement
| CALL qualifiedName '(' (callArgument (',' callArgument)*)? ')' #call
| CREATE (OR REPLACE)? functionSpecification #createFunction
| DROP FUNCTION (IF EXISTS)? functionDeclaration #dropFunction
| CREATE (OR REPLACE)? BRANCH (IF NOT EXISTS)? identifier
(WITH properties)? IN TABLE qualifiedName #createBranch
| DROP BRANCH (IF EXISTS)? identifier
IN TABLE qualifiedName #dropBranch
| ALTER BRANCH source=identifier IN TABLE qualifiedName
Copy link
Contributor

Choose a reason for hiding this comment

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

ALTER BRANCH source=identifier IN TABLE qualifiedName
        FAST FORWARD TO target=identifier                              #fastForwardBranch

When we want the changes from the branch experiment in main does this correspond to

ALTER BRANCH main IN TABLE test-table
        FAST FORWARD TO experiment

?

Copy link
Member Author

Choose a reason for hiding this comment

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

Yes, the query will call ManageSnapshots#fastForwardBranch("main", "experiment") in Iceberg connector.

FAST FORWARD TO target=identifier #fastForwardBranch
| SHOW BRANCHES IN TABLE qualifiedName #showBranchs
| CREATE ROLE name=identifier
(WITH ADMIN grantor)?
(IN catalog=identifier)? #createRole
Expand Down Expand Up @@ -190,10 +199,11 @@ statement
| DESCRIBE OUTPUT identifier #describeOutput
| SET PATH pathSpecification #setPath
| SET TIME ZONE (LOCAL | expression) #setTimeZone
| UPDATE qualifiedName
| UPDATE qualifiedName ('@' branch=identifier)?
SET updateAssignment (',' updateAssignment)*
(WHERE where=booleanExpression)? #update
| MERGE INTO qualifiedName (AS? identifier)?
| MERGE INTO
qualifiedName ('@' branch=identifier)? (AS? alias=identifier)?
USING relation ON expression mergeCase+ #merge
;

Expand Down Expand Up @@ -940,7 +950,7 @@ entityKind
;

grantObject
: entityKind? qualifiedName
: (BRANCH branch=identifier IN)? entityKind? qualifiedName
;

ownedEntityKind
Expand Down Expand Up @@ -1002,11 +1012,11 @@ authorizationUser
nonReserved
// IMPORTANT: this rule must only contain tokens. Nested rules are not supported. See SqlParser.exitNonReserved
: ABSENT | ADD | ADMIN | AFTER | ALL | ANALYZE | ANY | ARRAY | ASC | AT | AUTHORIZATION
| BEGIN | BERNOULLI | BOTH
| BEGIN | BERNOULLI | BOTH | BRANCH | BRANCHES
| CALL | CALLED | CASCADE | CATALOG | CATALOGS | COLUMN | COLUMNS | COMMENT | COMMIT | COMMITTED | CONDITIONAL | COPARTITION | COUNT | CURRENT
| DATA | DATE | DAY | DECLARE | DEFAULT | DEFINE | DEFINER | DENY | DESC | DESCRIPTOR | DETERMINISTIC | DISTRIBUTED | DO | DOUBLE
| ELSEIF | EMPTY | ENCODING | ERROR | EXCLUDING | EXECUTE | EXPLAIN
| FETCH | FILTER | FINAL | FIRST | FOLLOWING | FORMAT | FUNCTION | FUNCTIONS
| FAST | FETCH | FILTER | FINAL | FIRST | FOLLOWING | FORMAT | FORWARD | FUNCTION | FUNCTIONS
| GRACE | GRANT | GRANTED | GRANTS | GRAPHVIZ | GROUPS
| HOUR
| IF | IGNORE | IMMEDIATE | INCLUDING | INITIAL | INPUT | INTERVAL | INVOKER | IO | ITERATE | ISOLATION
Expand Down Expand Up @@ -1047,6 +1057,8 @@ BEGIN: 'BEGIN';
BERNOULLI: 'BERNOULLI';
BETWEEN: 'BETWEEN';
BOTH: 'BOTH';
BRANCH: 'BRANCH';
BRANCHES: 'BRANCHES';
BY: 'BY';
CALL: 'CALL';
CALLED: 'CALLED';
Expand Down Expand Up @@ -1109,13 +1121,15 @@ EXISTS: 'EXISTS';
EXPLAIN: 'EXPLAIN';
EXTRACT: 'EXTRACT';
FALSE: 'FALSE';
FAST: 'FAST';
FETCH: 'FETCH';
FILTER: 'FILTER';
FINAL: 'FINAL';
FIRST: 'FIRST';
FOLLOWING: 'FOLLOWING';
FOR: 'FOR';
FORMAT: 'FORMAT';
FORWARD: 'FORWARD';
FROM: 'FROM';
FULL: 'FULL';
FUNCTION: 'FUNCTION';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ public void test()
"BERNOULLI",
"BETWEEN",
"BOTH",
"BRANCH",
"BRANCHES",
"BY",
"CALL",
"CALLED",
Expand Down Expand Up @@ -106,13 +108,15 @@ public void test()
"EXPLAIN",
"EXTRACT",
"FALSE",
"FAST",
"FETCH",
"FILTER",
"FINAL",
"FIRST",
"FOLLOWING",
"FOR",
"FORMAT",
"FORWARD",
"FROM",
"FULL",
"FUNCTION",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import com.google.inject.Singleton;
import io.trino.SystemSessionPropertiesProvider;
import io.trino.metadata.AnalyzePropertyManager;
import io.trino.metadata.BranchPropertyManager;
import io.trino.metadata.CatalogProcedures;
import io.trino.metadata.CatalogTableFunctions;
import io.trino.metadata.CatalogTableProcedures;
Expand Down Expand Up @@ -156,6 +157,13 @@ public static AnalyzePropertyManager createAnalyzePropertyManager(ConnectorServi
return new AnalyzePropertyManager(new ConnectorCatalogServiceProvider<>("analyze properties", connectorServicesProvider, ConnectorServices::getAnalyzeProperties));
}

@Provides
@Singleton
public static BranchPropertyManager createBranchPropertyManager(ConnectorServicesProvider connectorServicesProvider)
{
return new BranchPropertyManager(new ConnectorCatalogServiceProvider<>("branch properties", connectorServicesProvider, ConnectorServices::getAnalyzeProperties));
}

@Provides
@Singleton
public static TableProceduresPropertyManager createTableProceduresPropertyManager(ConnectorServicesProvider connectorServicesProvider)
Expand Down
114 changes: 114 additions & 0 deletions core/trino-main/src/main/java/io/trino/execution/CreateBranchTask.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
/*
* 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.util.concurrent.ListenableFuture;
import com.google.inject.Inject;
import io.trino.Session;
import io.trino.execution.warnings.WarningCollector;
import io.trino.metadata.BranchPropertyManager;
import io.trino.metadata.Metadata;
import io.trino.metadata.QualifiedObjectName;
import io.trino.metadata.TableHandle;
import io.trino.security.AccessControl;
import io.trino.spi.connector.CatalogHandle;
import io.trino.sql.PlannerContext;
import io.trino.sql.tree.CreateBranch;
import io.trino.sql.tree.Expression;
import io.trino.sql.tree.NodeRef;
import io.trino.sql.tree.Parameter;

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

import static com.google.common.util.concurrent.Futures.immediateVoidFuture;
import static io.trino.execution.ParameterExtractor.bindParameters;
import static io.trino.metadata.MetadataUtil.createQualifiedObjectName;
import static io.trino.metadata.MetadataUtil.getRequiredCatalogHandle;
import static io.trino.spi.StandardErrorCode.GENERIC_USER_ERROR;
import static io.trino.spi.StandardErrorCode.NOT_SUPPORTED;
import static io.trino.spi.StandardErrorCode.TABLE_NOT_FOUND;
import static io.trino.sql.analyzer.SemanticExceptions.semanticException;
import static io.trino.sql.tree.SaveMode.FAIL;
import static io.trino.sql.tree.SaveMode.REPLACE;
import static java.util.Objects.requireNonNull;

public class CreateBranchTask
implements DataDefinitionTask<CreateBranch>
{
private final PlannerContext plannerContext;
private final Metadata metadata;
private final AccessControl accessControl;
private final BranchPropertyManager branchPropertyManager;

@Inject
public CreateBranchTask(PlannerContext plannerContext, Metadata metadata, AccessControl accessControl, BranchPropertyManager branchPropertyManager)
{
this.plannerContext = requireNonNull(plannerContext, "plannerContext is null");
this.metadata = requireNonNull(metadata, "metadata is null");
this.accessControl = requireNonNull(accessControl, "accessControl is null");
this.branchPropertyManager = requireNonNull(branchPropertyManager, "branchPropertyManager is null");
}

@Override
public String getName()
{
return "CREATE BRANCH";
}

@Override
public ListenableFuture<Void> execute(CreateBranch statement, QueryStateMachine stateMachine, List<Expression> parameters, WarningCollector warningCollector)
{
Session session = stateMachine.getSession();

QualifiedObjectName table = createQualifiedObjectName(session, statement, statement.getTableName());
String branch = statement.getBranchName().getValue();

if (metadata.isMaterializedView(session, table)) {
throw semanticException(GENERIC_USER_ERROR, statement, "Dropping branch from materialized view is not supported");
}
if (metadata.isView(session, table)) {
throw semanticException(GENERIC_USER_ERROR, statement, "Dropping branch from view is not supported");
}
Optional<TableHandle> tableHandle = metadata.getRedirectionAwareTableHandle(session, table).tableHandle();
if (tableHandle.isEmpty()) {
throw semanticException(TABLE_NOT_FOUND, statement, "Table '%s' does not exist", table);
}

if (metadata.branchExists(session, table, branch) && statement.getSaveMode() != REPLACE) {
if (statement.getSaveMode() == FAIL) {
throw semanticException(NOT_SUPPORTED, statement, "Branch '%s' already exists", branch);
}
return immediateVoidFuture();
}

Map<NodeRef<Parameter>, Expression> parameterLookup = bindParameters(statement, parameters);
CatalogHandle catalogHandle = getRequiredCatalogHandle(metadata, session, statement, table.catalogName());
Map<String, Object> properties = branchPropertyManager.getProperties(
table.catalogName(),
catalogHandle,
statement.getProperties(),
session,
plannerContext,
accessControl,
parameterLookup,
true);

accessControl.checkCanCreateBranch(session.toSecurityContext(), table, branch);
metadata.createBranch(session, tableHandle.get(), branch, properties);

return immediateVoidFuture();
}
}
22 changes: 18 additions & 4 deletions core/trino-main/src/main/java/io/trino/execution/DenyTask.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import io.trino.spi.security.Privilege;
import io.trino.sql.tree.Deny;
import io.trino.sql.tree.Expression;
import io.trino.sql.tree.Identifier;

import java.util.List;
import java.util.Optional;
Expand Down Expand Up @@ -82,6 +83,10 @@ else if (entityKind.equalsIgnoreCase("SCHEMA")) {

private static void executeDenyOnSchema(Session session, Deny statement, Metadata metadata, AccessControl accessControl)
{
if (statement.getGrantObject().getBranch().isEmpty()) {
throw semanticException(NOT_SUPPORTED, statement, "Denying on branch is not supported");
}

CatalogSchemaName schemaName = createCatalogSchemaName(session, statement, Optional.of(statement.getGrantObject().getName()));

if (!metadata.schemaExists(session, schemaName)) {
Expand All @@ -99,6 +104,7 @@ private static void executeDenyOnSchema(Session session, Deny statement, Metadat
private static void executeDenyOnTable(Session session, Deny statement, Metadata metadata, AccessControl accessControl)
{
QualifiedObjectName tableName = createQualifiedObjectName(session, statement, statement.getGrantObject().getName());
Optional<Identifier> branch = statement.getGrantObject().getBranch();

if (!metadata.isMaterializedView(session, tableName) && !metadata.isView(session, tableName)) {
RedirectionAwareTableHandle redirection = metadata.getRedirectionAwareTableHandle(session, tableName);
Expand All @@ -112,15 +118,23 @@ private static void executeDenyOnTable(Session session, Deny statement, Metadata

Set<Privilege> privileges = parseStatementPrivileges(statement, statement.getPrivileges());

for (Privilege privilege : privileges) {
accessControl.checkCanDenyTablePrivilege(session.toSecurityContext(), privilege, tableName, createPrincipal(statement.getGrantee()));
if (branch.isEmpty()) {
privileges.forEach(privilege -> accessControl.checkCanDenyTablePrivilege(session.toSecurityContext(), privilege, tableName, createPrincipal(statement.getGrantee())));
metadata.denyTablePrivileges(session, tableName, privileges, createPrincipal(statement.getGrantee()));
}
else {
String branchName = branch.get().getValue();
privileges.forEach(privilege -> accessControl.checkCanDenyTableBranchPrivilege(session.toSecurityContext(), privilege, tableName, branchName, createPrincipal(statement.getGrantee())));
metadata.denyTableBranchPrivileges(session, tableName, branchName, privileges, createPrincipal(statement.getGrantee()));
}

metadata.denyTablePrivileges(session, tableName, privileges, createPrincipal(statement.getGrantee()));
}

private static void executeDenyOnEntity(Session session, Deny statement, Metadata metadata, String entityKind, AccessControl accessControl)
{
if (statement.getGrantObject().getBranch().isEmpty()) {
throw semanticException(NOT_SUPPORTED, statement, "Denying on branch is not supported");
}

EntityKindAndName entity = createEntityKindAndName(entityKind, statement.getGrantObject().getName());
Set<EntityPrivilege> privileges = fetchEntityKindPrivileges(entityKind, metadata, statement.getPrivileges());

Expand Down
Loading
Loading