Search in sources :

Example 1 with TypeNotFoundException

use of io.trino.spi.type.TypeNotFoundException 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 2 with TypeNotFoundException

use of io.trino.spi.type.TypeNotFoundException in project trino by trinodb.

the class MetadataManager method listTableColumns.

@Override
public List<TableColumnsMetadata> listTableColumns(Session session, QualifiedTablePrefix prefix) {
    requireNonNull(prefix, "prefix is null");
    Optional<CatalogMetadata> catalog = getOptionalCatalogMetadata(session, prefix.getCatalogName());
    // Track column metadata for every object name to resolve ties between table and view
    Map<SchemaTableName, Optional<List<ColumnMetadata>>> tableColumns = new HashMap<>();
    if (catalog.isPresent()) {
        CatalogMetadata catalogMetadata = catalog.get();
        SchemaTablePrefix tablePrefix = prefix.asSchemaTablePrefix();
        for (CatalogName catalogName : catalogMetadata.listConnectorIds()) {
            ConnectorMetadata metadata = catalogMetadata.getMetadataFor(session, catalogName);
            ConnectorSession connectorSession = session.toConnectorSession(catalogName);
            // Collect column metadata from tables
            metadata.streamTableColumns(connectorSession, tablePrefix).forEach(columnsMetadata -> tableColumns.put(columnsMetadata.getTable(), columnsMetadata.getColumns()));
            // Collect column metadata from views. if table and view names overlap, the view wins
            for (Entry<QualifiedObjectName, ViewInfo> entry : getViews(session, prefix).entrySet()) {
                ImmutableList.Builder<ColumnMetadata> columns = ImmutableList.builder();
                for (ViewColumn column : entry.getValue().getColumns()) {
                    try {
                        columns.add(new ColumnMetadata(column.getName(), typeManager.getType(column.getType())));
                    } catch (TypeNotFoundException e) {
                        throw new TrinoException(INVALID_VIEW, format("Unknown type '%s' for column '%s' in view: %s", column.getType(), column.getName(), entry.getKey()));
                    }
                }
                tableColumns.put(entry.getKey().asSchemaTableName(), Optional.of(columns.build()));
            }
            // if view and materialized view names overlap, the materialized view wins
            for (Entry<QualifiedObjectName, ViewInfo> entry : getMaterializedViews(session, prefix).entrySet()) {
                ImmutableList.Builder<ColumnMetadata> columns = ImmutableList.builder();
                for (ViewColumn column : entry.getValue().getColumns()) {
                    try {
                        columns.add(new ColumnMetadata(column.getName(), typeManager.getType(column.getType())));
                    } catch (TypeNotFoundException e) {
                        throw new TrinoException(INVALID_VIEW, format("Unknown type '%s' for column '%s' in materialized view: %s", column.getType(), column.getName(), entry.getKey()));
                    }
                }
                tableColumns.put(entry.getKey().asSchemaTableName(), Optional.of(columns.build()));
            }
        }
    }
    return tableColumns.entrySet().stream().map(entry -> new TableColumnsMetadata(entry.getKey(), entry.getValue())).collect(toImmutableList());
}
Also used : RedirectionAwareTableHandle.noRedirection(io.trino.metadata.RedirectionAwareTableHandle.noRedirection) TransactionManager(io.trino.transaction.TransactionManager) AggregateFunction(io.trino.spi.connector.AggregateFunction) TypeSignatureProvider.fromTypes(io.trino.sql.analyzer.TypeSignatureProvider.fromTypes) TypeOperators(io.trino.spi.type.TypeOperators) ConnectorTableExecuteHandle(io.trino.spi.connector.ConnectorTableExecuteHandle) Collections.singletonList(java.util.Collections.singletonList) NOT_SUPPORTED(io.trino.spi.StandardErrorCode.NOT_SUPPORTED) CatalogName(io.trino.connector.CatalogName) SystemSessionProperties.getRetryPolicy(io.trino.SystemSessionProperties.getRetryPolicy) ConnectorOutputTableHandle(io.trino.spi.connector.ConnectorOutputTableHandle) ConnectorTableHandle(io.trino.spi.connector.ConnectorTableHandle) Map(java.util.Map) ProjectionApplicationResult(io.trino.spi.connector.ProjectionApplicationResult) ENGLISH(java.util.Locale.ENGLISH) TABLE_REDIRECTION_ERROR(io.trino.spi.StandardErrorCode.TABLE_REDIRECTION_ERROR) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) MoreFutures.toListenableFuture(io.airlift.concurrent.MoreFutures.toListenableFuture) Set(java.util.Set) ConnectorExpressions(io.trino.sql.planner.ConnectorExpressions) LimitApplicationResult(io.trino.spi.connector.LimitApplicationResult) GuardedBy(javax.annotation.concurrent.GuardedBy) SchemaTableName(io.trino.spi.connector.SchemaTableName) MoreExecutors.directExecutor(com.google.common.util.concurrent.MoreExecutors.directExecutor) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) Stream(java.util.stream.Stream) TrinoPrincipal(io.trino.spi.security.TrinoPrincipal) ConnectorPartitioningHandle(io.trino.spi.connector.ConnectorPartitioningHandle) CatalogSchemaTableName(io.trino.spi.connector.CatalogSchemaTableName) SchemaTablePrefix(io.trino.spi.connector.SchemaTablePrefix) TableScanRedirectApplicationResult(io.trino.spi.connector.TableScanRedirectApplicationResult) FUNCTION_IMPLEMENTATION_MISSING(io.trino.spi.StandardErrorCode.FUNCTION_IMPLEMENTATION_MISSING) TableColumnsMetadata(io.trino.spi.connector.TableColumnsMetadata) INVALID_VIEW(io.trino.spi.StandardErrorCode.INVALID_VIEW) Session(io.trino.Session) Verify.verifyNotNull(com.google.common.base.Verify.verifyNotNull) ConnectorResolvedIndex(io.trino.spi.connector.ConnectorResolvedIndex) ConnectorInsertTableHandle(io.trino.spi.connector.ConnectorInsertTableHandle) JoinCondition(io.trino.spi.connector.JoinCondition) Slice(io.airlift.slice.Slice) ColumnMetadata(io.trino.spi.connector.ColumnMetadata) ConnectorTableMetadata(io.trino.spi.connector.ConnectorTableMetadata) QualifiedObjectName.convertFromSchemaTableName(io.trino.metadata.QualifiedObjectName.convertFromSchemaTableName) Variable(io.trino.spi.expression.Variable) TypeSignatureProvider.fromTypeSignatures(io.trino.sql.analyzer.TypeSignatureProvider.fromTypeSignatures) InMemoryTransactionManager.createTestTransactionManager(io.trino.transaction.InMemoryTransactionManager.createTestTransactionManager) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) OptionalLong(java.util.OptionalLong) Signature.mangleOperatorName(io.trino.metadata.Signature.mangleOperatorName) GrantInfo(io.trino.spi.security.GrantInfo) MaterializedViewFreshness(io.trino.spi.connector.MaterializedViewFreshness) Identity(io.trino.spi.security.Identity) ColumnHandle(io.trino.spi.connector.ColumnHandle) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) LinkedHashSet(java.util.LinkedHashSet) SCHEMA_NOT_FOUND(io.trino.spi.StandardErrorCode.SCHEMA_NOT_FOUND) ConstraintApplicationResult(io.trino.spi.connector.ConstraintApplicationResult) BlockTypeOperators(io.trino.type.BlockTypeOperators) ConnectorCapabilities(io.trino.spi.connector.ConnectorCapabilities) TESTING_TYPE_MANAGER(io.trino.type.InternalTypeManager.TESTING_TYPE_MANAGER) ConnectorSession(io.trino.spi.connector.ConnectorSession) RoleGrant(io.trino.spi.security.RoleGrant) OperatorType(io.trino.spi.function.OperatorType) Futures(com.google.common.util.concurrent.Futures) ConnectorExpression(io.trino.spi.expression.ConnectorExpression) TypeSignatureProvider(io.trino.sql.analyzer.TypeSignatureProvider) TableStatisticsMetadata(io.trino.spi.statistics.TableStatisticsMetadata) QueryId(io.trino.spi.QueryId) TypeNotFoundException(io.trino.spi.type.TypeNotFoundException) SortItem(io.trino.spi.connector.SortItem) SecurityManagement(io.trino.metadata.Catalog.SecurityManagement) TopNApplicationResult(io.trino.spi.connector.TopNApplicationResult) ConnectorMaterializedViewDefinition(io.trino.spi.connector.ConnectorMaterializedViewDefinition) RedirectionAwareTableHandle.withRedirectionTo(io.trino.metadata.RedirectionAwareTableHandle.withRedirectionTo) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) Locale(java.util.Locale) CatalogSchemaName(io.trino.spi.connector.CatalogSchemaName) ConnectorViewDefinition(io.trino.spi.connector.ConnectorViewDefinition) SignatureBinder.applyBoundVariables(io.trino.metadata.SignatureBinder.applyBoundVariables) SampleType(io.trino.spi.connector.SampleType) SampleApplicationResult(io.trino.spi.connector.SampleApplicationResult) TypeSignature(io.trino.spi.type.TypeSignature) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) FUNCTION_NOT_FOUND(io.trino.spi.StandardErrorCode.FUNCTION_NOT_FOUND) Collections.nCopies(java.util.Collections.nCopies) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ComputedStatistics(io.trino.spi.statistics.ComputedStatistics) PartitioningHandle(io.trino.sql.planner.PartitioningHandle) TrinoException(io.trino.spi.TrinoException) Streams(com.google.common.collect.Streams) AGGREGATE(io.trino.metadata.FunctionKind.AGGREGATE) ConnectorOutputMetadata(io.trino.spi.connector.ConnectorOutputMetadata) Collectors(java.util.stream.Collectors) String.format(java.lang.String.format) ConnectorTableSchema(io.trino.spi.connector.ConnectorTableSchema) Preconditions.checkState(com.google.common.base.Preconditions.checkState) Objects(java.util.Objects) SafeCaches.buildNonEvictableCache(io.trino.collect.cache.SafeCaches.buildNonEvictableCache) List(java.util.List) UNKNOWN(io.trino.client.NodeVersion.UNKNOWN) Assignment(io.trino.spi.connector.Assignment) BeginTableExecuteResult(io.trino.spi.connector.BeginTableExecuteResult) Entry(java.util.Map.Entry) Optional(java.util.Optional) CacheBuilder(com.google.common.cache.CacheBuilder) ConnectorMetadata(io.trino.spi.connector.ConnectorMetadata) SystemTable(io.trino.spi.connector.SystemTable) SYNTAX_ERROR(io.trino.spi.StandardErrorCode.SYNTAX_ERROR) Constraint(io.trino.spi.connector.Constraint) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Type(io.trino.spi.type.Type) HashMap(java.util.HashMap) Function(java.util.function.Function) ConnectorTableVersion(io.trino.spi.connector.ConnectorTableVersion) ConcurrentMap(java.util.concurrent.ConcurrentMap) Inject(javax.inject.Inject) JoinStatistics(io.trino.spi.connector.JoinStatistics) ImmutableList(com.google.common.collect.ImmutableList) JoinType(io.trino.spi.connector.JoinType) Verify.verify(com.google.common.base.Verify.verify) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) Objects.requireNonNull(java.util.Objects.requireNonNull) TableStatistics(io.trino.spi.statistics.TableStatistics) CacheUtils.uncheckedCacheGet(io.trino.collect.cache.CacheUtils.uncheckedCacheGet) NonEvictableCache(io.trino.collect.cache.NonEvictableCache) Privilege(io.trino.spi.security.Privilege) ResolvedFunctionDecoder(io.trino.metadata.ResolvedFunction.ResolvedFunctionDecoder) TupleDomain(io.trino.spi.predicate.TupleDomain) AggregationApplicationResult(io.trino.spi.connector.AggregationApplicationResult) QualifiedName(io.trino.sql.tree.QualifiedName) JoinApplicationResult(io.trino.spi.connector.JoinApplicationResult) FeaturesConfig(io.trino.FeaturesConfig) VisibleForTesting(com.google.common.annotations.VisibleForTesting) TypeManager(io.trino.spi.type.TypeManager) ConnectorTransactionHandle(io.trino.spi.connector.ConnectorTransactionHandle) ColumnMetadata(io.trino.spi.connector.ColumnMetadata) Optional(java.util.Optional) LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) TableColumnsMetadata(io.trino.spi.connector.TableColumnsMetadata) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ImmutableList(com.google.common.collect.ImmutableList) SchemaTablePrefix(io.trino.spi.connector.SchemaTablePrefix) SchemaTableName(io.trino.spi.connector.SchemaTableName) CatalogSchemaTableName(io.trino.spi.connector.CatalogSchemaTableName) QualifiedObjectName.convertFromSchemaTableName(io.trino.metadata.QualifiedObjectName.convertFromSchemaTableName) TypeNotFoundException(io.trino.spi.type.TypeNotFoundException) TrinoException(io.trino.spi.TrinoException) CatalogName(io.trino.connector.CatalogName) ConnectorSession(io.trino.spi.connector.ConnectorSession) ConnectorMetadata(io.trino.spi.connector.ConnectorMetadata)

Example 3 with TypeNotFoundException

use of io.trino.spi.type.TypeNotFoundException in project trino by trinodb.

the class TypeRegistry method instantiateParametricType.

private Type instantiateParametricType(TypeSignature signature) {
    List<TypeParameter> parameters = new ArrayList<>();
    for (TypeSignatureParameter parameter : signature.getParameters()) {
        TypeParameter typeParameter = TypeParameter.of(parameter, typeManager);
        parameters.add(typeParameter);
    }
    ParametricType parametricType = parametricTypes.get(signature.getBase().toLowerCase(Locale.ENGLISH));
    if (parametricType == null) {
        throw new TypeNotFoundException(signature);
    }
    Type instantiatedType;
    try {
        instantiatedType = parametricType.createType(typeManager, parameters);
    } catch (IllegalArgumentException e) {
        throw new TypeNotFoundException(signature, e);
    }
    // checkState(instantiatedType.equalsSignature(signature), "Instantiated parametric type name (%s) does not match expected name (%s)", instantiatedType, signature);
    return instantiatedType;
}
Also used : TypeParameter(io.trino.spi.type.TypeParameter) DecimalParametricType(io.trino.type.DecimalParametricType) VarcharParametricType(io.trino.type.VarcharParametricType) Re2JRegexpType(io.trino.type.Re2JRegexpType) ParametricType(io.trino.spi.type.ParametricType) Type(io.trino.spi.type.Type) CharParametricType(io.trino.type.CharParametricType) OperatorType(io.trino.spi.function.OperatorType) TypeSignatureParameter(io.trino.spi.type.TypeSignatureParameter) TypeNotFoundException(io.trino.spi.type.TypeNotFoundException) ArrayList(java.util.ArrayList) DecimalParametricType(io.trino.type.DecimalParametricType) VarcharParametricType(io.trino.type.VarcharParametricType) ParametricType(io.trino.spi.type.ParametricType) CharParametricType(io.trino.type.CharParametricType)

Example 4 with TypeNotFoundException

use of io.trino.spi.type.TypeNotFoundException in project trino by trinodb.

the class AddColumnTask method execute.

@Override
public ListenableFuture<Void> execute(AddColumn statement, QueryStateMachine stateMachine, List<Expression> parameters, WarningCollector warningCollector) {
    Session session = stateMachine.getSession();
    QualifiedObjectName originalTableName = createQualifiedObjectName(session, statement, statement.getName());
    RedirectionAwareTableHandle redirectionAwareTableHandle = plannerContext.getMetadata().getRedirectionAwareTableHandle(session, originalTableName);
    if (redirectionAwareTableHandle.getTableHandle().isEmpty()) {
        if (!statement.isTableExists()) {
            throw semanticException(TABLE_NOT_FOUND, statement, "Table '%s' does not exist", originalTableName);
        }
        return immediateVoidFuture();
    }
    TableHandle tableHandle = redirectionAwareTableHandle.getTableHandle().get();
    CatalogName catalogName = getRequiredCatalogHandle(plannerContext.getMetadata(), session, statement, tableHandle.getCatalogName().getCatalogName());
    accessControl.checkCanAddColumns(session.toSecurityContext(), redirectionAwareTableHandle.getRedirectedTableName().orElse(originalTableName));
    Map<String, ColumnHandle> columnHandles = plannerContext.getMetadata().getColumnHandles(session, tableHandle);
    ColumnDefinition element = statement.getColumn();
    Type type;
    try {
        type = plannerContext.getTypeManager().getType(toTypeSignature(element.getType()));
    } catch (TypeNotFoundException e) {
        throw semanticException(TYPE_NOT_FOUND, element, "Unknown type '%s' for column '%s'", element.getType(), element.getName());
    }
    if (type.equals(UNKNOWN)) {
        throw semanticException(COLUMN_TYPE_UNKNOWN, element, "Unknown type '%s' for column '%s'", element.getType(), element.getName());
    }
    if (columnHandles.containsKey(element.getName().getValue().toLowerCase(ENGLISH))) {
        if (!statement.isColumnNotExists()) {
            throw semanticException(COLUMN_ALREADY_EXISTS, statement, "Column '%s' already exists", element.getName());
        }
        return immediateVoidFuture();
    }
    if (!element.isNullable() && !plannerContext.getMetadata().getConnectorCapabilities(session, catalogName).contains(NOT_NULL_COLUMN_CONSTRAINT)) {
        throw semanticException(NOT_SUPPORTED, element, "Catalog '%s' does not support NOT NULL for column '%s'", catalogName.getCatalogName(), element.getName());
    }
    Map<String, Object> columnProperties = columnPropertyManager.getProperties(catalogName, element.getProperties(), session, plannerContext, accessControl, parameterExtractor(statement, parameters), true);
    ColumnMetadata column = ColumnMetadata.builder().setName(element.getName().getValue()).setType(type).setNullable(element.isNullable()).setComment(element.getComment()).setProperties(columnProperties).build();
    plannerContext.getMetadata().addColumn(session, tableHandle, column);
    return immediateVoidFuture();
}
Also used : ColumnHandle(io.trino.spi.connector.ColumnHandle) ColumnMetadata(io.trino.spi.connector.ColumnMetadata) MetadataUtil.createQualifiedObjectName(io.trino.metadata.MetadataUtil.createQualifiedObjectName) QualifiedObjectName(io.trino.metadata.QualifiedObjectName) ColumnDefinition(io.trino.sql.tree.ColumnDefinition) Type(io.trino.spi.type.Type) TypeNotFoundException(io.trino.spi.type.TypeNotFoundException) TableHandle(io.trino.metadata.TableHandle) RedirectionAwareTableHandle(io.trino.metadata.RedirectionAwareTableHandle) CatalogName(io.trino.connector.CatalogName) RedirectionAwareTableHandle(io.trino.metadata.RedirectionAwareTableHandle) Session(io.trino.Session)

Aggregations

Type (io.trino.spi.type.Type)4 TypeNotFoundException (io.trino.spi.type.TypeNotFoundException)4 Session (io.trino.Session)3 CatalogName (io.trino.connector.CatalogName)3 ColumnMetadata (io.trino.spi.connector.ColumnMetadata)3 VisibleForTesting (com.google.common.annotations.VisibleForTesting)2 Preconditions.checkArgument (com.google.common.base.Preconditions.checkArgument)2 ImmutableList (com.google.common.collect.ImmutableList)2 ImmutableList.toImmutableList (com.google.common.collect.ImmutableList.toImmutableList)2 ImmutableMap (com.google.common.collect.ImmutableMap)2 ImmutableSet (com.google.common.collect.ImmutableSet)2 ImmutableSet.toImmutableSet (com.google.common.collect.ImmutableSet.toImmutableSet)2 ListenableFuture (com.google.common.util.concurrent.ListenableFuture)2 MetadataUtil.createQualifiedObjectName (io.trino.metadata.MetadataUtil.createQualifiedObjectName)2 QualifiedObjectName (io.trino.metadata.QualifiedObjectName)2 RedirectionAwareTableHandle (io.trino.metadata.RedirectionAwareTableHandle)2 ColumnHandle (io.trino.spi.connector.ColumnHandle)2 OperatorType (io.trino.spi.function.OperatorType)2 ArrayList (java.util.ArrayList)2 Preconditions.checkState (com.google.common.base.Preconditions.checkState)1