Search in sources :

Example 36 with Column

use of org.h2.table.Column in project ignite by apache.

the class GridReduceQueryExecutor method planColumns.

/**
 * @return Columns.
 */
private static ArrayList<Column> planColumns() {
    ArrayList<Column> res = new ArrayList<>(1);
    res.add(new Column("PLAN", Value.STRING));
    return res;
}
Also used : GridSqlSortColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlSortColumn) Column(org.h2.table.Column) ArrayList(java.util.ArrayList)

Example 37 with Column

use of org.h2.table.Column in project ignite by apache.

the class H2TableDescriptor method createUserIndex.

/**
 * Create user index.
 *
 * @param idxDesc Index descriptor.
 * @return Index.
 */
public GridH2IndexBase createUserIndex(GridQueryIndexDescriptor idxDesc) {
    IndexColumn keyCol = tbl.indexColumn(KEY_COL, SortOrder.ASCENDING);
    IndexColumn affCol = tbl.getAffinityKeyColumn();
    List<IndexColumn> cols = new ArrayList<>(idxDesc.fields().size() + 2);
    for (String field : idxDesc.fields()) {
        Column col = tbl.getColumn(field);
        cols.add(tbl.indexColumn(col.getColumnId(), idxDesc.descending(field) ? SortOrder.DESCENDING : SortOrder.ASCENDING));
    }
    GridH2RowDescriptor desc = tbl.rowDescriptor();
    if (idxDesc.type() == QueryIndexType.SORTED) {
        cols = H2Utils.treeIndexColumns(desc, cols, keyCol, affCol);
        return idx.createSortedIndex(idxDesc.name(), tbl, false, cols, idxDesc.inlineSize());
    } else if (idxDesc.type() == QueryIndexType.GEOSPATIAL)
        return H2Utils.createSpatialIndex(tbl, idxDesc.name(), cols.toArray(new IndexColumn[cols.size()]));
    throw new IllegalStateException("Index type: " + idxDesc.type());
}
Also used : GridH2RowDescriptor(org.apache.ignite.internal.processors.query.h2.opt.GridH2RowDescriptor) Column(org.h2.table.Column) IndexColumn(org.h2.table.IndexColumn) ArrayList(java.util.ArrayList) IndexColumn(org.h2.table.IndexColumn)

Example 38 with Column

use of org.h2.table.Column in project ignite by apache.

the class DmlUtils method convert.

/**
 * Convert value to column's expected type by means of H2.
 *
 * @param val Source value.
 * @param desc Row descriptor.
 * @param expCls Expected value class.
 * @param type Expected column type to convert to.
 * @return Converted object.
 * @throws IgniteCheckedException if failed.
 */
@SuppressWarnings({ "ConstantConditions", "SuspiciousSystemArraycopy" })
public static Object convert(Object val, GridH2RowDescriptor desc, Class<?> expCls, int type) throws IgniteCheckedException {
    if (val == null)
        return null;
    Class<?> currCls = val.getClass();
    try {
        if (val instanceof Date && currCls != Date.class && expCls == Date.class) {
            // precise Date instance. Let's satisfy it.
            return new Date(((Date) val).getTime());
        }
        // User-given UUID is always serialized by H2 to byte array, so we have to deserialize manually
        if (type == Value.UUID && currCls == byte[].class)
            return U.unmarshal(desc.context().marshaller(), (byte[]) val, U.resolveClassLoader(desc.context().gridConfig()));
        if (LocalDateTimeUtils.isJava8DateApiPresent()) {
            if (val instanceof Timestamp && LocalDateTimeUtils.isLocalDateTime(expCls))
                return LocalDateTimeUtils.valueToLocalDateTime(ValueTimestamp.get((Timestamp) val));
            if (val instanceof Date && LocalDateTimeUtils.isLocalDate(expCls))
                return LocalDateTimeUtils.valueToLocalDate(ValueDate.fromDateValue(DateTimeUtils.dateValueFromDate(((Date) val).getTime())));
            if (val instanceof Time && LocalDateTimeUtils.isLocalTime(expCls))
                return LocalDateTimeUtils.valueToLocalTime(ValueTime.get((Time) val));
        }
        // Still, we only can convert from Object[] to something more precise.
        if (type == Value.ARRAY && currCls != expCls) {
            if (currCls != Object[].class)
                throw new IgniteCheckedException("Unexpected array type - only conversion from Object[] " + "is assumed");
            // Why would otherwise type be Value.ARRAY?
            assert expCls.isArray();
            Object[] curr = (Object[]) val;
            Object newArr = Array.newInstance(expCls.getComponentType(), curr.length);
            System.arraycopy(curr, 0, newArr, 0, curr.length);
            return newArr;
        }
        Object res = H2Utils.convert(val, desc, type);
        if (res instanceof Date && res.getClass() != Date.class && expCls == Date.class) {
            // without query - let's handle this
            return new Date(((Date) res).getTime());
        }
        return res;
    } catch (Exception e) {
        throw new IgniteSQLException("Value conversion failed [from=" + currCls.getName() + ", to=" + expCls.getName() + ']', IgniteQueryErrorCode.CONVERSION_FAILED, e);
    }
}
Also used : IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) Time(java.sql.Time) ValueTime(org.h2.value.ValueTime) Timestamp(java.sql.Timestamp) ValueTimestamp(org.h2.value.ValueTimestamp) Date(java.util.Date) ValueDate(org.h2.value.ValueDate) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException)

Example 39 with Column

use of org.h2.table.Column 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.
 */
@SuppressWarnings("ConstantConditions")
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()];
    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);
        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;
    }
    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);
}
Also used : GridQueryProperty(org.apache.ignite.internal.processors.query.GridQueryProperty) GridH2RowDescriptor(org.apache.ignite.internal.processors.query.h2.opt.GridH2RowDescriptor) Column(org.h2.table.Column) GridSqlColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException)

Example 40 with Column

use of org.h2.table.Column in project ignite by apache.

the class UpdatePlanBuilder method planForUpdate.

/**
 * Prepare update plan for UPDATE or DELETE.
 *
 * @param stmt UPDATE or DELETE statement.
 * @param loc Local query flag.
 * @param idx Indexing.
 * @param conn Connection.
 * @param fieldsQuery Original query.
 * @param errKeysPos index to inject param for re-run keys at. Null if it's not a re-run plan.
 * @return Update plan.
 * @throws IgniteCheckedException if failed.
 */
private static UpdatePlan planForUpdate(GridSqlStatement stmt, boolean loc, IgniteH2Indexing idx, @Nullable Connection conn, @Nullable SqlFieldsQuery fieldsQuery, @Nullable Integer errKeysPos) throws IgniteCheckedException {
    GridSqlElement target;
    FastUpdate fastUpdate;
    UpdateMode mode;
    if (stmt instanceof GridSqlUpdate) {
        // Let's verify that user is not trying to mess with key's columns directly
        verifyUpdateColumns(stmt);
        GridSqlUpdate update = (GridSqlUpdate) stmt;
        target = update.target();
        fastUpdate = DmlAstUtils.getFastUpdateArgs(update);
        mode = UpdateMode.UPDATE;
    } else if (stmt instanceof GridSqlDelete) {
        GridSqlDelete del = (GridSqlDelete) stmt;
        target = del.from();
        fastUpdate = DmlAstUtils.getFastDeleteArgs(del);
        mode = UpdateMode.DELETE;
    } else
        throw new IgniteSQLException("Unexpected DML operation [cls=" + stmt.getClass().getName() + ']', IgniteQueryErrorCode.UNEXPECTED_OPERATION);
    GridSqlTable tbl = DmlAstUtils.gridTableForElement(target);
    GridH2Table h2Tbl = tbl.dataTable();
    GridH2RowDescriptor desc = h2Tbl.rowDescriptor();
    if (desc == null)
        throw new IgniteSQLException("Row descriptor undefined for table '" + h2Tbl.getName() + "'", IgniteQueryErrorCode.NULL_TABLE_DESCRIPTOR);
    if (fastUpdate != null) {
        return new UpdatePlan(mode, h2Tbl, null, fastUpdate, null);
    } else {
        GridSqlSelect sel;
        if (stmt instanceof GridSqlUpdate) {
            List<GridSqlColumn> updatedCols = ((GridSqlUpdate) stmt).cols();
            int valColIdx = -1;
            String[] colNames = new String[updatedCols.size()];
            int[] colTypes = new int[updatedCols.size()];
            for (int i = 0; i < updatedCols.size(); i++) {
                colNames[i] = updatedCols.get(i).columnName();
                colTypes[i] = updatedCols.get(i).resultType().type();
                Column col = updatedCols.get(i).column();
                if (desc.isValueColumn(col.getColumnId()))
                    valColIdx = i;
            }
            boolean hasNewVal = (valColIdx != -1);
            // Statement updates distinct properties if it does not have _val in updated columns list
            // or if its list of updated columns includes only _val, i.e. is single element.
            boolean hasProps = !hasNewVal || updatedCols.size() > 1;
            // Index of new _val in results of SELECT
            if (hasNewVal)
                valColIdx += 2;
            int newValColIdx = (hasNewVal ? valColIdx : 1);
            KeyValueSupplier valSupplier = createSupplier(desc.context(), desc.type(), newValColIdx, hasProps, false, true);
            sel = DmlAstUtils.selectForUpdate((GridSqlUpdate) stmt, errKeysPos);
            String selectSql = sel.getSQL();
            DmlDistributedPlanInfo distributed = F.isEmpty(selectSql) ? null : checkPlanCanBeDistributed(idx, conn, fieldsQuery, loc, selectSql, tbl.dataTable().cacheName());
            return new UpdatePlan(UpdateMode.UPDATE, h2Tbl, colNames, colTypes, null, valSupplier, -1, valColIdx, selectSql, false, null, 0, null, distributed);
        } else {
            sel = DmlAstUtils.selectForDelete((GridSqlDelete) stmt, errKeysPos);
            String selectSql = sel.getSQL();
            DmlDistributedPlanInfo distributed = F.isEmpty(selectSql) ? null : checkPlanCanBeDistributed(idx, conn, fieldsQuery, loc, selectSql, tbl.dataTable().cacheName());
            return new UpdatePlan(UpdateMode.DELETE, h2Tbl, selectSql, null, distributed);
        }
    }
}
Also used : GridSqlDelete(org.apache.ignite.internal.processors.query.h2.sql.GridSqlDelete) GridSqlSelect(org.apache.ignite.internal.processors.query.h2.sql.GridSqlSelect) GridH2RowDescriptor(org.apache.ignite.internal.processors.query.h2.opt.GridH2RowDescriptor) Column(org.h2.table.Column) GridSqlColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn) GridSqlTable(org.apache.ignite.internal.processors.query.h2.sql.GridSqlTable) GridH2Table(org.apache.ignite.internal.processors.query.h2.opt.GridH2Table) GridSqlColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) GridSqlElement(org.apache.ignite.internal.processors.query.h2.sql.GridSqlElement) GridSqlUpdate(org.apache.ignite.internal.processors.query.h2.sql.GridSqlUpdate)

Aggregations

Column (org.h2.table.Column)29 IgniteSQLException (org.apache.ignite.internal.processors.query.IgniteSQLException)16 IndexColumn (org.h2.table.IndexColumn)15 GridH2RowDescriptor (org.apache.ignite.internal.processors.query.h2.opt.GridH2RowDescriptor)12 GridH2Table (org.apache.ignite.internal.processors.query.h2.opt.GridH2Table)11 AlterTableAlterColumn (org.h2.command.ddl.AlterTableAlterColumn)8 ExpressionColumn (org.h2.expression.ExpressionColumn)8 ArrayList (java.util.ArrayList)7 GridSqlColumn (org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn)7 GridSqlType.fromColumn (org.apache.ignite.internal.processors.query.h2.sql.GridSqlType.fromColumn)7 AlterTableAddConstraint (org.h2.command.ddl.AlterTableAddConstraint)7 Expression (org.h2.expression.Expression)7 HashMap (java.util.HashMap)6 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)6 HashSet (java.util.HashSet)5 LinkedHashMap (java.util.LinkedHashMap)5 IgniteException (org.apache.ignite.IgniteException)5 GridSqlElement (org.apache.ignite.internal.processors.query.h2.sql.GridSqlElement)5 GridSqlTable (org.apache.ignite.internal.processors.query.h2.sql.GridSqlTable)5 ValueExpression (org.h2.expression.ValueExpression)5