Search in sources :

Example 1 with AccessControl

use of io.trino.security.AccessControl in project trino by trinodb.

the class ColumnJdbcTable method applyFilter.

@Override
public TupleDomain<ColumnHandle> applyFilter(ConnectorSession connectorSession, Constraint constraint) {
    TupleDomain<ColumnHandle> tupleDomain = constraint.getSummary();
    if (tupleDomain.isNone() || constraint.predicate().isEmpty()) {
        return tupleDomain;
    }
    Predicate<Map<ColumnHandle, NullableValue>> predicate = constraint.predicate().get();
    Set<ColumnHandle> predicateColumns = constraint.getPredicateColumns().orElseThrow(() -> new VerifyException("columns not present for a predicate"));
    boolean hasSchemaPredicate = predicateColumns.contains(TABLE_SCHEMA_COLUMN);
    boolean hasTablePredicate = predicateColumns.contains(TABLE_NAME_COLUMN);
    if (!hasSchemaPredicate && !hasTablePredicate) {
        // No filter on schema name and table name at all.
        return tupleDomain;
    }
    Session session = ((FullConnectorSession) connectorSession).getSession();
    Optional<String> catalogFilter = tryGetSingleVarcharValue(tupleDomain, TABLE_CATALOG_COLUMN);
    Optional<String> schemaFilter = tryGetSingleVarcharValue(tupleDomain, TABLE_SCHEMA_COLUMN);
    Optional<String> tableFilter = tryGetSingleVarcharValue(tupleDomain, TABLE_NAME_COLUMN);
    if (schemaFilter.isPresent() && tableFilter.isPresent()) {
        // No need to narrow down the domain.
        return tupleDomain;
    }
    List<String> catalogs = listCatalogs(session, metadata, accessControl, catalogFilter).keySet().stream().filter(catalogName -> predicate.test(ImmutableMap.of(TABLE_CATALOG_COLUMN, toNullableValue(catalogName)))).collect(toImmutableList());
    List<CatalogSchemaName> schemas = catalogs.stream().flatMap(catalogName -> listSchemas(session, metadata, accessControl, catalogName, schemaFilter).stream().filter(schemaName -> !hasSchemaPredicate || predicate.test(ImmutableMap.of(TABLE_CATALOG_COLUMN, toNullableValue(catalogName), TABLE_SCHEMA_COLUMN, toNullableValue(schemaName)))).map(schemaName -> new CatalogSchemaName(catalogName, schemaName))).collect(toImmutableList());
    if (!hasTablePredicate) {
        return TupleDomain.withColumnDomains(ImmutableMap.<ColumnHandle, Domain>builder().put(TABLE_CATALOG_COLUMN, schemas.stream().map(CatalogSchemaName::getCatalogName).collect(toVarcharDomain()).simplify(MAX_DOMAIN_SIZE)).put(TABLE_SCHEMA_COLUMN, schemas.stream().map(CatalogSchemaName::getSchemaName).collect(toVarcharDomain()).simplify(MAX_DOMAIN_SIZE)).buildOrThrow());
    }
    List<CatalogSchemaTableName> tables = schemas.stream().flatMap(schema -> {
        QualifiedTablePrefix tablePrefix = tableFilter.isPresent() ? new QualifiedTablePrefix(schema.getCatalogName(), schema.getSchemaName(), tableFilter.get()) : new QualifiedTablePrefix(schema.getCatalogName(), schema.getSchemaName());
        return listTables(session, metadata, accessControl, tablePrefix).stream().filter(schemaTableName -> predicate.test(ImmutableMap.of(TABLE_CATALOG_COLUMN, toNullableValue(schema.getCatalogName()), TABLE_SCHEMA_COLUMN, toNullableValue(schemaTableName.getSchemaName()), TABLE_NAME_COLUMN, toNullableValue(schemaTableName.getTableName())))).map(schemaTableName -> new CatalogSchemaTableName(schema.getCatalogName(), schemaTableName.getSchemaName(), schemaTableName.getTableName()));
    }).collect(toImmutableList());
    return TupleDomain.withColumnDomains(ImmutableMap.<ColumnHandle, Domain>builder().put(TABLE_CATALOG_COLUMN, tables.stream().map(CatalogSchemaTableName::getCatalogName).collect(toVarcharDomain()).simplify(MAX_DOMAIN_SIZE)).put(TABLE_SCHEMA_COLUMN, tables.stream().map(catalogSchemaTableName -> catalogSchemaTableName.getSchemaTableName().getSchemaName()).collect(toVarcharDomain()).simplify(MAX_DOMAIN_SIZE)).put(TABLE_NAME_COLUMN, tables.stream().map(catalogSchemaTableName -> catalogSchemaTableName.getSchemaTableName().getTableName()).collect(toVarcharDomain()).simplify(MAX_DOMAIN_SIZE)).buildOrThrow());
}
Also used : FilterUtil.tryGetSingleVarcharValue(io.trino.connector.system.jdbc.FilterUtil.tryGetSingleVarcharValue) TableMetadataBuilder.tableMetadataBuilder(io.trino.metadata.MetadataUtil.TableMetadataBuilder.tableMetadataBuilder) TimestampWithTimeZoneType(io.trino.spi.type.TimestampWithTimeZoneType) Slices(io.airlift.slice.Slices) Map(java.util.Map) CatalogSchemaName(io.trino.spi.connector.CatalogSchemaName) Slices.utf8Slice(io.airlift.slice.Slices.utf8Slice) Collector(java.util.stream.Collector) INTEGER(io.trino.spi.type.IntegerType.INTEGER) ENGLISH(java.util.Locale.ENGLISH) SMALLINT(io.trino.spi.type.SmallintType.SMALLINT) MetadataListing.listCatalogs(io.trino.metadata.MetadataListing.listCatalogs) ImmutableMap(com.google.common.collect.ImmutableMap) TypeUtils.getDisplayLabel(io.trino.type.TypeUtils.getDisplayLabel) Predicate(java.util.function.Predicate) Domain(io.trino.spi.predicate.Domain) Collection(java.util.Collection) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Set(java.util.Set) ArrayType(io.trino.spi.type.ArrayType) Math.min(java.lang.Math.min) Collectors(java.util.stream.Collectors) SchemaTableName(io.trino.spi.connector.SchemaTableName) ZoneId(java.time.ZoneId) List(java.util.List) AccessControl(io.trino.security.AccessControl) BIGINT(io.trino.spi.type.BigintType.BIGINT) CatalogSchemaTableName(io.trino.spi.connector.CatalogSchemaTableName) Entry(java.util.Map.Entry) Optional(java.util.Optional) DecimalType(io.trino.spi.type.DecimalType) DATE(io.trino.spi.type.DateType.DATE) REAL(io.trino.spi.type.RealType.REAL) Session(io.trino.Session) TimeWithTimeZoneType(io.trino.spi.type.TimeWithTimeZoneType) Types(java.sql.Types) Constraint(io.trino.spi.connector.Constraint) TimeType(io.trino.spi.type.TimeType) FullConnectorSession(io.trino.FullConnectorSession) NullableValue(io.trino.spi.predicate.NullableValue) ColumnMetadata(io.trino.spi.connector.ColumnMetadata) Type(io.trino.spi.type.Type) BOOLEAN(io.trino.spi.type.BooleanType.BOOLEAN) VarcharType.createUnboundedVarcharType(io.trino.spi.type.VarcharType.createUnboundedVarcharType) ConnectorTableMetadata(io.trino.spi.connector.ConnectorTableMetadata) DatabaseMetaData(java.sql.DatabaseMetaData) TimestampType(io.trino.spi.type.TimestampType) Inject(javax.inject.Inject) VarcharType(io.trino.spi.type.VarcharType) Objects.requireNonNull(java.util.Objects.requireNonNull) ColumnHandle(io.trino.spi.connector.ColumnHandle) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) VARBINARY(io.trino.spi.type.VarbinaryType.VARBINARY) QualifiedTablePrefix(io.trino.metadata.QualifiedTablePrefix) MetadataListing.listTables(io.trino.metadata.MetadataListing.listTables) VerifyException(com.google.common.base.VerifyException) MetadataListing.listSchemas(io.trino.metadata.MetadataListing.listSchemas) RecordCursor(io.trino.spi.connector.RecordCursor) MetadataListing.listTableColumns(io.trino.metadata.MetadataListing.listTableColumns) ConnectorSession(io.trino.spi.connector.ConnectorSession) TupleDomain(io.trino.spi.predicate.TupleDomain) InMemoryRecordSet(io.trino.spi.connector.InMemoryRecordSet) Builder(io.trino.spi.connector.InMemoryRecordSet.Builder) DOUBLE(io.trino.spi.type.DoubleType.DOUBLE) SystemColumnHandle(io.trino.connector.system.SystemColumnHandle) CharType(io.trino.spi.type.CharType) SystemSessionProperties.isOmitDateTimeTypePrecision(io.trino.SystemSessionProperties.isOmitDateTimeTypePrecision) Metadata(io.trino.metadata.Metadata) FilterUtil.tablePrefix(io.trino.connector.system.jdbc.FilterUtil.tablePrefix) TINYINT(io.trino.spi.type.TinyintType.TINYINT) ConnectorTransactionHandle(io.trino.spi.connector.ConnectorTransactionHandle) ColumnHandle(io.trino.spi.connector.ColumnHandle) SystemColumnHandle(io.trino.connector.system.SystemColumnHandle) CatalogSchemaTableName(io.trino.spi.connector.CatalogSchemaTableName) QualifiedTablePrefix(io.trino.metadata.QualifiedTablePrefix) VerifyException(com.google.common.base.VerifyException) CatalogSchemaName(io.trino.spi.connector.CatalogSchemaName) Domain(io.trino.spi.predicate.Domain) TupleDomain(io.trino.spi.predicate.TupleDomain) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) Session(io.trino.Session) FullConnectorSession(io.trino.FullConnectorSession) ConnectorSession(io.trino.spi.connector.ConnectorSession) FullConnectorSession(io.trino.FullConnectorSession)

Example 2 with AccessControl

use of io.trino.security.AccessControl in project trino by trinodb.

the class TestSetRoleTask method setUp.

@BeforeClass
public void setUp() {
    queryRunner = LocalQueryRunner.create(TEST_SESSION);
    MockConnectorFactory mockConnectorFactory = MockConnectorFactory.builder().withListRoleGrants((connectorSession, roles, grantees, limit) -> ImmutableSet.of(new RoleGrant(new TrinoPrincipal(USER, USER_NAME), ROLE_NAME, false))).build();
    queryRunner.createCatalog(CATALOG_NAME, mockConnectorFactory, ImmutableMap.of());
    MockConnectorFactory systemConnectorFactory = MockConnectorFactory.builder().withName("system_role_connector").build();
    queryRunner.createCatalog(SYSTEM_ROLE_CATALOG_NAME, systemConnectorFactory, ImmutableMap.of());
    transactionManager = queryRunner.getTransactionManager();
    accessControl = queryRunner.getAccessControl();
    metadata = queryRunner.getMetadata();
    parser = queryRunner.getSqlParser();
    executor = newCachedThreadPool(daemonThreadsNamed("test-set-role-task-executor-%s"));
}
Also used : TransactionManager(io.trino.transaction.TransactionManager) USER(io.trino.spi.security.PrincipalType.USER) ParsingOptions(io.trino.sql.parser.ParsingOptions) Assert.assertEquals(org.testng.Assert.assertEquals) Test(org.testng.annotations.Test) TrinoExceptionAssert.assertTrinoExceptionThrownBy(io.trino.testing.assertions.TrinoExceptionAssert.assertTrinoExceptionThrownBy) NOT_SUPPORTED(io.trino.spi.StandardErrorCode.NOT_SUPPORTED) ImmutableList(com.google.common.collect.ImmutableList) MockConnectorFactory(io.trino.connector.MockConnectorFactory) Threads.daemonThreadsNamed(io.airlift.concurrent.Threads.daemonThreadsNamed) Identity(io.trino.spi.security.Identity) LocalQueryRunner(io.trino.testing.LocalQueryRunner) Map(java.util.Map) TEST_SESSION(io.trino.SessionTestUtils.TEST_SESSION) SqlParser(io.trino.sql.parser.SqlParser) URI(java.net.URI) ExecutorService(java.util.concurrent.ExecutorService) ResourceGroupId(io.trino.spi.resourcegroups.ResourceGroupId) AfterClass(org.testng.annotations.AfterClass) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) BeforeClass(org.testng.annotations.BeforeClass) CATALOG_NOT_FOUND(io.trino.spi.StandardErrorCode.CATALOG_NOT_FOUND) RoleGrant(io.trino.spi.security.RoleGrant) SelectedRole(io.trino.spi.security.SelectedRole) TestingSession.testSessionBuilder(io.trino.testing.TestingSession.testSessionBuilder) AccessControl(io.trino.security.AccessControl) TrinoPrincipal(io.trino.spi.security.TrinoPrincipal) Executors.newCachedThreadPool(java.util.concurrent.Executors.newCachedThreadPool) SetRole(io.trino.sql.tree.SetRole) WarningCollector(io.trino.execution.warnings.WarningCollector) Metadata(io.trino.metadata.Metadata) Optional(java.util.Optional) ROLE_NOT_FOUND(io.trino.spi.StandardErrorCode.ROLE_NOT_FOUND) RoleGrant(io.trino.spi.security.RoleGrant) MockConnectorFactory(io.trino.connector.MockConnectorFactory) TrinoPrincipal(io.trino.spi.security.TrinoPrincipal) BeforeClass(org.testng.annotations.BeforeClass)

Example 3 with AccessControl

use of io.trino.security.AccessControl in project trino by trinodb.

the class CallTask method execute.

@Override
public ListenableFuture<Void> execute(Call call, QueryStateMachine stateMachine, List<Expression> parameters, WarningCollector warningCollector) {
    if (!transactionManager.isAutoCommit(stateMachine.getSession().getRequiredTransactionId())) {
        throw new TrinoException(NOT_SUPPORTED, "Procedures cannot be called within a transaction (use autocommit mode)");
    }
    Session session = stateMachine.getSession();
    QualifiedObjectName procedureName = createQualifiedObjectName(session, call, call.getName());
    CatalogName catalogName = plannerContext.getMetadata().getCatalogHandle(stateMachine.getSession(), procedureName.getCatalogName()).orElseThrow(() -> semanticException(CATALOG_NOT_FOUND, call, "Catalog '%s' does not exist", procedureName.getCatalogName()));
    Procedure procedure = procedureRegistry.resolve(catalogName, procedureName.asSchemaTableName());
    // map declared argument names to positions
    Map<String, Integer> positions = new HashMap<>();
    for (int i = 0; i < procedure.getArguments().size(); i++) {
        positions.put(procedure.getArguments().get(i).getName(), i);
    }
    // per specification, do not allow mixing argument types
    Predicate<CallArgument> hasName = argument -> argument.getName().isPresent();
    boolean anyNamed = call.getArguments().stream().anyMatch(hasName);
    boolean allNamed = call.getArguments().stream().allMatch(hasName);
    if (anyNamed && !allNamed) {
        throw semanticException(INVALID_ARGUMENTS, call, "Named and positional arguments cannot be mixed");
    }
    // get the argument names in call order
    Map<String, CallArgument> names = new LinkedHashMap<>();
    for (int i = 0; i < call.getArguments().size(); i++) {
        CallArgument argument = call.getArguments().get(i);
        if (argument.getName().isPresent()) {
            String name = argument.getName().get().getCanonicalValue();
            if (names.put(name, argument) != null) {
                throw semanticException(INVALID_ARGUMENTS, argument, "Duplicate procedure argument: %s", name);
            }
            if (!positions.containsKey(name)) {
                throw semanticException(INVALID_ARGUMENTS, argument, "Unknown argument name: %s", name);
            }
        } else if (i < procedure.getArguments().size()) {
            names.put(procedure.getArguments().get(i).getName(), argument);
        } else {
            throw semanticException(INVALID_ARGUMENTS, call, "Too many arguments for procedure");
        }
    }
    procedure.getArguments().stream().filter(Argument::isRequired).filter(argument -> !names.containsKey(argument.getName())).map(Argument::getName).findFirst().ifPresent(argument -> {
        throw semanticException(INVALID_ARGUMENTS, call, "Required procedure argument '%s' is missing", argument);
    });
    // get argument values
    Object[] values = new Object[procedure.getArguments().size()];
    Map<NodeRef<Parameter>, Expression> parameterLookup = parameterExtractor(call, parameters);
    for (Entry<String, CallArgument> entry : names.entrySet()) {
        CallArgument callArgument = entry.getValue();
        int index = positions.get(entry.getKey());
        Argument argument = procedure.getArguments().get(index);
        Expression expression = ExpressionTreeRewriter.rewriteWith(new ParameterRewriter(parameterLookup), callArgument.getValue());
        Type type = argument.getType();
        Object value = evaluateConstantExpression(expression, type, plannerContext, session, accessControl, parameterLookup);
        values[index] = toTypeObjectValue(session, type, value);
    }
    // fill values with optional arguments defaults
    for (int i = 0; i < procedure.getArguments().size(); i++) {
        Argument argument = procedure.getArguments().get(i);
        if (!names.containsKey(argument.getName())) {
            verify(argument.isOptional());
            values[i] = toTypeObjectValue(session, argument.getType(), argument.getDefaultValue());
        }
    }
    // validate arguments
    MethodType methodType = procedure.getMethodHandle().type();
    for (int i = 0; i < procedure.getArguments().size(); i++) {
        if ((values[i] == null) && methodType.parameterType(i).isPrimitive()) {
            String name = procedure.getArguments().get(i).getName();
            throw new TrinoException(INVALID_PROCEDURE_ARGUMENT, "Procedure argument cannot be null: " + name);
        }
    }
    // insert session argument
    List<Object> arguments = new ArrayList<>();
    Iterator<Object> valuesIterator = asList(values).iterator();
    for (Class<?> type : methodType.parameterList()) {
        if (ConnectorSession.class.equals(type)) {
            arguments.add(session.toConnectorSession(catalogName));
        } else if (ConnectorAccessControl.class.equals(type)) {
            arguments.add(new InjectedConnectorAccessControl(accessControl, session.toSecurityContext(), catalogName.getCatalogName()));
        } else {
            arguments.add(valuesIterator.next());
        }
    }
    accessControl.checkCanExecuteProcedure(session.toSecurityContext(), procedureName);
    stateMachine.setRoutines(ImmutableList.of(new RoutineInfo(procedureName.getObjectName(), session.getUser())));
    try {
        procedure.getMethodHandle().invokeWithArguments(arguments);
    } catch (Throwable t) {
        if (t instanceof InterruptedException) {
            Thread.currentThread().interrupt();
        }
        throwIfInstanceOf(t, TrinoException.class);
        throw new TrinoException(PROCEDURE_CALL_FAILED, t);
    }
    return immediateVoidFuture();
}
Also used : InjectedConnectorAccessControl(io.trino.security.InjectedConnectorAccessControl) TransactionManager(io.trino.transaction.TransactionManager) ParameterUtils.parameterExtractor(io.trino.sql.ParameterUtils.parameterExtractor) NOT_SUPPORTED(io.trino.spi.StandardErrorCode.NOT_SUPPORTED) CatalogName(io.trino.connector.CatalogName) Arrays.asList(java.util.Arrays.asList) Map(java.util.Map) SemanticExceptions.semanticException(io.trino.sql.analyzer.SemanticExceptions.semanticException) Argument(io.trino.spi.procedure.Procedure.Argument) Futures.immediateVoidFuture(com.google.common.util.concurrent.Futures.immediateVoidFuture) INVALID_ARGUMENTS(io.trino.spi.StandardErrorCode.INVALID_ARGUMENTS) Predicate(java.util.function.Predicate) ExpressionTreeRewriter(io.trino.sql.tree.ExpressionTreeRewriter) ConnectorAccessControl(io.trino.spi.connector.ConnectorAccessControl) TrinoException(io.trino.spi.TrinoException) TypeUtils.writeNativeValue(io.trino.spi.type.TypeUtils.writeNativeValue) List(java.util.List) AccessControl(io.trino.security.AccessControl) Parameter(io.trino.sql.tree.Parameter) Entry(java.util.Map.Entry) Expression(io.trino.sql.tree.Expression) PROCEDURE_CALL_FAILED(io.trino.spi.StandardErrorCode.PROCEDURE_CALL_FAILED) Session(io.trino.Session) PlannerContext(io.trino.sql.PlannerContext) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) ExpressionInterpreter.evaluateConstantExpression(io.trino.sql.planner.ExpressionInterpreter.evaluateConstantExpression) RoutineInfo(io.trino.spi.eventlistener.RoutineInfo) Type(io.trino.spi.type.Type) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) LinkedHashMap(java.util.LinkedHashMap) INVALID_PROCEDURE_ARGUMENT(io.trino.spi.StandardErrorCode.INVALID_PROCEDURE_ARGUMENT) ImmutableList(com.google.common.collect.ImmutableList) Procedure(io.trino.spi.procedure.Procedure) Verify.verify(com.google.common.base.Verify.verify) MetadataUtil.createQualifiedObjectName(io.trino.metadata.MetadataUtil.createQualifiedObjectName) NodeRef(io.trino.sql.tree.NodeRef) Objects.requireNonNull(java.util.Objects.requireNonNull) Iterator(java.util.Iterator) CATALOG_NOT_FOUND(io.trino.spi.StandardErrorCode.CATALOG_NOT_FOUND) ConnectorSession(io.trino.spi.connector.ConnectorSession) Throwables.throwIfInstanceOf(com.google.common.base.Throwables.throwIfInstanceOf) CallArgument(io.trino.sql.tree.CallArgument) Call(io.trino.sql.tree.Call) MethodType(java.lang.invoke.MethodType) QualifiedObjectName(io.trino.metadata.QualifiedObjectName) ProcedureRegistry(io.trino.metadata.ProcedureRegistry) WarningCollector(io.trino.execution.warnings.WarningCollector) BlockBuilder(io.trino.spi.block.BlockBuilder) ParameterRewriter(io.trino.sql.planner.ParameterRewriter) CallArgument(io.trino.sql.tree.CallArgument) Argument(io.trino.spi.procedure.Procedure.Argument) CallArgument(io.trino.sql.tree.CallArgument) ParameterRewriter(io.trino.sql.planner.ParameterRewriter) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) RoutineInfo(io.trino.spi.eventlistener.RoutineInfo) NodeRef(io.trino.sql.tree.NodeRef) Procedure(io.trino.spi.procedure.Procedure) MethodType(java.lang.invoke.MethodType) InjectedConnectorAccessControl(io.trino.security.InjectedConnectorAccessControl) ConnectorAccessControl(io.trino.spi.connector.ConnectorAccessControl) MetadataUtil.createQualifiedObjectName(io.trino.metadata.MetadataUtil.createQualifiedObjectName) QualifiedObjectName(io.trino.metadata.QualifiedObjectName) InjectedConnectorAccessControl(io.trino.security.InjectedConnectorAccessControl) Type(io.trino.spi.type.Type) MethodType(java.lang.invoke.MethodType) Expression(io.trino.sql.tree.Expression) ExpressionInterpreter.evaluateConstantExpression(io.trino.sql.planner.ExpressionInterpreter.evaluateConstantExpression) TrinoException(io.trino.spi.TrinoException) CatalogName(io.trino.connector.CatalogName) Session(io.trino.Session) ConnectorSession(io.trino.spi.connector.ConnectorSession)

Example 4 with AccessControl

use of io.trino.security.AccessControl in project trino by trinodb.

the class CreateTableTask method internalExecute.

@VisibleForTesting
ListenableFuture<Void> internalExecute(CreateTable statement, Session session, List<Expression> parameters, Consumer<Output> outputConsumer) {
    checkArgument(!statement.getElements().isEmpty(), "no columns for table");
    Map<NodeRef<Parameter>, Expression> parameterLookup = parameterExtractor(statement, parameters);
    QualifiedObjectName tableName = createQualifiedObjectName(session, statement, statement.getName());
    Optional<TableHandle> tableHandle = plannerContext.getMetadata().getTableHandle(session, tableName);
    if (tableHandle.isPresent()) {
        if (!statement.isNotExists()) {
            throw semanticException(TABLE_ALREADY_EXISTS, statement, "Table '%s' already exists", tableName);
        }
        return immediateVoidFuture();
    }
    CatalogName catalogName = getRequiredCatalogHandle(plannerContext.getMetadata(), session, statement, tableName.getCatalogName());
    LinkedHashMap<String, ColumnMetadata> columns = new LinkedHashMap<>();
    Map<String, Object> inheritedProperties = ImmutableMap.of();
    boolean includingProperties = false;
    for (TableElement element : statement.getElements()) {
        if (element instanceof ColumnDefinition) {
            ColumnDefinition column = (ColumnDefinition) element;
            String name = column.getName().getValue().toLowerCase(Locale.ENGLISH);
            Type type;
            try {
                type = plannerContext.getTypeManager().getType(toTypeSignature(column.getType()));
            } catch (TypeNotFoundException e) {
                throw semanticException(TYPE_NOT_FOUND, element, "Unknown type '%s' for column '%s'", column.getType(), column.getName());
            }
            if (type.equals(UNKNOWN)) {
                throw semanticException(COLUMN_TYPE_UNKNOWN, element, "Unknown type '%s' for column '%s'", column.getType(), column.getName());
            }
            if (columns.containsKey(name)) {
                throw semanticException(DUPLICATE_COLUMN_NAME, column, "Column name '%s' specified more than once", column.getName());
            }
            if (!column.isNullable() && !plannerContext.getMetadata().getConnectorCapabilities(session, catalogName).contains(NOT_NULL_COLUMN_CONSTRAINT)) {
                throw semanticException(NOT_SUPPORTED, column, "Catalog '%s' does not support non-null column for column name '%s'", catalogName.getCatalogName(), column.getName());
            }
            Map<String, Object> columnProperties = columnPropertyManager.getProperties(catalogName, column.getProperties(), session, plannerContext, accessControl, parameterLookup, true);
            columns.put(name, ColumnMetadata.builder().setName(name).setType(type).setNullable(column.isNullable()).setComment(column.getComment()).setProperties(columnProperties).build());
        } else if (element instanceof LikeClause) {
            LikeClause likeClause = (LikeClause) element;
            QualifiedObjectName originalLikeTableName = createQualifiedObjectName(session, statement, likeClause.getTableName());
            if (plannerContext.getMetadata().getCatalogHandle(session, originalLikeTableName.getCatalogName()).isEmpty()) {
                throw semanticException(CATALOG_NOT_FOUND, statement, "LIKE table catalog '%s' does not exist", originalLikeTableName.getCatalogName());
            }
            RedirectionAwareTableHandle redirection = plannerContext.getMetadata().getRedirectionAwareTableHandle(session, originalLikeTableName);
            TableHandle likeTable = redirection.getTableHandle().orElseThrow(() -> semanticException(TABLE_NOT_FOUND, statement, "LIKE table '%s' does not exist", originalLikeTableName));
            QualifiedObjectName likeTableName = redirection.getRedirectedTableName().orElse(originalLikeTableName);
            if (!tableName.getCatalogName().equals(likeTableName.getCatalogName())) {
                String message = "CREATE TABLE LIKE across catalogs is not supported";
                if (!originalLikeTableName.equals(likeTableName)) {
                    message += format(". LIKE table '%s' redirected to '%s'.", originalLikeTableName, likeTableName);
                }
                throw semanticException(NOT_SUPPORTED, statement, message);
            }
            TableMetadata likeTableMetadata = plannerContext.getMetadata().getTableMetadata(session, likeTable);
            Optional<LikeClause.PropertiesOption> propertiesOption = likeClause.getPropertiesOption();
            if (propertiesOption.isPresent() && propertiesOption.get() == LikeClause.PropertiesOption.INCLUDING) {
                if (includingProperties) {
                    throw semanticException(NOT_SUPPORTED, statement, "Only one LIKE clause can specify INCLUDING PROPERTIES");
                }
                includingProperties = true;
                inheritedProperties = likeTableMetadata.getMetadata().getProperties();
            }
            try {
                accessControl.checkCanSelectFromColumns(session.toSecurityContext(), likeTableName, likeTableMetadata.getColumns().stream().map(ColumnMetadata::getName).collect(toImmutableSet()));
            } catch (AccessDeniedException e) {
                throw new AccessDeniedException("Cannot reference columns of table " + likeTableName);
            }
            if (propertiesOption.orElse(EXCLUDING) == INCLUDING) {
                try {
                    accessControl.checkCanShowCreateTable(session.toSecurityContext(), likeTableName);
                } catch (AccessDeniedException e) {
                    throw new AccessDeniedException("Cannot reference properties of table " + likeTableName);
                }
            }
            likeTableMetadata.getColumns().stream().filter(column -> !column.isHidden()).forEach(column -> {
                if (columns.containsKey(column.getName().toLowerCase(Locale.ENGLISH))) {
                    throw semanticException(DUPLICATE_COLUMN_NAME, element, "Column name '%s' specified more than once", column.getName());
                }
                columns.put(column.getName().toLowerCase(Locale.ENGLISH), column);
            });
        } else {
            throw new TrinoException(GENERIC_INTERNAL_ERROR, "Invalid TableElement: " + element.getClass().getName());
        }
    }
    Map<String, Object> properties = tablePropertyManager.getProperties(catalogName, statement.getProperties(), session, plannerContext, accessControl, parameterLookup, true);
    accessControl.checkCanCreateTable(session.toSecurityContext(), tableName, properties);
    Set<String> specifiedPropertyKeys = statement.getProperties().stream().map(property -> property.getName().getValue()).collect(toImmutableSet());
    Map<String, Object> finalProperties = combineProperties(specifiedPropertyKeys, properties, inheritedProperties);
    ConnectorTableMetadata tableMetadata = new ConnectorTableMetadata(tableName.asSchemaTableName(), ImmutableList.copyOf(columns.values()), finalProperties, statement.getComment());
    try {
        plannerContext.getMetadata().createTable(session, tableName.getCatalogName(), tableMetadata, statement.isNotExists());
    } catch (TrinoException e) {
        // connectors are not required to handle the ignoreExisting flag
        if (!e.getErrorCode().equals(ALREADY_EXISTS.toErrorCode()) || !statement.isNotExists()) {
            throw e;
        }
    }
    outputConsumer.accept(new Output(tableName.getCatalogName(), tableName.getSchemaName(), tableName.getObjectName(), Optional.of(tableMetadata.getColumns().stream().map(column -> new OutputColumn(new Column(column.getName(), column.getType().toString()), ImmutableSet.of())).collect(toImmutableList()))));
    return immediateVoidFuture();
}
Also used : LikeClause(io.trino.sql.tree.LikeClause) TYPE_NOT_FOUND(io.trino.spi.StandardErrorCode.TYPE_NOT_FOUND) TypeNotFoundException(io.trino.spi.type.TypeNotFoundException) OutputColumn(io.trino.sql.analyzer.OutputColumn) UNKNOWN(io.trino.type.UnknownType.UNKNOWN) ParameterUtils.parameterExtractor(io.trino.sql.ParameterUtils.parameterExtractor) COLUMN_TYPE_UNKNOWN(io.trino.spi.StandardErrorCode.COLUMN_TYPE_UNKNOWN) NOT_SUPPORTED(io.trino.spi.StandardErrorCode.NOT_SUPPORTED) CatalogName(io.trino.connector.CatalogName) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) TABLE_ALREADY_EXISTS(io.trino.spi.StandardErrorCode.TABLE_ALREADY_EXISTS) Locale(java.util.Locale) TABLE_NOT_FOUND(io.trino.spi.StandardErrorCode.TABLE_NOT_FOUND) Map(java.util.Map) ALREADY_EXISTS(io.trino.spi.StandardErrorCode.ALREADY_EXISTS) SemanticExceptions.semanticException(io.trino.sql.analyzer.SemanticExceptions.semanticException) TableElement(io.trino.sql.tree.TableElement) Futures.immediateVoidFuture(com.google.common.util.concurrent.Futures.immediateVoidFuture) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) INCLUDING(io.trino.sql.tree.LikeClause.PropertiesOption.INCLUDING) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) TypeSignatureTranslator.toTypeSignature(io.trino.sql.analyzer.TypeSignatureTranslator.toTypeSignature) Set(java.util.Set) TrinoException(io.trino.spi.TrinoException) String.format(java.lang.String.format) DUPLICATE_COLUMN_NAME(io.trino.spi.StandardErrorCode.DUPLICATE_COLUMN_NAME) TableMetadata(io.trino.metadata.TableMetadata) List(java.util.List) CreateTable(io.trino.sql.tree.CreateTable) AccessControl(io.trino.security.AccessControl) Parameter(io.trino.sql.tree.Parameter) RedirectionAwareTableHandle(io.trino.metadata.RedirectionAwareTableHandle) Optional(java.util.Optional) Expression(io.trino.sql.tree.Expression) ColumnPropertyManager(io.trino.metadata.ColumnPropertyManager) Session(io.trino.Session) PlannerContext(io.trino.sql.PlannerContext) AccessDeniedException(io.trino.spi.security.AccessDeniedException) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) ColumnMetadata(io.trino.spi.connector.ColumnMetadata) Type(io.trino.spi.type.Type) ConnectorTableMetadata(io.trino.spi.connector.ConnectorTableMetadata) HashMap(java.util.HashMap) Inject(javax.inject.Inject) LinkedHashMap(java.util.LinkedHashMap) EXCLUDING(io.trino.sql.tree.LikeClause.PropertiesOption.EXCLUDING) ImmutableList(com.google.common.collect.ImmutableList) MetadataUtil.createQualifiedObjectName(io.trino.metadata.MetadataUtil.createQualifiedObjectName) NodeRef(io.trino.sql.tree.NodeRef) Objects.requireNonNull(java.util.Objects.requireNonNull) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) NOT_NULL_COLUMN_CONSTRAINT(io.trino.spi.connector.ConnectorCapabilities.NOT_NULL_COLUMN_CONSTRAINT) CATALOG_NOT_FOUND(io.trino.spi.StandardErrorCode.CATALOG_NOT_FOUND) MetadataUtil.getRequiredCatalogHandle(io.trino.metadata.MetadataUtil.getRequiredCatalogHandle) GENERIC_INTERNAL_ERROR(io.trino.spi.StandardErrorCode.GENERIC_INTERNAL_ERROR) Consumer(java.util.function.Consumer) LikeClause(io.trino.sql.tree.LikeClause) TableHandle(io.trino.metadata.TableHandle) QualifiedObjectName(io.trino.metadata.QualifiedObjectName) TablePropertyManager(io.trino.metadata.TablePropertyManager) WarningCollector(io.trino.execution.warnings.WarningCollector) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Output(io.trino.sql.analyzer.Output) ColumnDefinition(io.trino.sql.tree.ColumnDefinition) ColumnMetadata(io.trino.spi.connector.ColumnMetadata) AccessDeniedException(io.trino.spi.security.AccessDeniedException) TableElement(io.trino.sql.tree.TableElement) LinkedHashMap(java.util.LinkedHashMap) NodeRef(io.trino.sql.tree.NodeRef) OutputColumn(io.trino.sql.analyzer.OutputColumn) Output(io.trino.sql.analyzer.Output) ConnectorTableMetadata(io.trino.spi.connector.ConnectorTableMetadata) TableMetadata(io.trino.metadata.TableMetadata) ConnectorTableMetadata(io.trino.spi.connector.ConnectorTableMetadata) Optional(java.util.Optional) MetadataUtil.createQualifiedObjectName(io.trino.metadata.MetadataUtil.createQualifiedObjectName) QualifiedObjectName(io.trino.metadata.QualifiedObjectName) ColumnDefinition(io.trino.sql.tree.ColumnDefinition) Type(io.trino.spi.type.Type) Expression(io.trino.sql.tree.Expression) TypeNotFoundException(io.trino.spi.type.TypeNotFoundException) OutputColumn(io.trino.sql.analyzer.OutputColumn) TrinoException(io.trino.spi.TrinoException) RedirectionAwareTableHandle(io.trino.metadata.RedirectionAwareTableHandle) TableHandle(io.trino.metadata.TableHandle) CatalogName(io.trino.connector.CatalogName) RedirectionAwareTableHandle(io.trino.metadata.RedirectionAwareTableHandle) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 5 with AccessControl

use of io.trino.security.AccessControl in project trino by trinodb.

the class TestCallTask method executeCallTask.

private void executeCallTask(MethodHandle methodHandle, Function<TransactionManager, AccessControl> accessControlProvider) {
    TransactionManager transactionManager = queryRunner.getTransactionManager();
    ProcedureRegistry procedureRegistry = createProcedureRegistry(new Procedure("test", "testing_procedure", ImmutableList.of(), methodHandle));
    AccessControl accessControl = accessControlProvider.apply(transactionManager);
    PlannerContext plannerContext = plannerContextBuilder().withTransactionManager(transactionManager).build();
    new CallTask(transactionManager, plannerContext, accessControl, procedureRegistry).execute(new Call(QualifiedName.of("testing_procedure"), ImmutableList.of()), stateMachine(transactionManager, plannerContext.getMetadata(), accessControl), ImmutableList.of(), WarningCollector.NOOP);
}
Also used : Call(io.trino.sql.tree.Call) PlannerContext(io.trino.sql.PlannerContext) TransactionManager(io.trino.transaction.TransactionManager) ProcedureRegistry(io.trino.metadata.ProcedureRegistry) Procedure(io.trino.spi.procedure.Procedure) AllowAllAccessControl(io.trino.security.AllowAllAccessControl) DenyAllAccessControl(io.trino.security.DenyAllAccessControl) ConnectorAccessControl(io.trino.spi.connector.ConnectorAccessControl) AccessControl(io.trino.security.AccessControl) AllowAllSystemAccessControl(io.trino.plugin.base.security.AllowAllSystemAccessControl)

Aggregations

AccessControl (io.trino.security.AccessControl)7 Map (java.util.Map)6 Session (io.trino.Session)5 PlannerContext (io.trino.sql.PlannerContext)5 List (java.util.List)5 Objects.requireNonNull (java.util.Objects.requireNonNull)5 Optional (java.util.Optional)5 ImmutableList.toImmutableList (com.google.common.collect.ImmutableList.toImmutableList)4 CatalogName (io.trino.connector.CatalogName)4 WarningCollector (io.trino.execution.warnings.WarningCollector)4 Expression (io.trino.sql.tree.Expression)4 NodeRef (io.trino.sql.tree.NodeRef)4 Parameter (io.trino.sql.tree.Parameter)4 ImmutableList (com.google.common.collect.ImmutableList)3 ImmutableMap (com.google.common.collect.ImmutableMap)3 ImmutableSet.toImmutableSet (com.google.common.collect.ImmutableSet.toImmutableSet)3 Futures.immediateVoidFuture (com.google.common.util.concurrent.Futures.immediateVoidFuture)3 ListenableFuture (com.google.common.util.concurrent.ListenableFuture)3 MetadataUtil.createQualifiedObjectName (io.trino.metadata.MetadataUtil.createQualifiedObjectName)3 QualifiedObjectName (io.trino.metadata.QualifiedObjectName)3