Search in sources :

Example 11 with Table

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

the class GridH2Table method doUpdate.

/**
     * For testing only.
     *
     * @param row Row.
     * @param del If given row should be deleted from table.
     * @return {@code True} if operation succeeded.
     * @throws IgniteCheckedException If failed.
     */
@SuppressWarnings("LockAcquiredButNotSafelyReleased")
boolean doUpdate(final GridH2Row row, boolean del) throws IgniteCheckedException {
    // Here we assume that each key can't be updated concurrently and case when different indexes
    // getting updated from different threads with different rows with the same key is impossible.
    GridUnsafeMemory mem = desc == null ? null : desc.memory();
    lock(false);
    if (mem != null)
        desc.guard().begin();
    try {
        ensureNotDestroyed();
        GridH2IndexBase pk = pk();
        if (!del) {
            assert rowFactory == null || row.link != 0 : row;
            // Put to PK.
            GridH2Row old = pk.put(row);
            if (old == null)
                size.increment();
            int len = idxs.size();
            int i = pkIndexPos;
            // Start from 3 because 0 - Scan (don't need to update), 1 - PK hash (already updated), 2 - PK (already updated).
            while (++i < len) {
                if (!(idxs.get(i) instanceof GridH2IndexBase))
                    continue;
                GridH2IndexBase idx = index(i);
                addToIndex(idx, pk, row, old, false);
            }
            for (GridH2IndexBase idx : tmpIdxs.values()) addToIndex(idx, pk, row, old, true);
        } else {
            //  index(1) is PK, get full row from there (search row here contains only key but no other columns).
            GridH2Row old = pk.remove(row);
            if (old != null) {
                // Start from 3 because 0 - Scan (don't need to update), 1 - PK hash (already updated), 2 - PK (already updated).
                for (int i = pkIndexPos + 1, len = idxs.size(); i < len; i++) {
                    if (!(idxs.get(i) instanceof GridH2IndexBase))
                        continue;
                    Row res = index(i).remove(old);
                    assert eq(pk, res, old) : "\n" + old + "\n" + res + "\n" + i + " -> " + index(i).getName();
                }
                for (GridH2IndexBase idx : tmpIdxs.values()) idx.remove(old);
                size.decrement();
            } else
                return false;
        }
        // The snapshot is not actual after update.
        if (actualSnapshot != null)
            actualSnapshot.set(pk.segmentForRow(row), null);
        return true;
    } finally {
        unlock(false);
        if (mem != null)
            desc.guard().end();
    }
}
Also used : Row(org.h2.result.Row) SearchRow(org.h2.result.SearchRow) GridUnsafeMemory(org.apache.ignite.internal.util.offheap.unsafe.GridUnsafeMemory)

Example 12 with Table

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

the class GridH2IndexBase method segmentForRow.

/**
     * @param row Table row.
     * @return Segment ID for given row.
     */
protected int segmentForRow(SearchRow row) {
    assert row != null;
    CacheObject key;
    if (ctx != null) {
        final Value keyColValue = row.getValue(KEY_COL);
        assert keyColValue != null;
        final Object o = keyColValue.getObject();
        if (o instanceof CacheObject)
            key = (CacheObject) o;
        else
            key = ctx.toCacheKeyObject(o);
        return segmentForPartition(ctx.affinity().partition(key));
    }
    assert segmentsCount() == 1;
    return 0;
}
Also used : Value(org.h2.value.Value) CacheObject(org.apache.ignite.internal.processors.cache.CacheObject) CacheObject(org.apache.ignite.internal.processors.cache.CacheObject)

Example 13 with Table

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

the class DmlAstUtils method selectForDelete.

/**
     * Generate SQL SELECT based on DELETE's WHERE, LIMIT, etc.
     *
     * @param del Delete statement.
     * @param keysParamIdx Index for .
     * @return SELECT statement.
     */
public static GridSqlSelect selectForDelete(GridSqlDelete del, @Nullable Integer keysParamIdx) {
    GridSqlSelect mapQry = new GridSqlSelect();
    mapQry.from(del.from());
    Set<GridSqlTable> tbls = new HashSet<>();
    collectAllGridTablesInTarget(del.from(), tbls);
    assert tbls.size() == 1 : "Failed to determine target table for DELETE";
    GridSqlTable tbl = tbls.iterator().next();
    GridH2Table gridTbl = tbl.dataTable();
    assert gridTbl != null : "Failed to determine target grid table for DELETE";
    Column h2KeyCol = gridTbl.getColumn(GridH2AbstractKeyValueRow.KEY_COL);
    Column h2ValCol = gridTbl.getColumn(GridH2AbstractKeyValueRow.VAL_COL);
    GridSqlColumn keyCol = new GridSqlColumn(h2KeyCol, tbl, h2KeyCol.getName());
    keyCol.resultType(GridSqlType.fromColumn(h2KeyCol));
    GridSqlColumn valCol = new GridSqlColumn(h2ValCol, tbl, h2ValCol.getName());
    valCol.resultType(GridSqlType.fromColumn(h2ValCol));
    mapQry.addColumn(keyCol, true);
    mapQry.addColumn(valCol, true);
    GridSqlElement where = del.where();
    if (keysParamIdx != null)
        where = injectKeysFilterParam(where, keyCol, keysParamIdx);
    mapQry.where(where);
    mapQry.limit(del.limit());
    return mapQry;
}
Also used : Column(org.h2.table.Column) GridH2Table(org.apache.ignite.internal.processors.query.h2.opt.GridH2Table) HashSet(java.util.HashSet)

Example 14 with Table

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

the class GridSqlFunction method getSQL.

/** {@inheritDoc} */
@Override
public String getSQL() {
    StatementBuilder buff = new StatementBuilder();
    if (schema != null)
        buff.append(Parser.quoteIdentifier(schema)).append('.');
    // We don't need to quote identifier as long as H2 never does so with function names when generating plan SQL.
    // On the other hand, quoting identifiers that also serve as keywords (like CURRENT_DATE() and CURRENT_DATE)
    // turns CURRENT_DATE() into "CURRENT_DATE"(), which is not good.
    buff.append(name);
    if (type == CASE) {
        buff.append(' ').append(child().getSQL());
        for (int i = 1, len = size() - 1; i < len; i += 2) {
            buff.append(" WHEN ").append(child(i).getSQL());
            buff.append(" THEN ").append(child(i + 1).getSQL());
        }
        if ((size() & 1) == 0)
            buff.append(" ELSE ").append(child(size() - 1).getSQL());
        return buff.append(" END").toString();
    }
    buff.append('(');
    switch(type) {
        case CAST:
        case CONVERT:
            assert size() == 1;
            String castType = resultType().sql();
            assert !F.isEmpty(castType) : castType;
            buff.append(child().getSQL());
            buff.append(type == CAST ? " AS " : ",");
            buff.append(castType);
            break;
        case EXTRACT:
            ValueString v = (ValueString) ((GridSqlConst) child(0)).value();
            buff.append(v.getString()).append(" FROM ").append(child(1).getSQL());
            break;
        case TABLE:
            for (int i = 0; i < size(); i++) {
                buff.appendExceptFirst(", ");
                GridSqlElement e = child(i);
                // id int = ?, name varchar = ('aaa', 'bbb')
                buff.append(Parser.quoteIdentifier(((GridSqlAlias) e).alias())).append(' ').append(e.resultType().sql()).append('=').append(e.child().getSQL());
            }
            break;
        default:
            for (int i = 0; i < size(); i++) {
                buff.appendExceptFirst(", ");
                buff.append(child(i).getSQL());
            }
    }
    return buff.append(')').toString();
}
Also used : StatementBuilder(org.h2.util.StatementBuilder) ValueString(org.h2.value.ValueString) ValueString(org.h2.value.ValueString)

Example 15 with Table

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

the class GridSqlQueryParser method processExtraParam.

/**
     * @param name Param name.
     * @param val Param value.
     * @param res Table params to update.
     */
private static void processExtraParam(String name, String val, GridSqlCreateTable res) {
    assert !F.isEmpty(name);
    switch(name) {
        case PARAM_TEMPLATE:
            ensureNotEmpty(name, val);
            res.templateName(val);
            break;
        case PARAM_BACKUPS:
            ensureNotEmpty(name, val);
            int backups = parseIntParam(PARAM_BACKUPS, val);
            if (backups < 0)
                throw new IgniteSQLException("\"" + PARAM_BACKUPS + "\" cannot be negative: " + backups, IgniteQueryErrorCode.PARSING);
            res.backups(backups);
            break;
        case PARAM_ATOMICITY:
            ensureNotEmpty(name, val);
            CacheAtomicityMode mode;
            if (CacheAtomicityMode.TRANSACTIONAL.name().equalsIgnoreCase(val))
                mode = CacheAtomicityMode.TRANSACTIONAL;
            else if (CacheAtomicityMode.ATOMIC.name().equalsIgnoreCase(val))
                mode = CacheAtomicityMode.ATOMIC;
            else
                throw new IgniteSQLException("Invalid value of \"" + PARAM_ATOMICITY + "\" parameter " + "(should be either TRANSACTIONAL or ATOMIC): " + val, IgniteQueryErrorCode.PARSING);
            res.atomicityMode(mode);
            break;
        default:
            throw new IgniteSQLException("Unsupported parameter: " + name, IgniteQueryErrorCode.PARSING);
    }
}
Also used : IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) CacheAtomicityMode(org.apache.ignite.cache.CacheAtomicityMode) AlterTableAddConstraint(org.h2.command.ddl.AlterTableAddConstraint)

Aggregations

Column (org.h2.table.Column)11 Statement (java.sql.Statement)8 IndexColumn (org.h2.table.IndexColumn)8 IgniteSQLException (org.apache.ignite.internal.processors.query.IgniteSQLException)7 PreparedStatement (java.sql.PreparedStatement)6 AlterTableAddConstraint (org.h2.command.ddl.AlterTableAddConstraint)6 Table (org.h2.table.Table)6 Connection (java.sql.Connection)5 ResultSet (java.sql.ResultSet)5 SQLException (java.sql.SQLException)5 ArrayList (java.util.ArrayList)4 LinkedHashMap (java.util.LinkedHashMap)4 Map (java.util.Map)4 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)4 IgniteException (org.apache.ignite.IgniteException)4 GridH2Table (org.apache.ignite.internal.processors.query.h2.opt.GridH2Table)4 Prepared (org.h2.command.Prepared)4 Query (org.h2.command.dml.Query)4 ExpressionColumn (org.h2.expression.ExpressionColumn)4 ValueString (org.h2.value.ValueString)4