Search in sources :

Example 81 with AND

use of org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperationType.AND in project ignite by apache.

the class CommandProcessor method toQueryEntity.

/**
 * Convert this statement to query entity and do Ignite specific sanity checks on the way.
 * @return Query entity mimicking this SQL statement.
 */
private static QueryEntity toQueryEntity(GridSqlCreateTable createTbl) {
    QueryEntityEx res = new QueryEntityEx();
    res.setTableName(createTbl.tableName());
    Set<String> notNullFields = null;
    HashMap<String, Object> dfltValues = new HashMap<>();
    Map<String, Integer> precision = new HashMap<>();
    Map<String, Integer> scale = new HashMap<>();
    for (Map.Entry<String, GridSqlColumn> e : createTbl.columns().entrySet()) {
        GridSqlColumn gridCol = e.getValue();
        Column col = gridCol.column();
        res.addQueryField(e.getKey(), getTypeClassName(gridCol), null);
        if (!col.isNullable()) {
            if (notNullFields == null)
                notNullFields = new HashSet<>();
            notNullFields.add(e.getKey());
        }
        Object dfltVal = gridCol.defaultValue();
        if (dfltVal != null)
            dfltValues.put(e.getKey(), dfltVal);
        if (col.getType() == Value.DECIMAL) {
            if (col.getPrecision() < H2Utils.DECIMAL_DEFAULT_PRECISION)
                precision.put(e.getKey(), (int) col.getPrecision());
            if (col.getScale() < H2Utils.DECIMAL_DEFAULT_SCALE)
                scale.put(e.getKey(), col.getScale());
        }
        if (col.getType() == Value.STRING || col.getType() == Value.STRING_FIXED || col.getType() == Value.STRING_IGNORECASE || col.getType() == Value.BYTES)
            if (col.getPrecision() < H2Utils.STRING_DEFAULT_PRECISION)
                precision.put(e.getKey(), (int) col.getPrecision());
    }
    if (!F.isEmpty(dfltValues))
        res.setDefaultFieldValues(dfltValues);
    if (!F.isEmpty(precision))
        res.setFieldsPrecision(precision);
    if (!F.isEmpty(scale))
        res.setFieldsScale(scale);
    String valTypeName = QueryUtils.createTableValueTypeName(createTbl.schemaName(), createTbl.tableName());
    String keyTypeName = QueryUtils.createTableKeyTypeName(valTypeName);
    if (!F.isEmpty(createTbl.keyTypeName()))
        keyTypeName = createTbl.keyTypeName();
    if (!F.isEmpty(createTbl.valueTypeName()))
        valTypeName = createTbl.valueTypeName();
    assert createTbl.wrapKey() != null;
    assert createTbl.wrapValue() != null;
    if (!createTbl.wrapKey()) {
        GridSqlColumn pkCol = createTbl.columns().get(createTbl.primaryKeyColumns().iterator().next());
        keyTypeName = getTypeClassName(pkCol);
        res.setKeyFieldName(pkCol.columnName());
    } else {
        res.setKeyFields(createTbl.primaryKeyColumns());
        res.setPreserveKeysOrder(true);
    }
    if (!createTbl.wrapValue()) {
        GridSqlColumn valCol = null;
        for (Map.Entry<String, GridSqlColumn> e : createTbl.columns().entrySet()) {
            if (!createTbl.primaryKeyColumns().contains(e.getKey())) {
                valCol = e.getValue();
                break;
            }
        }
        assert valCol != null;
        valTypeName = getTypeClassName(valCol);
        res.setValueFieldName(valCol.columnName());
    }
    res.setValueType(valTypeName);
    res.setKeyType(keyTypeName);
    if (!F.isEmpty(notNullFields))
        res.setNotNullFields(notNullFields);
    // Fill key object with all fields for new tables.
    res.fillAbsentPKsWithDefaults(true);
    if (Objects.nonNull(createTbl.primaryKeyInlineSize()))
        res.setPrimaryKeyInlineSize(createTbl.primaryKeyInlineSize());
    if (Objects.nonNull(createTbl.affinityKeyInlineSize()))
        res.setAffinityKeyInlineSize(createTbl.affinityKeyInlineSize());
    return res;
}
Also used : QueryEntityEx(org.apache.ignite.internal.processors.query.QueryEntityEx) LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) AlterTableAlterColumn(org.h2.command.ddl.AlterTableAlterColumn) Column(org.h2.table.Column) GridSqlAlterTableAddColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlAlterTableAddColumn) SqlIndexColumn(org.apache.ignite.internal.sql.command.SqlIndexColumn) GridSqlAlterTableDropColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlAlterTableDropColumn) GridSqlColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn) GridSqlColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) HashSet(java.util.HashSet)

Example 82 with AND

use of org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperationType.AND 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)

Example 83 with AND

use of org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperationType.AND in project ignite by apache.

the class GatherPartitionStatistics method recollectPartition.

/**
 * Collect some statistics, fix existing in repo and return resulting partition statistics.
 *
 * @param cctx Cache context to get partition from.
 * @param partStat Existing partition statistics to fix or use as a base.
 * @param colsToCollect Columns to collect.
 * @param colsToRemove Columns to remove.
 * @return New partition statistics.
 */
private ObjectPartitionStatisticsImpl recollectPartition(GridCacheContext<?, ?> cctx, ObjectPartitionStatisticsImpl partStat, Map<String, StatisticsColumnConfiguration> colsToCollect, Set<String> colsToRemove) {
    CacheGroupContext grp = cctx.group();
    GridDhtPartitionTopology top = grp.topology();
    AffinityTopologyVersion topVer = top.readyTopologyVersion();
    GridDhtLocalPartition locPart = top.localPartition(partId, topVer, false);
    if (locPart == null)
        throw new GatherStatisticCancelException();
    boolean reserved = locPart.reserve();
    GridH2Table tbl = gathCtx.table();
    ObjectPartitionStatisticsImpl res = null;
    try {
        if (!reserved || (locPart.state() != OWNING)) {
            if (log.isDebugEnabled()) {
                log.debug("Partition not owning. Need to retry [part=" + partId + ", tbl=" + tbl.identifier() + ']');
            }
            throw new GatherStatisticCancelException();
        }
        Column[] cols = IgniteStatisticsHelper.filterColumns(tbl.getColumns(), colsToCollect.keySet());
        ColumnStatisticsCollector[] collectors = new ColumnStatisticsCollector[cols.length];
        for (int i = 0; i < cols.length; ++i) {
            long colCfgVer = colsToCollect.get(cols[i].getName()).version();
            collectors[i] = new ColumnStatisticsCollector(cols[i], tbl::compareTypeSafe, colCfgVer);
        }
        GridH2RowDescriptor rowDesc = tbl.rowDescriptor();
        GridQueryTypeDescriptor typeDesc = rowDesc.type();
        try {
            int checkInt = CANCELLED_CHECK_INTERVAL;
            if (log.isDebugEnabled()) {
                log.debug("Start partition scan [part=" + partId + ", tbl=" + gathCtx.table().identifier() + ']');
            }
            for (CacheDataRow row : grp.offheap().cachePartitionIterator(gathCtx.table().cacheId(), partId, null, false)) {
                if (--checkInt == 0) {
                    if (gathCtx.future().isCancelled())
                        throw new GatherStatisticCancelException();
                    checkInt = CANCELLED_CHECK_INTERVAL;
                }
                if (!typeDesc.matchType(row.value()) || wasExpired(row))
                    continue;
                H2Row h2row = rowDesc.createRow(row);
                for (ColumnStatisticsCollector colStat : collectors) colStat.add(h2row.getValue(colStat.col().getColumnId()));
            }
        } catch (IgniteCheckedException e) {
            log.warning(String.format("Unable to collect partition level statistics by %s.%s:%d due to %s", tbl.identifier().schema(), tbl.identifier().table(), partId, e.getMessage()));
            throw new IgniteException("Unable to collect partition level statistics", e);
        }
        Map<String, ColumnStatistics> colStats = Arrays.stream(collectors).collect(Collectors.toMap(csc -> csc.col().getName(), ColumnStatisticsCollector::finish));
        // Add existing to full replace existing statistics with new one.
        if (partStat != null) {
            for (Map.Entry<String, ColumnStatistics> oldColStat : partStat.columnsStatistics().entrySet()) {
                if (!colsToRemove.contains(oldColStat.getKey()))
                    colStats.putIfAbsent(oldColStat.getKey(), oldColStat.getValue());
            }
        }
        res = new ObjectPartitionStatisticsImpl(partId, getRowCount(colStats), locPart.updateCounter(), colStats);
    } finally {
        if (reserved)
            locPart.release();
    }
    statRepo.replaceLocalPartitionStatistics(gathCtx.configuration().key(), res);
    if (gathCtx.configuration().columns().size() == colsToCollect.size())
        statRepo.refreshObsolescence(gathCtx.configuration().key(), partId);
    return res;
}
Also used : Arrays(java.util.Arrays) IgniteStatisticsRepository(org.apache.ignite.internal.processors.query.stat.IgniteStatisticsRepository) IgniteStatisticsHelper(org.apache.ignite.internal.processors.query.stat.IgniteStatisticsHelper) U(org.apache.ignite.internal.util.typedef.internal.U) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) IgniteLogger(org.apache.ignite.IgniteLogger) CacheGroupContext(org.apache.ignite.internal.processors.cache.CacheGroupContext) ColumnStatisticsCollector(org.apache.ignite.internal.processors.query.stat.ColumnStatisticsCollector) ColumnStatistics(org.apache.ignite.internal.processors.query.stat.ColumnStatistics) HashSet(java.util.HashSet) Column(org.h2.table.Column) LocalStatisticsGatheringContext(org.apache.ignite.internal.processors.query.stat.LocalStatisticsGatheringContext) GridH2Table(org.apache.ignite.internal.processors.query.h2.opt.GridH2Table) GatherStatisticCancelException(org.apache.ignite.internal.processors.query.stat.GatherStatisticCancelException) Map(java.util.Map) StatisticsColumnConfiguration(org.apache.ignite.internal.processors.query.stat.config.StatisticsColumnConfiguration) GridH2RowDescriptor(org.apache.ignite.internal.processors.query.h2.opt.GridH2RowDescriptor) GridQueryTypeDescriptor(org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor) F(org.apache.ignite.internal.util.typedef.F) ObjectPartitionStatisticsImpl(org.apache.ignite.internal.processors.query.stat.ObjectPartitionStatisticsImpl) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) AffinityTopologyVersion(org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion) Set(java.util.Set) OWNING(org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtPartitionState.OWNING) CacheDataRow(org.apache.ignite.internal.processors.cache.persistence.CacheDataRow) Collectors(java.util.stream.Collectors) GridDhtLocalPartition(org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtLocalPartition) Nullable(org.jetbrains.annotations.Nullable) H2Row(org.apache.ignite.internal.processors.query.h2.opt.H2Row) GridDhtPartitionTopology(org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtPartitionTopology) GridCacheContext(org.apache.ignite.internal.processors.cache.GridCacheContext) Collections(java.util.Collections) ColumnStatisticsCollector(org.apache.ignite.internal.processors.query.stat.ColumnStatisticsCollector) GridDhtPartitionTopology(org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtPartitionTopology) GatherStatisticCancelException(org.apache.ignite.internal.processors.query.stat.GatherStatisticCancelException) GridQueryTypeDescriptor(org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor) ObjectPartitionStatisticsImpl(org.apache.ignite.internal.processors.query.stat.ObjectPartitionStatisticsImpl) GridH2RowDescriptor(org.apache.ignite.internal.processors.query.h2.opt.GridH2RowDescriptor) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) Column(org.h2.table.Column) IgniteException(org.apache.ignite.IgniteException) GridH2Table(org.apache.ignite.internal.processors.query.h2.opt.GridH2Table) GridDhtLocalPartition(org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtLocalPartition) H2Row(org.apache.ignite.internal.processors.query.h2.opt.H2Row) CacheDataRow(org.apache.ignite.internal.processors.cache.persistence.CacheDataRow) ColumnStatistics(org.apache.ignite.internal.processors.query.stat.ColumnStatistics) AffinityTopologyVersion(org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion) CacheGroupContext(org.apache.ignite.internal.processors.cache.CacheGroupContext) HashMap(java.util.HashMap) Map(java.util.Map)

Example 84 with AND

use of org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperationType.AND in project ignite by apache.

the class GridSqlQueryParser method parseSelect.

/**
 * @param select Select.
 */
private GridSqlSelect parseSelect(Select select) {
    GridSqlSelect res = (GridSqlSelect) h2ObjToGridObj.get(select);
    if (res != null)
        return res;
    res = new GridSqlSelect();
    h2ObjToGridObj.put(select, res);
    res.distinct(select.isDistinct());
    Expression where = CONDITION.get(select);
    res.where(parseExpression(where, true));
    ArrayList<TableFilter> tableFilters = new ArrayList<>();
    TableFilter filter = select.getTopTableFilter();
    boolean isForUpdate = SELECT_IS_FOR_UPDATE.get(select);
    do {
        assert0(filter != null, select);
        assert0(filter.getNestedJoin() == null, select);
        // Can use optimized join order only if we are not inside of an expression.
        if (parsingSubQryExpression == 0 && optimizedTableFilterOrder != null) {
            String tblAlias = filter.getTableAlias();
            int idx = optimizedTableFilterOrder.get(tblAlias);
            setElementAt(tableFilters, idx, filter);
        } else
            tableFilters.add(filter);
        filter = filter.getJoin();
    } while (filter != null);
    // Build FROM clause from correctly ordered table filters.
    GridSqlElement from = null;
    for (int i = 0; i < tableFilters.size(); i++) {
        TableFilter f = tableFilters.get(i);
        GridSqlElement gridFilter = parseTableFilter(f);
        from = from == null ? gridFilter : new GridSqlJoin(from, gridFilter, f.isJoinOuter(), parseExpression(f.getJoinCondition(), true));
    }
    res.from(from);
    if (isForUpdate) {
        if (!(from instanceof GridSqlTable || (from instanceof GridSqlAlias && from.size() == 1 && from.child() instanceof GridSqlTable))) {
            throw new IgniteSQLException("SELECT FOR UPDATE with joins is not supported.", IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
        }
        GridSqlTable gridTbl = from instanceof GridSqlTable ? (GridSqlTable) from : ((GridSqlAlias) from).child();
        GridH2Table tbl = gridTbl.dataTable();
        if (tbl == null) {
            throw new IgniteSQLException("SELECT FOR UPDATE query must involve Ignite table.", IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
        }
        if (select.getLimit() != null || select.getOffset() != null) {
            throw new IgniteSQLException("LIMIT/OFFSET clauses are not supported for SELECT FOR UPDATE.", IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
        }
        if (SELECT_IS_GROUP_QUERY.get(select)) {
            throw new IgniteSQLException("SELECT FOR UPDATE with aggregates and/or GROUP BY is not supported.", IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
        }
        if (select.isDistinct())
            throw new IgniteSQLException("DISTINCT clause is not supported for SELECT FOR UPDATE.", IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
        if (SplitterUtils.hasSubQueries(res))
            throw new IgniteSQLException("Sub queries are not supported for SELECT FOR UPDATE.", IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
    }
    ArrayList<Expression> expressions = select.getExpressions();
    for (int i = 0; i < expressions.size(); i++) res.addColumn(parseExpression(expressions.get(i), true), i < select.getColumnCount());
    int[] grpIdx = GROUP_INDEXES.get(select);
    if (grpIdx != null)
        res.groupColumns(grpIdx);
    int havingIdx = HAVING_INDEX.get(select);
    if (havingIdx >= 0)
        res.havingColumn(havingIdx);
    res.forUpdate(isForUpdate);
    processSortOrder(select.getSortOrder(), res);
    res.limit(parseExpression(select.getLimit(), false));
    res.offset(parseExpression(select.getOffset(), false));
    return res;
}
Also used : ArrayList(java.util.ArrayList) AlterTableAddConstraint(org.h2.command.ddl.AlterTableAddConstraint) Expression(org.h2.expression.Expression) GridSqlType.fromExpression(org.apache.ignite.internal.processors.query.h2.sql.GridSqlType.fromExpression) ValueExpression(org.h2.expression.ValueExpression) TableFilter(org.h2.table.TableFilter) GridH2Table(org.apache.ignite.internal.processors.query.h2.opt.GridH2Table) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException)

Example 85 with AND

use of org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperationType.AND in project ignite by apache.

the class GridSqlQueryParser method parseExpression0.

/**
 * @param expression Expression.
 * @param calcTypes Calculate types for all the expressions.
 * @return Parsed expression.
 */
private GridSqlElement parseExpression0(Expression expression, boolean calcTypes) {
    if (expression instanceof ExpressionColumn) {
        ExpressionColumn expCol = (ExpressionColumn) expression;
        return new GridSqlColumn(expCol.getColumn(), parseTableFilter(expCol.getTableFilter()), SCHEMA_NAME.get(expCol), expCol.getOriginalTableAliasName(), expCol.getColumnName());
    }
    if (expression instanceof Alias)
        return new GridSqlAlias(expression.getAlias(), parseExpression(expression.getNonAliasExpression(), calcTypes), true);
    if (expression instanceof ValueExpression)
        // == comparison is legit, see ValueExpression#getSQL()
        return expression == ValueExpression.getDefault() ? GridSqlKeyword.DEFAULT : new GridSqlConst(expression.getValue(null));
    if (expression instanceof Operation) {
        Operation operation = (Operation) expression;
        Operation.OpType type = OPERATION_TYPE.get(operation);
        if (type == Operation.OpType.NEGATE) {
            assert OPERATION_RIGHT.get(operation) == null;
            return new GridSqlOperation(GridSqlOperationType.NEGATE, parseExpression(OPERATION_LEFT.get(operation), calcTypes));
        }
        return new GridSqlOperation(mapOperationType(type), parseExpression(OPERATION_LEFT.get(operation), calcTypes), parseExpression(OPERATION_RIGHT.get(operation), calcTypes));
    }
    if (expression instanceof Comparison) {
        Comparison cmp = (Comparison) expression;
        GridSqlOperationType opType = COMPARISON_TYPES[COMPARISON_TYPE.get(cmp)];
        assert opType != null : COMPARISON_TYPE.get(cmp);
        Expression leftExp = COMPARISON_LEFT.get(cmp);
        GridSqlElement left = parseExpression(leftExp, calcTypes);
        if (opType.childrenCount() == 1)
            return new GridSqlOperation(opType, left);
        Expression rightExp = COMPARISON_RIGHT.get(cmp);
        GridSqlElement right = parseExpression(rightExp, calcTypes);
        return new GridSqlOperation(opType, left, right);
    }
    if (expression instanceof ConditionNot)
        return new GridSqlOperation(NOT, parseExpression(expression.getNotIfPossible(null), calcTypes));
    if (expression instanceof ConditionAndOr) {
        ConditionAndOr andOr = (ConditionAndOr) expression;
        int type = ANDOR_TYPE.get(andOr);
        assert type == ConditionAndOr.AND || type == ConditionAndOr.OR;
        return new GridSqlOperation(type == ConditionAndOr.AND ? AND : OR, parseExpression(ANDOR_LEFT.get(andOr), calcTypes), parseExpression(ANDOR_RIGHT.get(andOr), calcTypes));
    }
    if (expression instanceof Subquery) {
        Query qry = ((Subquery) expression).getQuery();
        return parseQueryExpression(qry);
    }
    if (expression instanceof ConditionIn) {
        GridSqlOperation res = new GridSqlOperation(IN);
        res.addChild(parseExpression(LEFT_CI.get((ConditionIn) expression), calcTypes));
        List<Expression> vals = VALUE_LIST_CI.get((ConditionIn) expression);
        for (Expression val : vals) res.addChild(parseExpression(val, calcTypes));
        return res;
    }
    if (expression instanceof ConditionInConstantSet) {
        GridSqlOperation res = new GridSqlOperation(IN);
        res.addChild(parseExpression(LEFT_CICS.get((ConditionInConstantSet) expression), calcTypes));
        List<Expression> vals = VALUE_LIST_CICS.get((ConditionInConstantSet) expression);
        for (Expression val : vals) res.addChild(parseExpression(val, calcTypes));
        return res;
    }
    if (expression instanceof ConditionInSelect) {
        GridSqlOperation res = new GridSqlOperation(IN);
        boolean all = ALL.get((ConditionInSelect) expression);
        int compareType = COMPARE_TYPE.get((ConditionInSelect) expression);
        assert0(!all, expression);
        assert0(compareType == Comparison.EQUAL, expression);
        res.addChild(parseExpression(LEFT_CIS.get((ConditionInSelect) expression), calcTypes));
        Query qry = QUERY_IN.get((ConditionInSelect) expression);
        res.addChild(parseQueryExpression(qry));
        return res;
    }
    if (expression instanceof CompareLike) {
        assert0(ESCAPE.get((CompareLike) expression) == null, expression);
        boolean regexp = REGEXP_CL.get((CompareLike) expression);
        return new GridSqlOperation(regexp ? REGEXP : LIKE, parseExpression(LEFT.get((CompareLike) expression), calcTypes), parseExpression(RIGHT.get((CompareLike) expression), calcTypes));
    }
    if (expression instanceof Function) {
        Function f = (Function) expression;
        GridSqlFunction res = new GridSqlFunction(null, f.getName());
        if (f.getArgs() != null) {
            if (f.getFunctionType() == Function.TABLE || f.getFunctionType() == Function.TABLE_DISTINCT) {
                Column[] cols = FUNC_TBL_COLS.get((TableFunction) f);
                Expression[] args = f.getArgs();
                assert cols.length == args.length;
                for (int i = 0; i < cols.length; i++) {
                    GridSqlElement arg = parseExpression(args[i], calcTypes);
                    GridSqlAlias alias = new GridSqlAlias(cols[i].getName(), arg, false);
                    alias.resultType(fromColumn(cols[i]));
                    res.addChild(alias);
                }
            } else {
                for (Expression arg : f.getArgs()) {
                    if (arg == null) {
                        if (f.getFunctionType() != Function.CASE)
                            throw new IllegalStateException("Function type with null arg: " + f.getFunctionType());
                        res.addChild(GridSqlPlaceholder.EMPTY);
                    } else
                        res.addChild(parseExpression(arg, calcTypes));
                }
            }
        }
        if (f.getFunctionType() == Function.CAST || f.getFunctionType() == Function.CONVERT) {
            checkTypeSupported(f.getType(), "[expSql=" + f.getSQL() + ']');
            res.resultType(fromExpression(f));
        }
        return res;
    }
    if (expression instanceof JavaFunction) {
        JavaFunction f = (JavaFunction) expression;
        FunctionAlias alias = FUNC_ALIAS.get(f);
        GridSqlFunction res = new GridSqlFunction(alias.getSchema().getName(), f.getName());
        if (f.getArgs() != null) {
            for (Expression arg : f.getArgs()) res.addChild(parseExpression(arg, calcTypes));
        }
        return res;
    }
    if (expression instanceof Parameter)
        return new GridSqlParameter(((Parameter) expression).getIndex());
    if (expression instanceof Aggregate) {
        Aggregate.AggregateType type = TYPE.get((Aggregate) expression);
        if (GridSqlAggregateFunction.isValidType(type)) {
            GridSqlAggregateFunction res = new GridSqlAggregateFunction(DISTINCT.get((Aggregate) expression), type);
            Expression on = ON.get((Aggregate) expression);
            if (on != null)
                res.addChild(parseExpression(on, calcTypes));
            ArrayList<SelectOrderBy> orders = GROUP_CONCAT_ORDER_LIST.get((Aggregate) expression);
            if (!F.isEmpty(orders))
                parseGroupConcatOrder(res, orders, calcTypes);
            Expression separator = GROUP_CONCAT_SEPARATOR.get((Aggregate) expression);
            if (separator != null)
                res.setGroupConcatSeparator(parseExpression(separator, calcTypes));
            return res;
        }
    }
    if (expression instanceof ExpressionList) {
        Expression[] exprs = EXPR_LIST.get((ExpressionList) expression);
        GridSqlArray res = new GridSqlArray(exprs.length);
        for (Expression expr : exprs) res.addChild(parseExpression(expr, calcTypes));
        return res;
    }
    if (expression instanceof ConditionExists) {
        Query qry = QUERY_EXISTS.get((ConditionExists) expression);
        GridSqlOperation res = new GridSqlOperation(EXISTS);
        res.addChild(parseQueryExpression(qry));
        return res;
    }
    throw new IgniteException("Unsupported expression: " + expression + " [type=" + expression.getClass().getSimpleName() + ']');
}
Also used : SelectOrderBy(org.h2.command.dml.SelectOrderBy) ConditionNot(org.h2.expression.ConditionNot) Query(org.h2.command.dml.Query) JavaFunction(org.h2.expression.JavaFunction) Operation(org.h2.expression.Operation) ConditionAndOr(org.h2.expression.ConditionAndOr) Subquery(org.h2.expression.Subquery) ExpressionColumn(org.h2.expression.ExpressionColumn) Function(org.h2.expression.Function) TableFunction(org.h2.expression.TableFunction) JavaFunction(org.h2.expression.JavaFunction) Comparison(org.h2.expression.Comparison) GridSqlType.fromColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlType.fromColumn) AlterTableAlterColumn(org.h2.command.ddl.AlterTableAlterColumn) Column(org.h2.table.Column) ExpressionColumn(org.h2.expression.ExpressionColumn) IndexColumn(org.h2.table.IndexColumn) IgniteException(org.apache.ignite.IgniteException) ExpressionList(org.h2.expression.ExpressionList) FunctionAlias(org.h2.engine.FunctionAlias) ConditionIn(org.h2.expression.ConditionIn) AlterTableAddConstraint(org.h2.command.ddl.AlterTableAddConstraint) CompareLike(org.h2.expression.CompareLike) ConditionInConstantSet(org.h2.expression.ConditionInConstantSet) ConditionInSelect(org.h2.expression.ConditionInSelect) Expression(org.h2.expression.Expression) GridSqlType.fromExpression(org.apache.ignite.internal.processors.query.h2.sql.GridSqlType.fromExpression) ValueExpression(org.h2.expression.ValueExpression) FunctionAlias(org.h2.engine.FunctionAlias) Alias(org.h2.expression.Alias) ValueExpression(org.h2.expression.ValueExpression) Parameter(org.h2.expression.Parameter) Aggregate(org.h2.expression.Aggregate) ConditionExists(org.h2.expression.ConditionExists)

Aggregations

IgniteCheckedException (org.apache.ignite.IgniteCheckedException)37 IgniteSQLException (org.apache.ignite.internal.processors.query.IgniteSQLException)33 ArrayList (java.util.ArrayList)26 GridH2Table (org.apache.ignite.internal.processors.query.h2.opt.GridH2Table)25 List (java.util.List)22 IgniteException (org.apache.ignite.IgniteException)21 SQLException (java.sql.SQLException)15 GridCacheContext (org.apache.ignite.internal.processors.cache.GridCacheContext)15 GridH2RowDescriptor (org.apache.ignite.internal.processors.query.h2.opt.GridH2RowDescriptor)13 HashMap (java.util.HashMap)12 Column (org.h2.table.Column)12 LinkedHashMap (java.util.LinkedHashMap)11 GridQueryTypeDescriptor (org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor)11 Index (org.h2.index.Index)11 PreparedStatement (java.sql.PreparedStatement)9 SqlFieldsQuery (org.apache.ignite.cache.query.SqlFieldsQuery)9 GridQueryProperty (org.apache.ignite.internal.processors.query.GridQueryProperty)9 UpdatePlan (org.apache.ignite.internal.processors.query.h2.dml.UpdatePlan)9 GridSqlColumn (org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn)9 GridSqlElement (org.apache.ignite.internal.processors.query.h2.sql.GridSqlElement)9