Search in sources :

Example 26 with Cache

use of org.h2.util.Cache in project h2database by h2database.

the class TestSequence method testConcurrentCreate.

private void testConcurrentCreate() throws Exception {
    deleteDb("sequence");
    final String url = getURL("sequence;MULTI_THREADED=1;LOCK_TIMEOUT=2000", true);
    Connection conn = getConnection(url);
    Task[] tasks = new Task[2];
    try {
        Statement stat = conn.createStatement();
        stat.execute("create table dummy(id bigint primary key)");
        stat.execute("create table test(id bigint primary key)");
        stat.execute("create sequence test_seq cache 2");
        for (int i = 0; i < tasks.length; i++) {
            final int x = i;
            tasks[i] = new Task() {

                @Override
                public void call() throws Exception {
                    try (Connection conn = getConnection(url)) {
                        PreparedStatement prep = conn.prepareStatement("insert into test(id) values(next value for test_seq)");
                        PreparedStatement prep2 = conn.prepareStatement("delete from test");
                        while (!stop) {
                            prep.execute();
                            if (Math.random() < 0.01) {
                                prep2.execute();
                            }
                            if (Math.random() < 0.01) {
                                createDropTrigger(conn);
                            }
                        }
                    }
                }

                private void createDropTrigger(Connection conn) throws Exception {
                    String triggerName = "t_" + x;
                    Statement stat = conn.createStatement();
                    stat.execute("create trigger " + triggerName + " before insert on dummy call \"" + TriggerTest.class.getName() + "\"");
                    stat.execute("drop trigger " + triggerName);
                }
            }.execute();
        }
        Thread.sleep(1000);
        for (Task t : tasks) {
            t.get();
        }
    } finally {
        for (Task t : tasks) {
            t.join();
        }
        conn.close();
    }
}
Also used : Task(org.h2.util.Task) Statement(java.sql.Statement) PreparedStatement(java.sql.PreparedStatement) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement)

Example 27 with Cache

use of org.h2.util.Cache in project ignite by apache.

the class IgniteH2Indexing method unregisterCache.

/** {@inheritDoc} */
@Override
public void unregisterCache(String cacheName) {
    String schemaName = schema(cacheName);
    boolean dflt = isDefaultSchema(schemaName);
    H2Schema schema = dflt ? schemas.get(schemaName) : schemas.remove(schemaName);
    if (schema != null) {
        mapQryExec.onCacheStop(cacheName);
        dmlProc.onCacheStop(cacheName);
        // Remove this mapping only after callback to DML proc - it needs that mapping internally
        cacheName2schema.remove(cacheName);
        // Drop tables.
        Collection<H2TableDescriptor> rmvTbls = new HashSet<>();
        for (H2TableDescriptor tbl : schema.tables()) {
            if (F.eq(tbl.cache().name(), cacheName)) {
                try {
                    dropTable(tbl);
                } catch (IgniteCheckedException e) {
                    U.error(log, "Failed to drop table on cache stop (will ignore): " + tbl.fullTableName(), e);
                }
                schema.drop(tbl);
                rmvTbls.add(tbl);
            }
        }
        if (!dflt) {
            try {
                dropSchema(schemaName);
            } catch (IgniteCheckedException e) {
                U.error(log, "Failed to drop schema on cache stop (will ignore): " + cacheName, e);
            }
        }
        for (H2TableDescriptor tbl : rmvTbls) {
            for (Index idx : tbl.table().getIndexes()) idx.close(null);
        }
        int cacheId = CU.cacheId(cacheName);
        for (Iterator<Map.Entry<H2TwoStepCachedQueryKey, H2TwoStepCachedQuery>> it = twoStepCache.entrySet().iterator(); it.hasNext(); ) {
            Map.Entry<H2TwoStepCachedQueryKey, H2TwoStepCachedQuery> e = it.next();
            GridCacheTwoStepQuery qry = e.getValue().query();
            if (!F.isEmpty(qry.cacheIds()) && qry.cacheIds().contains(cacheId))
                it.remove();
        }
    }
}
Also used : GridCacheTwoStepQuery(org.apache.ignite.internal.processors.cache.query.GridCacheTwoStepQuery) Index(org.h2.index.Index) H2TreeIndex(org.apache.ignite.internal.processors.query.h2.database.H2TreeIndex) H2PkHashIndex(org.apache.ignite.internal.processors.query.h2.database.H2PkHashIndex) IgniteSystemProperties.getString(org.apache.ignite.IgniteSystemProperties.getString) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) GridBoundedConcurrentLinkedHashMap(org.apache.ignite.internal.util.GridBoundedConcurrentLinkedHashMap) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 28 with Cache

use of org.h2.util.Cache in project ignite by apache.

the class DmlStatementsProcessor method rowToKeyValue.

/**
     * Convert row presented as an array of Objects into key-value pair to be inserted to cache.
     * @param cctx Cache context.
     * @param row Row to process.
     * @param plan Update plan.
     * @throws IgniteCheckedException if failed.
     */
@SuppressWarnings({ "unchecked", "ConstantConditions", "ResultOfMethodCallIgnored" })
private IgniteBiTuple<?, ?> rowToKeyValue(GridCacheContext cctx, List<?> row, UpdatePlan plan) throws IgniteCheckedException {
    GridH2RowDescriptor rowDesc = plan.tbl.rowDescriptor();
    GridQueryTypeDescriptor desc = rowDesc.type();
    Object key = plan.keySupplier.apply(row);
    if (QueryUtils.isSqlType(desc.keyClass())) {
        assert plan.keyColIdx != -1;
        key = convert(key, rowDesc, desc.keyClass(), plan.colTypes[plan.keyColIdx]);
    }
    Object val = plan.valSupplier.apply(row);
    if (QueryUtils.isSqlType(desc.valueClass())) {
        assert plan.valColIdx != -1;
        val = convert(val, rowDesc, desc.valueClass(), plan.colTypes[plan.valColIdx]);
    }
    if (key == null)
        throw new IgniteSQLException("Key for INSERT or MERGE must not be null", IgniteQueryErrorCode.NULL_KEY);
    if (val == null)
        throw new IgniteSQLException("Value for INSERT or MERGE must not be null", IgniteQueryErrorCode.NULL_VALUE);
    Map<String, Object> newColVals = new HashMap<>();
    for (int i = 0; i < plan.colNames.length; i++) {
        if (i == plan.keyColIdx || i == plan.valColIdx)
            continue;
        String colName = plan.colNames[i];
        GridQueryProperty prop = desc.property(colName);
        assert prop != null;
        Class<?> expCls = prop.type();
        newColVals.put(colName, convert(row.get(i), rowDesc, expCls, plan.colTypes[i]));
    }
    // We update columns in the order specified by the table for a reason - table's
    // column order preserves their precedence for correct update of nested properties.
    Column[] cols = plan.tbl.getColumns();
    // First 3 columns are _key, _val and _ver. Skip 'em.
    for (int i = DEFAULT_COLUMNS_COUNT; i < cols.length; i++) {
        if (plan.tbl.rowDescriptor().isKeyValueOrVersionColumn(i))
            continue;
        String colName = cols[i].getName();
        if (!newColVals.containsKey(colName))
            continue;
        Object colVal = newColVals.get(colName);
        desc.setValue(colName, key, val, colVal);
    }
    if (cctx.binaryMarshaller()) {
        if (key instanceof BinaryObjectBuilder)
            key = ((BinaryObjectBuilder) key).build();
        if (val instanceof BinaryObjectBuilder)
            val = ((BinaryObjectBuilder) val).build();
    }
    return new IgniteBiTuple<>(key, val);
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) GridBoundedConcurrentLinkedHashMap(org.apache.ignite.internal.util.GridBoundedConcurrentLinkedHashMap) IgniteBiTuple(org.apache.ignite.lang.IgniteBiTuple) GridQueryTypeDescriptor(org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor) GridQueryProperty(org.apache.ignite.internal.processors.query.GridQueryProperty) GridH2RowDescriptor(org.apache.ignite.internal.processors.query.h2.opt.GridH2RowDescriptor) Column(org.h2.table.Column) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) BinaryObject(org.apache.ignite.binary.BinaryObject) BinaryObjectBuilder(org.apache.ignite.binary.BinaryObjectBuilder)

Example 29 with Cache

use of org.h2.util.Cache in project ignite by apache.

the class GridH2AbstractKeyValueRow method getValue.

/** {@inheritDoc} */
@Override
public Value getValue(int col) {
    Value[] vCache = valCache;
    if (vCache != null) {
        Value v = vCache[col];
        if (v != null)
            return v;
    }
    Value v;
    if (desc.isValueColumn(col)) {
        v = peekValue(VAL_COL);
        assert !(v instanceof WeakValue) : v;
        return v;
    } else if (desc.isKeyColumn(col)) {
        v = peekValue(KEY_COL);
        if (v == null) {
            v = getOffheapValue(KEY_COL);
            assert v != null;
            setValue(KEY_COL, v);
            if (peekValue(VAL_COL) == null)
                cache();
        }
        assert !(v instanceof WeakValue) : v;
        return v;
    } else if (col == VER_COL)
        return version;
    col -= DEFAULT_COLUMNS_COUNT;
    assert col >= 0;
    Value key = getValue(KEY_COL);
    Value val = getValue(VAL_COL);
    assert key != null;
    assert val != null;
    Object res = desc.columnValue(key.getObject(), val.getObject(), col);
    if (res == null)
        v = ValueNull.INSTANCE;
    else {
        try {
            v = desc.wrap(res, desc.fieldType(col));
        } catch (IgniteCheckedException e) {
            throw DbException.convert(e);
        }
    }
    if (vCache != null)
        vCache[col + DEFAULT_COLUMNS_COUNT] = v;
    return v;
}
Also used : IgniteCheckedException(org.apache.ignite.IgniteCheckedException) Value(org.h2.value.Value)

Example 30 with Cache

use of org.h2.util.Cache in project ignite by apache.

the class H2DynamicTableSelfTest method testSqlFlagCompatibilityCheck.

/**
 * Test that attempting to start a node that has a cache with the name already present in the grid and whose
 * SQL flag does not match that of cache with the same name that is already started, yields an error.
 * @throws Exception if failed.
 */
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
public void testSqlFlagCompatibilityCheck() throws Exception {
    execute("CREATE TABLE \"Person\" (\"id\" int, \"city\" varchar, \"name\" varchar, \"surname\" varchar, " + "\"age\" int, PRIMARY KEY (\"id\", \"city\")) WITH \"template=cache\"");
    GridTestUtils.assertThrows(null, new Callable<Object>() {

        @Override
        public Object call() throws Exception {
            String cacheName = cacheName("Person");
            Ignition.start(clientConfiguration(5).setCacheConfiguration(new CacheConfiguration(cacheName)));
            return null;
        }
    }, IgniteException.class, "Cache configuration mismatch (local cache was created via Ignite API, while " + "remote cache was created via CREATE TABLE): SQL_PUBLIC_Person");
}
Also used : BinaryObject(org.apache.ignite.binary.BinaryObject) IgniteException(org.apache.ignite.IgniteException) SQLException(java.sql.SQLException) CacheException(javax.cache.CacheException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) JdbcSQLException(org.h2.jdbc.JdbcSQLException) SchemaOperationException(org.apache.ignite.internal.processors.query.schema.SchemaOperationException) CacheConfiguration(org.apache.ignite.configuration.CacheConfiguration)

Aggregations

IgniteCheckedException (org.apache.ignite.IgniteCheckedException)12 Connection (java.sql.Connection)11 PreparedStatement (java.sql.PreparedStatement)10 IgniteSQLException (org.apache.ignite.internal.processors.query.IgniteSQLException)10 ResultSet (java.sql.ResultSet)9 SQLException (java.sql.SQLException)9 CacheException (javax.cache.CacheException)9 Statement (java.sql.Statement)7 ArrayList (java.util.ArrayList)7 IgniteException (org.apache.ignite.IgniteException)7 List (java.util.List)5 UUID (java.util.UUID)5 IgniteSystemProperties.getString (org.apache.ignite.IgniteSystemProperties.getString)5 ClusterNode (org.apache.ignite.cluster.ClusterNode)5 Prepared (org.h2.command.Prepared)5 IntArray (org.h2.util.IntArray)5 HashMap (java.util.HashMap)4 LinkedHashMap (java.util.LinkedHashMap)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)4 BinaryObject (org.apache.ignite.binary.BinaryObject)4