Search in sources :

Example 16 with GridQueryProperty

use of org.apache.ignite.internal.processors.query.GridQueryProperty in project ignite by apache.

the class UpdatePlanBuilder method planForBulkLoad.

/**
 * Prepare update plan for COPY command (AKA bulk load).
 *
 * @param cmd Bulk load command
 * @return The update plan for this command.
 * @throws IgniteCheckedException if failed.
 */
public static UpdatePlan planForBulkLoad(SqlBulkLoadCommand cmd, GridH2Table tbl) throws IgniteCheckedException {
    GridH2RowDescriptor desc = tbl.rowDescriptor();
    if (desc == null)
        throw new IgniteSQLException("Row descriptor undefined for table '" + tbl.getName() + "'", IgniteQueryErrorCode.NULL_TABLE_DESCRIPTOR);
    GridCacheContext<?, ?> cctx = desc.context();
    List<String> cols = cmd.columns();
    if (cols == null)
        throw new IgniteSQLException("Columns are not defined", IgniteQueryErrorCode.NULL_TABLE_DESCRIPTOR);
    String[] colNames = new String[cols.size()];
    Column[] h2Cols = new Column[cols.size()];
    int[] colTypes = new int[cols.size()];
    int keyColIdx = -1;
    int valColIdx = -1;
    boolean hasKeyProps = false;
    boolean hasValProps = false;
    for (int i = 0; i < cols.size(); i++) {
        String colName = cols.get(i);
        colNames[i] = colName;
        Column h2Col = tbl.getColumn(colName);
        h2Cols[i] = h2Col;
        colTypes[i] = h2Col.getType();
        int colId = h2Col.getColumnId();
        if (desc.isKeyColumn(colId)) {
            keyColIdx = i;
            continue;
        }
        if (desc.isValueColumn(colId)) {
            valColIdx = i;
            continue;
        }
        GridQueryProperty prop = desc.type().property(colName);
        assert prop != null : "Property '" + colName + "' not found.";
        if (prop.key())
            hasKeyProps = true;
        else
            hasValProps = true;
    }
    verifyDmlColumns(tbl, Arrays.asList(h2Cols));
    KeyValueSupplier keySupplier = createSupplier(cctx, desc.type(), keyColIdx, hasKeyProps, true, false);
    KeyValueSupplier valSupplier = createSupplier(cctx, desc.type(), valColIdx, hasValProps, false, false);
    return new UpdatePlan(UpdateMode.BULK_LOAD, tbl, colNames, colTypes, keySupplier, valSupplier, keyColIdx, valColIdx, null, true, null, 0, null, null, true, false);
}
Also used : GridQueryProperty(org.apache.ignite.internal.processors.query.GridQueryProperty) GridH2RowDescriptor(org.apache.ignite.internal.processors.query.h2.opt.GridH2RowDescriptor) GridSqlColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn) Column(org.h2.table.Column) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException)

Example 17 with GridQueryProperty

use of org.apache.ignite.internal.processors.query.GridQueryProperty in project ignite by apache.

the class GridH2RowDescriptor method refreshMetadataFromTypeDescriptor.

/**
 * Update metadata of this row descriptor according to current state of type descriptor.
 */
@SuppressWarnings({ "WeakerAccess", "ToArrayCallWithZeroLengthArrayArgument" })
public final void refreshMetadataFromTypeDescriptor() {
    Map<String, Class<?>> allFields = new LinkedHashMap<>(type.fields());
    fields = allFields.keySet().toArray(new String[allFields.size()]);
    fieldTypes = new int[fields.length];
    Class[] classes = allFields.values().toArray(new Class[fields.length]);
    for (int i = 0; i < fieldTypes.length; i++) fieldTypes[i] = DataType.getTypeFromClass(classes[i]);
    props = new GridQueryProperty[fields.length];
    for (int i = 0; i < fields.length; i++) {
        GridQueryProperty p = type.property(fields[i]);
        assert p != null : fields[i];
        props[i] = p;
    }
    List<String> fieldsList = Arrays.asList(fields);
    keyAliasColId = (type.keyFieldName() != null) ? QueryUtils.DEFAULT_COLUMNS_COUNT + fieldsList.indexOf(type.keyFieldAlias()) : COL_NOT_EXISTS;
    valAliasColId = (type.valueFieldName() != null) ? QueryUtils.DEFAULT_COLUMNS_COUNT + fieldsList.indexOf(type.valueFieldAlias()) : COL_NOT_EXISTS;
    rowKeyColumnNames = Arrays.stream(props).filter(GridQueryProperty::key).map(GridQueryProperty::name).collect(Collectors.toSet());
}
Also used : GridQueryProperty(org.apache.ignite.internal.processors.query.GridQueryProperty) LinkedHashMap(java.util.LinkedHashMap)

Example 18 with GridQueryProperty

use of org.apache.ignite.internal.processors.query.GridQueryProperty in project ignite by apache.

the class H2TableDescriptor method extractKeyColumns.

/**
 * Create list of affinity and key index columns. Key, if it possible, partitions into simple components.
 *
 * @param tbl GridH2Table instance
 * @param keyCol Key index column.
 * @param affCol Affinity index column.
 *
 * @return List of key and affinity columns. Key's, if it possible, splitted into simple components.
 */
@NotNull
private List<IndexColumn> extractKeyColumns(GridH2Table tbl, IndexColumn keyCol, IndexColumn affCol) {
    ArrayList<IndexColumn> keyCols;
    if (isSql) {
        keyCols = new ArrayList<>(type.fields().size() + 1);
        // Check if key is simple type.
        if (QueryUtils.isSqlType(type.keyClass()))
            keyCols.add(keyCol);
        else {
            if (!type.primaryKeyFields().isEmpty()) {
                for (String keyName : type.primaryKeyFields()) {
                    GridQueryProperty prop = type.property(keyName);
                    assert prop.key() : keyName + " is not a key field";
                    Column col = tbl.getColumn(prop.name());
                    keyCols.add(tbl.indexColumn(col.getColumnId(), SortOrder.ASCENDING));
                }
            } else {
                for (String propName : type.fields().keySet()) {
                    GridQueryProperty prop = type.property(propName);
                    if (prop.key()) {
                        Column col = tbl.getColumn(propName);
                        keyCols.add(tbl.indexColumn(col.getColumnId(), SortOrder.ASCENDING));
                    }
                }
            }
            // we have to fall back to whole-key index.
            if (keyCols.isEmpty())
                keyCols.add(keyCol);
        }
    } else {
        keyCols = new ArrayList<>(2);
        keyCols.add(keyCol);
    }
    if (affCol != null && !H2Utils.containsColumn(keyCols, affCol))
        keyCols.add(affCol);
    else
        keyCols.trimToSize();
    return Collections.unmodifiableList(keyCols);
}
Also used : GridQueryProperty(org.apache.ignite.internal.processors.query.GridQueryProperty) Column(org.h2.table.Column) IndexColumn(org.h2.table.IndexColumn) IndexColumn(org.h2.table.IndexColumn) NotNull(org.jetbrains.annotations.NotNull)

Example 19 with GridQueryProperty

use of org.apache.ignite.internal.processors.query.GridQueryProperty in project ignite by apache.

the class IgniteH2Indexing method columnsInformation.

/**
 * {@inheritDoc}
 */
@Override
public Collection<ColumnInformation> columnsInformation(String schemaNamePtrn, String tblNamePtrn, String colNamePtrn) {
    Collection<ColumnInformation> infos = new ArrayList<>();
    // Gather information about tables.
    schemaMgr.dataTables().stream().filter(t -> matches(t.getSchema().getName(), schemaNamePtrn)).filter(t -> matches(t.getName(), tblNamePtrn)).flatMap(tbl -> {
        IndexColumn affCol = tbl.getAffinityKeyColumn();
        return Stream.of(tbl.getColumns()).filter(Column::getVisible).filter(c -> matches(c.getName(), colNamePtrn)).map(c -> {
            GridQueryProperty prop = tbl.rowDescriptor().type().property(c.getName());
            boolean isAff = affCol != null && c.getColumnId() == affCol.column.getColumnId();
            return new ColumnInformation(c.getColumnId() - QueryUtils.DEFAULT_COLUMNS_COUNT + 1, tbl.getSchema().getName(), tbl.getName(), c.getName(), prop.type(), c.isNullable(), prop.defaultValue(), prop.precision(), prop.scale(), isAff);
        });
    }).forEach(infos::add);
    // Gather information about system views.
    if (matches(QueryUtils.SCHEMA_SYS, schemaNamePtrn)) {
        schemaMgr.systemViews().stream().filter(v -> matches(v.getTableName(), tblNamePtrn)).flatMap(view -> Stream.of(view.getColumns()).filter(c -> matches(c.getName(), colNamePtrn)).map(c -> new ColumnInformation(c.getColumnId() + 1, QueryUtils.SCHEMA_SYS, view.getTableName(), c.getName(), IgniteUtils.classForName(DataType.getTypeClassName(c.getType()), Object.class), c.isNullable(), null, (int) c.getPrecision(), c.getScale(), false))).forEach(infos::add);
    }
    return infos;
}
Also used : QueryCancelledException(org.apache.ignite.cache.query.QueryCancelledException) SQL_CMD_QRY_EXECUTE(org.apache.ignite.internal.processors.tracing.SpanType.SQL_CMD_QRY_EXECUTE) InlineIndexFactory(org.apache.ignite.internal.cache.query.index.sorted.inline.InlineIndexFactory) Collections.singletonList(java.util.Collections.singletonList) BinaryUtils(org.apache.ignite.internal.binary.BinaryUtils) SysProperties(org.h2.engine.SysProperties) Map(java.util.Map) SqlQuery(org.apache.ignite.cache.query.SqlQuery) JdbcParameterMeta(org.apache.ignite.internal.processors.odbc.jdbc.JdbcParameterMeta) TimestampIndexKey(org.apache.ignite.internal.processors.query.h2.index.keys.TimestampIndexKey) IgniteInClosure(org.apache.ignite.lang.IgniteInClosure) QueryField(org.apache.ignite.internal.processors.query.QueryField) CacheGroupDescriptor(org.apache.ignite.internal.processors.cache.CacheGroupDescriptor) PreparedStatement(java.sql.PreparedStatement) CacheDataRow(org.apache.ignite.internal.processors.cache.persistence.CacheDataRow) GridMapQueryExecutor(org.apache.ignite.internal.processors.query.h2.twostep.GridMapQueryExecutor) Stream(java.util.stream.Stream) GridQueryCacheObjectsIterator(org.apache.ignite.internal.processors.query.GridQueryCacheObjectsIterator) InlineIndexImpl(org.apache.ignite.internal.cache.query.index.sorted.inline.InlineIndexImpl) GridCacheContext(org.apache.ignite.internal.processors.cache.GridCacheContext) GridQueryNextPageRequest(org.apache.ignite.internal.processors.query.h2.twostep.messages.GridQueryNextPageRequest) SchemaIndexCacheVisitor(org.apache.ignite.internal.processors.query.schema.SchemaIndexCacheVisitor) BatchUpdateException(java.sql.BatchUpdateException) U(org.apache.ignite.internal.util.typedef.internal.U) IgniteLogger(org.apache.ignite.IgniteLogger) GridQueryIndexing(org.apache.ignite.internal.processors.query.GridQueryIndexing) SecurityPermission(org.apache.ignite.plugin.security.SecurityPermission) LinkedHashMap(java.util.LinkedHashMap) SqlQueryExecutionEvent(org.apache.ignite.events.SqlQueryExecutionEvent) GridCacheQueryMarshallable(org.apache.ignite.internal.processors.cache.query.GridCacheQueryMarshallable) DmlUtils(org.apache.ignite.internal.processors.query.h2.dml.DmlUtils) ClusterTopologyServerNotFoundException(org.apache.ignite.internal.cluster.ClusterTopologyServerNotFoundException) IgniteStatisticsManagerImpl(org.apache.ignite.internal.processors.query.stat.IgniteStatisticsManagerImpl) IgniteMBeansManager(org.apache.ignite.internal.managers.IgniteMBeansManager) GridQueryProperty(org.apache.ignite.internal.processors.query.GridQueryProperty) DmlDistributedPlanInfo(org.apache.ignite.internal.processors.query.h2.dml.DmlDistributedPlanInfo) SQL_QRY(org.apache.ignite.internal.processors.tracing.SpanType.SQL_QRY) MvccSnapshot(org.apache.ignite.internal.processors.cache.mvcc.MvccSnapshot) SqlClientContext(org.apache.ignite.internal.processors.query.SqlClientContext) H2Utils.generateFieldsQueryString(org.apache.ignite.internal.processors.query.h2.H2Utils.generateFieldsQueryString) SQL_QRY_EXECUTE(org.apache.ignite.internal.processors.tracing.SpanType.SQL_QRY_EXECUTE) IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) SqlRollbackTransactionCommand(org.apache.ignite.internal.sql.command.SqlRollbackTransactionCommand) IndexingQueryFilter(org.apache.ignite.spi.indexing.IndexingQueryFilter) JdbcUtils(org.h2.util.JdbcUtils) GridQueryFieldMetadata(org.apache.ignite.internal.processors.query.GridQueryFieldMetadata) IgniteStatisticsManager(org.apache.ignite.internal.processors.query.stat.IgniteStatisticsManager) PartitionResult(org.apache.ignite.internal.sql.optimizer.affinity.PartitionResult) RegisteredQueryCursor(org.apache.ignite.internal.processors.cache.query.RegisteredQueryCursor) LoggerResource(org.apache.ignite.resources.LoggerResource) GridCacheTwoStepQuery(org.apache.ignite.internal.processors.cache.query.GridCacheTwoStepQuery) SqlCommand(org.apache.ignite.internal.sql.command.SqlCommand) Collection(java.util.Collection) GridSqlStatement(org.apache.ignite.internal.processors.query.h2.sql.GridSqlStatement) UUID(java.util.UUID) GridQueryFieldsResultAdapter(org.apache.ignite.internal.processors.query.GridQueryFieldsResultAdapter) Math.min(java.lang.Math.min) IgniteBiTuple(org.apache.ignite.lang.IgniteBiTuple) Objects(java.util.Objects) Nullable(org.jetbrains.annotations.Nullable) H2TreeIndex(org.apache.ignite.internal.processors.query.h2.database.H2TreeIndex) IndexColumn(org.h2.table.IndexColumn) CU(org.apache.ignite.internal.util.typedef.internal.CU) TX_SIZE_THRESHOLD(org.apache.ignite.internal.processors.cache.mvcc.MvccCachingManager.TX_SIZE_THRESHOLD) SQL_CURSOR_OPEN(org.apache.ignite.internal.processors.tracing.SpanType.SQL_CURSOR_OPEN) FieldsQueryCursor(org.apache.ignite.cache.query.FieldsQueryCursor) SqlCommitTransactionCommand(org.apache.ignite.internal.sql.command.SqlCommitTransactionCommand) Span(org.apache.ignite.internal.processors.tracing.Span) H2TreeClientIndex(org.apache.ignite.internal.processors.query.h2.database.H2TreeClientIndex) QueryUtils.matches(org.apache.ignite.internal.processors.query.QueryUtils.matches) HashSet(java.util.HashSet) QueryIndexDescriptorImpl(org.apache.ignite.internal.processors.query.QueryIndexDescriptorImpl) IndexType(org.h2.index.IndexType) UpdateSourceIterator(org.apache.ignite.internal.processors.query.UpdateSourceIterator) CacheDataTree(org.apache.ignite.internal.processors.cache.tree.CacheDataTree) GridMessageListener(org.apache.ignite.internal.managers.communication.GridMessageListener) GridNearTxLocal(org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal) DynamicCacheDescriptor(org.apache.ignite.internal.processors.cache.DynamicCacheDescriptor) GridCacheContextInfo(org.apache.ignite.internal.processors.cache.GridCacheContextInfo) GridReduceQueryExecutor(org.apache.ignite.internal.processors.query.h2.twostep.GridReduceQueryExecutor) GridCloseableIterator(org.apache.ignite.internal.util.lang.GridCloseableIterator) GridQueryNextPageResponse(org.apache.ignite.internal.processors.query.h2.twostep.messages.GridQueryNextPageResponse) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) GridCacheQueryType(org.apache.ignite.internal.processors.cache.query.GridCacheQueryType) UPDATE_RESULT_META(org.apache.ignite.internal.processors.query.h2.H2Utils.UPDATE_RESULT_META) EnlistOperation(org.apache.ignite.internal.processors.query.EnlistOperation) GridPlainRunnable(org.apache.ignite.internal.util.lang.GridPlainRunnable) GridLocalEventListener(org.apache.ignite.internal.managers.eventstorage.GridLocalEventListener) IndexKeyTypes(org.apache.ignite.internal.cache.query.index.sorted.IndexKeyTypes) Arrays(java.util.Arrays) GridQueryCancel(org.apache.ignite.internal.processors.query.GridQueryCancel) QueryUtils(org.apache.ignite.internal.processors.query.QueryUtils) UpdateMode(org.apache.ignite.internal.processors.query.h2.dml.UpdateMode) MvccUtils.txStart(org.apache.ignite.internal.processors.cache.mvcc.MvccUtils.txStart) DateIndexKey(org.apache.ignite.internal.processors.query.h2.index.keys.DateIndexKey) GridH2Table(org.apache.ignite.internal.processors.query.h2.opt.GridH2Table) ResultSet(java.sql.ResultSet) QueryIndexDefinition(org.apache.ignite.internal.processors.query.h2.index.QueryIndexDefinition) GridEmptyCloseableIterator(org.apache.ignite.internal.util.GridEmptyCloseableIterator) QueryContextRegistry(org.apache.ignite.internal.processors.query.h2.opt.QueryContextRegistry) StaticMvccQueryTracker(org.apache.ignite.internal.processors.cache.mvcc.StaticMvccQueryTracker) GridQueryTypeDescriptor(org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) Set(java.util.Set) SqlQueryMXBean(org.apache.ignite.internal.mxbean.SqlQueryMXBean) IgniteClusterReadOnlyException(org.apache.ignite.internal.processors.cache.distributed.dht.IgniteClusterReadOnlyException) ERROR(org.apache.ignite.internal.processors.tracing.SpanTags.ERROR) DataType(org.h2.value.DataType) MTC(org.apache.ignite.internal.processors.tracing.MTC) IGNITE_MVCC_TX_SIZE_CACHING_THRESHOLD(org.apache.ignite.IgniteSystemProperties.IGNITE_MVCC_TX_SIZE_CACHING_THRESHOLD) ClientIndexDefinition(org.apache.ignite.internal.processors.query.h2.index.client.ClientIndexDefinition) Message(org.apache.ignite.plugin.extensions.communication.Message) H2Utils.zeroCursor(org.apache.ignite.internal.processors.query.h2.H2Utils.zeroCursor) ColumnInformation(org.apache.ignite.internal.processors.query.ColumnInformation) GridQueryFieldsResult(org.apache.ignite.internal.processors.query.GridQueryFieldsResult) SQL_SCHEMA(org.apache.ignite.internal.processors.tracing.SpanTags.SQL_SCHEMA) ArrayList(java.util.ArrayList) GridKernalContext(org.apache.ignite.internal.GridKernalContext) Column(org.h2.table.Column) MvccUtils.requestSnapshot(org.apache.ignite.internal.processors.cache.mvcc.MvccUtils.requestSnapshot) CacheServerNotFoundException(org.apache.ignite.cache.CacheServerNotFoundException) SQLException(java.sql.SQLException) Session(org.h2.engine.Session) ClusterNode(org.apache.ignite.cluster.ClusterNode) SQL_QRY_TEXT(org.apache.ignite.internal.processors.tracing.SpanTags.SQL_QRY_TEXT) GridDhtPartitionsExchangeFuture(org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsExchangeFuture) MvccUtils(org.apache.ignite.internal.processors.cache.mvcc.MvccUtils) IndexName(org.apache.ignite.internal.cache.query.index.IndexName) IgniteTxAdapter(org.apache.ignite.internal.processors.cache.transactions.IgniteTxAdapter) SQL_ITER_OPEN(org.apache.ignite.internal.processors.tracing.SpanType.SQL_ITER_OPEN) ErrorCode(org.h2.api.ErrorCode) DmlUpdateSingleEntryIterator(org.apache.ignite.internal.processors.query.h2.dml.DmlUpdateSingleEntryIterator) GridRunningQueryInfo(org.apache.ignite.internal.processors.query.GridRunningQueryInfo) Marshaller(org.apache.ignite.marshaller.Marshaller) TableType(org.h2.table.TableType) GridH2IndexBase(org.apache.ignite.internal.processors.query.h2.opt.GridH2IndexBase) TimeIndexKey(org.apache.ignite.internal.processors.query.h2.index.keys.TimeIndexKey) GridTopic(org.apache.ignite.internal.GridTopic) PartitionReservationManager(org.apache.ignite.internal.processors.query.h2.twostep.PartitionReservationManager) Statement(java.sql.Statement) IgniteDataStreamer(org.apache.ignite.IgniteDataStreamer) BinaryMarshaller(org.apache.ignite.internal.binary.BinaryMarshaller) SqlFieldsQuery(org.apache.ignite.cache.query.SqlFieldsQuery) H2Utils.session(org.apache.ignite.internal.processors.query.h2.H2Utils.session) SqlQueryMXBeanImpl(org.apache.ignite.internal.mxbean.SqlQueryMXBeanImpl) Index(org.h2.index.Index) CacheObjectValueContext(org.apache.ignite.internal.processors.cache.CacheObjectValueContext) IgniteSystemProperties(org.apache.ignite.IgniteSystemProperties) TableInformation(org.apache.ignite.internal.processors.query.TableInformation) ClientIndexFactory(org.apache.ignite.internal.processors.query.h2.index.client.ClientIndexFactory) SqlStateCode(org.apache.ignite.internal.processors.odbc.SqlStateCode) RunningQueryManager(org.apache.ignite.internal.processors.query.RunningQueryManager) H2Utils.validateTypeDescriptor(org.apache.ignite.internal.processors.query.h2.H2Utils.validateTypeDescriptor) InlineIndex(org.apache.ignite.internal.cache.query.index.sorted.inline.InlineIndex) X(org.apache.ignite.internal.util.typedef.X) GridQueryFailResponse(org.apache.ignite.internal.processors.query.h2.twostep.messages.GridQueryFailResponse) GridH2DmlResponse(org.apache.ignite.internal.processors.query.h2.twostep.msg.GridH2DmlResponse) UpdatePlan(org.apache.ignite.internal.processors.query.h2.dml.UpdatePlan) TEXT(org.apache.ignite.internal.processors.cache.query.GridCacheQueryType.TEXT) IgniteFuture(org.apache.ignite.lang.IgniteFuture) DmlUpdateResultsIterator(org.apache.ignite.internal.processors.query.h2.dml.DmlUpdateResultsIterator) EventType(org.apache.ignite.events.EventType) IndexingQueryFilterImpl(org.apache.ignite.spi.indexing.IndexingQueryFilterImpl) IgniteException(org.apache.ignite.IgniteException) GridSpinBusyLock(org.apache.ignite.internal.util.GridSpinBusyLock) List(java.util.List) JavaObjectSerializer(org.h2.api.JavaObjectSerializer) Math.max(java.lang.Math.max) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject) IgniteSingletonIterator(org.apache.ignite.internal.util.lang.IgniteSingletonIterator) DiscoveryEvent(org.apache.ignite.events.DiscoveryEvent) QueryCursorImpl(org.apache.ignite.internal.processors.cache.QueryCursorImpl) GridH2QueryRequest(org.apache.ignite.internal.processors.query.h2.twostep.msg.GridH2QueryRequest) MvccUtils.tx(org.apache.ignite.internal.processors.cache.mvcc.MvccUtils.tx) GridQueryCancelRequest(org.apache.ignite.internal.processors.query.h2.twostep.messages.GridQueryCancelRequest) HashMap(java.util.HashMap) IgniteBiClosure(org.apache.ignite.lang.IgniteBiClosure) SQL_DML_QRY_EXECUTE(org.apache.ignite.internal.processors.tracing.SpanType.SQL_DML_QRY_EXECUTE) PartitionExtractor(org.apache.ignite.internal.processors.query.h2.affinity.PartitionExtractor) IndexKeyFactory(org.apache.ignite.internal.cache.query.index.sorted.keys.IndexKeyFactory) IgniteUtils(org.apache.ignite.internal.util.IgniteUtils) CacheException(javax.cache.CacheException) EVT_SQL_QUERY_EXECUTION(org.apache.ignite.events.EventType.EVT_SQL_QUERY_EXECUTION) IgniteInClosure2X(org.apache.ignite.internal.util.lang.IgniteInClosure2X) F(org.apache.ignite.internal.util.typedef.F) Iterator(java.util.Iterator) AffinityTopologyVersion(org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion) H2TreeIndexBase(org.apache.ignite.internal.processors.query.h2.database.H2TreeIndexBase) GridH2DmlRequest(org.apache.ignite.internal.processors.query.h2.twostep.msg.GridH2DmlRequest) MvccUtils.mvccEnabled(org.apache.ignite.internal.processors.cache.mvcc.MvccUtils.mvccEnabled) IgniteQueryErrorCode(org.apache.ignite.internal.processors.cache.query.IgniteQueryErrorCode) TimeUnit(java.util.concurrent.TimeUnit) H2PartitionResolver(org.apache.ignite.internal.processors.query.h2.affinity.H2PartitionResolver) GridSqlConst(org.apache.ignite.internal.processors.query.h2.sql.GridSqlConst) CacheOperationContext(org.apache.ignite.internal.processors.cache.CacheOperationContext) MvccUtils.checkActive(org.apache.ignite.internal.processors.cache.mvcc.MvccUtils.checkActive) Collections(java.util.Collections) MvccQueryTracker(org.apache.ignite.internal.processors.cache.mvcc.MvccQueryTracker) QueryContext(org.apache.ignite.internal.processors.query.h2.opt.QueryContext) TraceSurroundings(org.apache.ignite.internal.processors.tracing.MTC.TraceSurroundings) GridQueryProperty(org.apache.ignite.internal.processors.query.GridQueryProperty) ColumnInformation(org.apache.ignite.internal.processors.query.ColumnInformation) ArrayList(java.util.ArrayList) IndexColumn(org.h2.table.IndexColumn)

Example 20 with GridQueryProperty

use of org.apache.ignite.internal.processors.query.GridQueryProperty in project ignite by apache.

the class CommandProcessor method runCommandH2.

/**
 * Execute DDL statement.
 *
 * @param sql SQL.
 * @param cmdH2 Command.
 */
private void runCommandH2(String sql, GridSqlStatement cmdH2) {
    IgniteInternalFuture fut = null;
    try {
        finishActiveTxIfNecessary();
        if (cmdH2 instanceof GridSqlCreateIndex) {
            GridSqlCreateIndex cmd = (GridSqlCreateIndex) cmdH2;
            isDdlOnSchemaSupported(cmd.schemaName());
            GridH2Table tbl = schemaMgr.dataTable(cmd.schemaName(), cmd.tableName());
            if (tbl == null)
                throw new SchemaOperationException(SchemaOperationException.CODE_TABLE_NOT_FOUND, cmd.tableName());
            assert tbl.rowDescriptor() != null;
            ensureDdlSupported(tbl);
            QueryIndex newIdx = new QueryIndex();
            newIdx.setName(cmd.index().getName());
            newIdx.setIndexType(cmd.index().getIndexType());
            LinkedHashMap<String, Boolean> flds = new LinkedHashMap<>();
            // Let's replace H2's table and property names by those operated by GridQueryProcessor.
            GridQueryTypeDescriptor typeDesc = tbl.rowDescriptor().type();
            for (Map.Entry<String, Boolean> e : cmd.index().getFields().entrySet()) {
                GridQueryProperty prop = typeDesc.property(e.getKey());
                if (prop == null)
                    throw new SchemaOperationException(SchemaOperationException.CODE_COLUMN_NOT_FOUND, e.getKey());
                flds.put(prop.name(), e.getValue());
            }
            newIdx.setFields(flds);
            fut = ctx.query().dynamicIndexCreate(tbl.cacheName(), cmd.schemaName(), typeDesc.tableName(), newIdx, cmd.ifNotExists(), 0);
        } else if (cmdH2 instanceof GridSqlDropIndex) {
            GridSqlDropIndex cmd = (GridSqlDropIndex) cmdH2;
            isDdlOnSchemaSupported(cmd.schemaName());
            GridH2Table tbl = schemaMgr.dataTableForIndex(cmd.schemaName(), cmd.indexName());
            if (tbl != null) {
                ensureDdlSupported(tbl);
                fut = ctx.query().dynamicIndexDrop(tbl.cacheName(), cmd.schemaName(), cmd.indexName(), cmd.ifExists());
            } else {
                if (cmd.ifExists())
                    fut = new GridFinishedFuture();
                else
                    throw new SchemaOperationException(SchemaOperationException.CODE_INDEX_NOT_FOUND, cmd.indexName());
            }
        } else if (cmdH2 instanceof GridSqlCreateTable) {
            GridSqlCreateTable cmd = (GridSqlCreateTable) cmdH2;
            ctx.security().authorize(cmd.cacheName(), SecurityPermission.CACHE_CREATE);
            isDdlOnSchemaSupported(cmd.schemaName());
            GridH2Table tbl = schemaMgr.dataTable(cmd.schemaName(), cmd.tableName());
            if (tbl != null) {
                if (!cmd.ifNotExists())
                    throw new SchemaOperationException(SchemaOperationException.CODE_TABLE_EXISTS, cmd.tableName());
            } else {
                QueryEntity e = toQueryEntity(cmd);
                CacheConfiguration<?, ?> ccfg = new CacheConfiguration<>(cmd.tableName());
                ccfg.setQueryEntities(Collections.singleton(e));
                ccfg.setSqlSchema(cmd.schemaName());
                SchemaOperationException err = QueryUtils.checkQueryEntityConflicts(ccfg, ctx.cache().cacheDescriptors().values());
                if (err != null)
                    throw err;
                if (!F.isEmpty(cmd.cacheName()) && ctx.cache().cacheDescriptor(cmd.cacheName()) != null) {
                    ctx.query().dynamicAddQueryEntity(cmd.cacheName(), cmd.schemaName(), e, cmd.parallelism(), true).get();
                } else {
                    ctx.query().dynamicTableCreate(cmd.schemaName(), e, cmd.templateName(), cmd.cacheName(), cmd.cacheGroup(), cmd.dataRegionName(), cmd.affinityKey(), cmd.atomicityMode(), cmd.writeSynchronizationMode(), cmd.backups(), cmd.ifNotExists(), cmd.encrypted(), cmd.parallelism());
                }
            }
        } else if (cmdH2 instanceof GridSqlDropTable) {
            GridSqlDropTable cmd = (GridSqlDropTable) cmdH2;
            isDdlOnSchemaSupported(cmd.schemaName());
            GridH2Table tbl = schemaMgr.dataTable(cmd.schemaName(), cmd.tableName());
            if (tbl == null) {
                if (!cmd.ifExists())
                    throw new SchemaOperationException(SchemaOperationException.CODE_TABLE_NOT_FOUND, cmd.tableName());
            } else {
                ctx.security().authorize(tbl.cacheName(), SecurityPermission.CACHE_DESTROY);
                ctx.query().dynamicTableDrop(tbl.cacheName(), cmd.tableName(), cmd.ifExists());
            }
        } else if (cmdH2 instanceof GridSqlAlterTableAddColumn) {
            GridSqlAlterTableAddColumn cmd = (GridSqlAlterTableAddColumn) cmdH2;
            isDdlOnSchemaSupported(cmd.schemaName());
            GridH2Table tbl = schemaMgr.dataTable(cmd.schemaName(), cmd.tableName());
            if (tbl == null) {
                if (!cmd.ifTableExists())
                    throw new SchemaOperationException(SchemaOperationException.CODE_TABLE_NOT_FOUND, cmd.tableName());
            } else {
                if (QueryUtils.isSqlType(tbl.rowDescriptor().type().valueClass()))
                    throw new SchemaOperationException("Cannot add column(s) because table was created " + "with " + PARAM_WRAP_VALUE + "=false option.");
                List<QueryField> cols = new ArrayList<>(cmd.columns().length);
                boolean allFieldsNullable = true;
                for (GridSqlColumn col : cmd.columns()) {
                    if (tbl.doesColumnExist(col.columnName())) {
                        if ((!cmd.ifNotExists() || cmd.columns().length != 1)) {
                            throw new SchemaOperationException(SchemaOperationException.CODE_COLUMN_EXISTS, col.columnName());
                        } else {
                            cols = null;
                            break;
                        }
                    }
                    QueryField field = new QueryField(col.columnName(), getTypeClassName(col), col.column().isNullable(), col.defaultValue(), col.precision(), col.scale());
                    cols.add(field);
                    allFieldsNullable &= field.isNullable();
                }
                if (cols != null) {
                    assert tbl.rowDescriptor() != null;
                    if (!allFieldsNullable)
                        QueryUtils.checkNotNullAllowed(tbl.cacheInfo().config());
                    fut = ctx.query().dynamicColumnAdd(tbl.cacheName(), cmd.schemaName(), tbl.rowDescriptor().type().tableName(), cols, cmd.ifTableExists(), cmd.ifNotExists());
                }
            }
        } else if (cmdH2 instanceof GridSqlAlterTableDropColumn) {
            GridSqlAlterTableDropColumn cmd = (GridSqlAlterTableDropColumn) cmdH2;
            isDdlOnSchemaSupported(cmd.schemaName());
            GridH2Table tbl = schemaMgr.dataTable(cmd.schemaName(), cmd.tableName());
            if (tbl == null) {
                if (!cmd.ifTableExists())
                    throw new SchemaOperationException(SchemaOperationException.CODE_TABLE_NOT_FOUND, cmd.tableName());
            } else {
                assert tbl.rowDescriptor() != null;
                GridCacheContext cctx = tbl.cacheContext();
                assert cctx != null;
                if (cctx.mvccEnabled())
                    throw new IgniteSQLException("Cannot drop column(s) with enabled MVCC. " + "Operation is unsupported at the moment.", IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
                if (QueryUtils.isSqlType(tbl.rowDescriptor().type().valueClass()))
                    throw new SchemaOperationException("Cannot drop column(s) because table was created " + "with " + PARAM_WRAP_VALUE + "=false option.");
                List<String> cols = new ArrayList<>(cmd.columns().length);
                GridQueryTypeDescriptor type = tbl.rowDescriptor().type();
                for (String colName : cmd.columns()) {
                    if (!tbl.doesColumnExist(colName)) {
                        if ((!cmd.ifExists() || cmd.columns().length != 1)) {
                            throw new SchemaOperationException(SchemaOperationException.CODE_COLUMN_NOT_FOUND, colName);
                        } else {
                            cols = null;
                            break;
                        }
                    }
                    SchemaOperationException err = QueryUtils.validateDropColumn(type, colName);
                    if (err != null)
                        throw err;
                    cols.add(colName);
                }
                if (cols != null) {
                    fut = ctx.query().dynamicColumnRemove(tbl.cacheName(), cmd.schemaName(), type.tableName(), cols, cmd.ifTableExists(), cmd.ifExists());
                }
            }
        } else
            throw new IgniteSQLException("Unsupported DDL operation: " + sql, IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
        if (fut != null)
            fut.get();
    } catch (SchemaOperationException e) {
        U.error(null, "DDL operation failure", e);
        throw convert(e);
    } catch (IgniteSQLException e) {
        throw e;
    } catch (Exception e) {
        throw new IgniteSQLException(e.getMessage(), e);
    }
}
Also used : ArrayList(java.util.ArrayList) IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) GridSqlDropIndex(org.apache.ignite.internal.processors.query.h2.sql.GridSqlDropIndex) LinkedHashMap(java.util.LinkedHashMap) GridQueryTypeDescriptor(org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor) GridFinishedFuture(org.apache.ignite.internal.util.future.GridFinishedFuture) QueryField(org.apache.ignite.internal.processors.query.QueryField) GridSqlCreateIndex(org.apache.ignite.internal.processors.query.h2.sql.GridSqlCreateIndex) GridH2Table(org.apache.ignite.internal.processors.query.h2.opt.GridH2Table) QueryIndex(org.apache.ignite.cache.QueryIndex) ArrayList(java.util.ArrayList) List(java.util.List) CacheConfiguration(org.apache.ignite.configuration.CacheConfiguration) SchemaOperationException(org.apache.ignite.internal.processors.query.schema.SchemaOperationException) GridCacheContext(org.apache.ignite.internal.processors.cache.GridCacheContext) GridSqlCreateTable(org.apache.ignite.internal.processors.query.h2.sql.GridSqlCreateTable) QueryEntity(org.apache.ignite.cache.QueryEntity) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) SchemaOperationException(org.apache.ignite.internal.processors.query.schema.SchemaOperationException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) GridQueryProperty(org.apache.ignite.internal.processors.query.GridQueryProperty) GridSqlAlterTableAddColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlAlterTableAddColumn) GridSqlAlterTableDropColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlAlterTableDropColumn) GridSqlColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) GridSqlDropTable(org.apache.ignite.internal.processors.query.h2.sql.GridSqlDropTable)

Aggregations

GridQueryProperty (org.apache.ignite.internal.processors.query.GridQueryProperty)20 IgniteSQLException (org.apache.ignite.internal.processors.query.IgniteSQLException)15 GridQueryTypeDescriptor (org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor)13 LinkedHashMap (java.util.LinkedHashMap)8 Column (org.h2.table.Column)8 ArrayList (java.util.ArrayList)7 Map (java.util.Map)7 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)7 GridH2RowDescriptor (org.apache.ignite.internal.processors.query.h2.opt.GridH2RowDescriptor)7 GridH2Table (org.apache.ignite.internal.processors.query.h2.opt.GridH2Table)7 HashMap (java.util.HashMap)6 List (java.util.List)6 IgniteInternalFuture (org.apache.ignite.internal.IgniteInternalFuture)6 GridSqlColumn (org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn)6 QueryIndex (org.apache.ignite.cache.QueryIndex)5 SchemaOperationException (org.apache.ignite.internal.processors.query.schema.SchemaOperationException)5 GridFinishedFuture (org.apache.ignite.internal.util.future.GridFinishedFuture)5 GridCacheContext (org.apache.ignite.internal.processors.cache.GridCacheContext)4 QueryCursorImpl (org.apache.ignite.internal.processors.cache.QueryCursorImpl)3 QueryField (org.apache.ignite.internal.processors.query.QueryField)3