Search in sources :

Example 6 with Schema

use of org.h2.schema.Schema in project che by eclipse.

the class SshTckModule method configure.

@Override
protected void configure() {
    H2DBTestServer server = H2DBTestServer.startDefault();
    install(new PersistTestModuleBuilder().setDriver(Driver.class).runningOn(server).addEntityClasses(SshPairImpl.class, UserImpl.class, AccountImpl.class).setExceptionHandler(H2ExceptionHandler.class).build());
    bind(DBInitializer.class).asEagerSingleton();
    bind(SchemaInitializer.class).toInstance(new FlywaySchemaInitializer(server.getDataSource(), "che-schema"));
    bind(TckResourcesCleaner.class).toInstance(new H2JpaCleaner(server));
    bind(SshDao.class).to(JpaSshDao.class);
    bind(new TypeLiteral<TckRepository<SshPairImpl>>() {
    }).toInstance(new JpaTckRepository<>(SshPairImpl.class));
    bind(new TypeLiteral<TckRepository<UserImpl>>() {
    }).toInstance(new JpaTckRepository<>(UserImpl.class));
}
Also used : TckResourcesCleaner(org.eclipse.che.commons.test.tck.TckResourcesCleaner) SshPairImpl(org.eclipse.che.api.ssh.server.model.impl.SshPairImpl) H2DBTestServer(org.eclipse.che.commons.test.db.H2DBTestServer) AccountImpl(org.eclipse.che.account.spi.AccountImpl) Driver(org.h2.Driver) H2JpaCleaner(org.eclipse.che.commons.test.db.H2JpaCleaner) SshDao(org.eclipse.che.api.ssh.server.spi.SshDao) PersistTestModuleBuilder(org.eclipse.che.commons.test.db.PersistTestModuleBuilder) SchemaInitializer(org.eclipse.che.core.db.schema.SchemaInitializer) FlywaySchemaInitializer(org.eclipse.che.core.db.schema.impl.flyway.FlywaySchemaInitializer) FlywaySchemaInitializer(org.eclipse.che.core.db.schema.impl.flyway.FlywaySchemaInitializer) TypeLiteral(com.google.inject.TypeLiteral) DBInitializer(org.eclipse.che.core.db.DBInitializer) UserImpl(org.eclipse.che.api.user.server.model.impl.UserImpl)

Example 7 with Schema

use of org.h2.schema.Schema in project che by eclipse.

the class JpaTckModule method configure.

@Override
protected void configure() {
    H2DBTestServer server = H2DBTestServer.startDefault();
    install(new PersistTestModuleBuilder().setDriver(Driver.class).runningOn(server).addEntityClasses(UserImpl.class, ProfileImpl.class, PreferenceEntity.class, AccountImpl.class).setExceptionHandler(H2ExceptionHandler.class).build());
    bind(DBInitializer.class).asEagerSingleton();
    bind(SchemaInitializer.class).toInstance(new FlywaySchemaInitializer(server.getDataSource(), "che-schema"));
    bind(TckResourcesCleaner.class).toInstance(new H2JpaCleaner(server.getDataSource()));
    bind(new TypeLiteral<TckRepository<UserImpl>>() {
    }).to(UserJpaTckRepository.class);
    bind(new TypeLiteral<TckRepository<ProfileImpl>>() {
    }).toInstance(new JpaTckRepository<>(ProfileImpl.class));
    bind(new TypeLiteral<TckRepository<Pair<String, Map<String, String>>>>() {
    }).to(PreferenceJpaTckRepository.class);
    bind(UserDao.class).to(JpaUserDao.class);
    bind(ProfileDao.class).to(JpaProfileDao.class);
    bind(PreferenceDao.class).to(JpaPreferenceDao.class);
    // SHA-512 encryptor is faster than PBKDF2 so it is better for testing
    bind(PasswordEncryptor.class).to(SHA512PasswordEncryptor.class).in(Singleton.class);
}
Also used : TckResourcesCleaner(org.eclipse.che.commons.test.tck.TckResourcesCleaner) H2DBTestServer(org.eclipse.che.commons.test.db.H2DBTestServer) AccountImpl(org.eclipse.che.account.spi.AccountImpl) Driver(org.h2.Driver) PreferenceDao(org.eclipse.che.api.user.server.spi.PreferenceDao) SHA512PasswordEncryptor(org.eclipse.che.security.SHA512PasswordEncryptor) H2JpaCleaner(org.eclipse.che.commons.test.db.H2JpaCleaner) PersistTestModuleBuilder(org.eclipse.che.commons.test.db.PersistTestModuleBuilder) SchemaInitializer(org.eclipse.che.core.db.schema.SchemaInitializer) FlywaySchemaInitializer(org.eclipse.che.core.db.schema.impl.flyway.FlywaySchemaInitializer) FlywaySchemaInitializer(org.eclipse.che.core.db.schema.impl.flyway.FlywaySchemaInitializer) ProfileDao(org.eclipse.che.api.user.server.spi.ProfileDao) TypeLiteral(com.google.inject.TypeLiteral) UserDao(org.eclipse.che.api.user.server.spi.UserDao) ProfileImpl(org.eclipse.che.api.user.server.model.impl.ProfileImpl) DBInitializer(org.eclipse.che.core.db.DBInitializer) UserImpl(org.eclipse.che.api.user.server.model.impl.UserImpl) Pair(org.eclipse.che.commons.lang.Pair)

Example 8 with Schema

use of org.h2.schema.Schema in project ignite by apache.

the class DmlStatementsProcessor method getPlanForStatement.

/**
     * Generate SELECT statements to retrieve data for modifications from and find fast UPDATE or DELETE args,
     * if available.
     *
     * @param schema Schema.
     * @param prepStmt JDBC statement.
     * @return Update plan.
     */
@SuppressWarnings({ "unchecked", "ConstantConditions" })
private UpdatePlan getPlanForStatement(String schema, PreparedStatement prepStmt, @Nullable Integer errKeysPos) throws IgniteCheckedException {
    Prepared p = GridSqlQueryParser.prepared(prepStmt);
    H2DmlPlanKey planKey = new H2DmlPlanKey(schema, p.getSQL());
    UpdatePlan res = (errKeysPos == null ? planCache.get(planKey) : null);
    if (res != null)
        return res;
    res = UpdatePlanBuilder.planForStatement(p, errKeysPos);
    // Don't cache re-runs
    if (errKeysPos == null)
        return U.firstNotNull(planCache.putIfAbsent(planKey, res), res);
    else
        return res;
}
Also used : Prepared(org.h2.command.Prepared) UpdatePlan(org.apache.ignite.internal.processors.query.h2.dml.UpdatePlan)

Example 9 with Schema

use of org.h2.schema.Schema in project ignite by apache.

the class DdlStatementsProcessor method runDdlStatement.

/**
     * Execute DDL statement.
     *
     * @param sql SQL.
     * @param stmt H2 statement to parse and execute.
     */
@SuppressWarnings("unchecked")
public FieldsQueryCursor<List<?>> runDdlStatement(String sql, PreparedStatement stmt) throws IgniteCheckedException {
    assert stmt instanceof JdbcPreparedStatement;
    IgniteInternalFuture fut = null;
    try {
        GridSqlStatement stmt0 = new GridSqlQueryParser(false).parse(GridSqlQueryParser.prepared(stmt));
        if (stmt0 instanceof GridSqlCreateIndex) {
            GridSqlCreateIndex cmd = (GridSqlCreateIndex) stmt0;
            GridH2Table tbl = idx.dataTable(cmd.schemaName(), cmd.tableName());
            if (tbl == null)
                throw new SchemaOperationException(SchemaOperationException.CODE_TABLE_NOT_FOUND, cmd.tableName());
            assert tbl.rowDescriptor() != null;
            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());
        } else if (stmt0 instanceof GridSqlDropIndex) {
            GridSqlDropIndex cmd = (GridSqlDropIndex) stmt0;
            GridH2Table tbl = idx.dataTableForIndex(cmd.schemaName(), cmd.indexName());
            if (tbl != null) {
                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 (stmt0 instanceof GridSqlCreateTable) {
            GridSqlCreateTable cmd = (GridSqlCreateTable) stmt0;
            if (!F.eq(QueryUtils.DFLT_SCHEMA, cmd.schemaName()))
                throw new SchemaOperationException("CREATE TABLE can only be executed on " + QueryUtils.DFLT_SCHEMA + " schema.");
            GridH2Table tbl = idx.dataTable(cmd.schemaName(), cmd.tableName());
            if (tbl != null) {
                if (!cmd.ifNotExists())
                    throw new SchemaOperationException(SchemaOperationException.CODE_TABLE_EXISTS, cmd.tableName());
            } else {
                ctx.query().dynamicTableCreate(cmd.schemaName(), toQueryEntity(cmd), cmd.templateName(), cmd.atomicityMode(), cmd.backups(), cmd.ifNotExists());
            }
        } else if (stmt0 instanceof GridSqlDropTable) {
            GridSqlDropTable cmd = (GridSqlDropTable) stmt0;
            if (!F.eq(QueryUtils.DFLT_SCHEMA, cmd.schemaName()))
                throw new SchemaOperationException("DROP TABLE can only be executed on " + QueryUtils.DFLT_SCHEMA + " schema.");
            GridH2Table tbl = idx.dataTable(cmd.schemaName(), cmd.tableName());
            if (tbl == null) {
                if (!cmd.ifExists())
                    throw new SchemaOperationException(SchemaOperationException.CODE_TABLE_NOT_FOUND, cmd.tableName());
            } else
                ctx.query().dynamicTableDrop(tbl.cacheName(), cmd.tableName(), cmd.ifExists());
        } else
            throw new IgniteSQLException("Unsupported DDL operation: " + sql, IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
        if (fut != null)
            fut.get();
        QueryCursorImpl<List<?>> resCur = (QueryCursorImpl<List<?>>) new QueryCursorImpl(Collections.singletonList(Collections.singletonList(0L)), null, false);
        resCur.fieldsMeta(UPDATE_RESULT_META);
        return resCur;
    } catch (SchemaOperationException e) {
        throw convert(e);
    } catch (IgniteSQLException e) {
        throw e;
    } catch (Exception e) {
        throw new IgniteSQLException("Unexpected DLL operation failure: " + e.getMessage(), e);
    }
}
Also used : GridSqlStatement(org.apache.ignite.internal.processors.query.h2.sql.GridSqlStatement) 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) 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) List(java.util.List) JdbcPreparedStatement(org.h2.jdbc.JdbcPreparedStatement) SchemaOperationException(org.apache.ignite.internal.processors.query.schema.SchemaOperationException) GridSqlCreateTable(org.apache.ignite.internal.processors.query.h2.sql.GridSqlCreateTable) QueryCursorImpl(org.apache.ignite.internal.processors.cache.QueryCursorImpl) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) SchemaOperationException(org.apache.ignite.internal.processors.query.schema.SchemaOperationException) GridQueryProperty(org.apache.ignite.internal.processors.query.GridQueryProperty) GridSqlQueryParser(org.apache.ignite.internal.processors.query.h2.sql.GridSqlQueryParser) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) GridSqlDropTable(org.apache.ignite.internal.processors.query.h2.sql.GridSqlDropTable)

Example 10 with Schema

use of org.h2.schema.Schema in project ignite by apache.

the class GridMapQueryExecutor method onQueryRequest0.

/**
     * @param node Node authored request.
     * @param reqId Request ID.
     * @param segmentId index segment ID.
     * @param schemaName Schema name.
     * @param qrys Queries to execute.
     * @param cacheIds Caches which will be affected by these queries.
     * @param topVer Topology version.
     * @param partsMap Partitions map for unstable topology.
     * @param parts Explicit partitions for current node.
     * @param tbls Tables.
     * @param pageSize Page size.
     * @param distributedJoinMode Query distributed join mode.
     */
private void onQueryRequest0(ClusterNode node, long reqId, int segmentId, String schemaName, Collection<GridCacheSqlQuery> qrys, List<Integer> cacheIds, AffinityTopologyVersion topVer, Map<UUID, int[]> partsMap, int[] parts, Collection<QueryTable> tbls, int pageSize, DistributedJoinMode distributedJoinMode, boolean enforceJoinOrder, boolean replicated, int timeout, Object[] params) {
    // Prepare to run queries.
    GridCacheContext<?, ?> mainCctx = !F.isEmpty(cacheIds) ? ctx.cache().context().cacheContext(cacheIds.get(0)) : null;
    NodeResults nodeRess = resultsForNode(node.id());
    QueryResults qr = null;
    List<GridReservable> reserved = new ArrayList<>();
    try {
        if (topVer != null) {
            // Reserve primary for topology version or explicit partitions.
            if (!reservePartitions(cacheIds, topVer, parts, reserved)) {
                sendRetry(node, reqId, segmentId);
                return;
            }
        }
        qr = new QueryResults(reqId, qrys.size(), mainCctx != null ? mainCctx.name() : null);
        if (nodeRess.put(reqId, segmentId, qr) != null)
            throw new IllegalStateException();
        // Prepare query context.
        GridH2QueryContext qctx = new GridH2QueryContext(ctx.localNodeId(), node.id(), reqId, segmentId, replicated ? REPLICATED : MAP).filter(h2.backupFilter(topVer, parts)).partitionsMap(partsMap).distributedJoinMode(distributedJoinMode).pageSize(pageSize).topologyVersion(topVer).reservations(reserved);
        List<GridH2Table> snapshotedTbls = null;
        if (!F.isEmpty(tbls)) {
            snapshotedTbls = new ArrayList<>(tbls.size());
            for (QueryTable tbl : tbls) {
                GridH2Table h2Tbl = h2.dataTable(tbl);
                Objects.requireNonNull(h2Tbl, tbl.toString());
                h2Tbl.snapshotIndexes(qctx, segmentId);
                snapshotedTbls.add(h2Tbl);
            }
        }
        Connection conn = h2.connectionForSchema(schemaName);
        H2Utils.setupConnection(conn, distributedJoinMode != OFF, enforceJoinOrder);
        GridH2QueryContext.set(qctx);
        // qctx is set, we have to release reservations inside of it.
        reserved = null;
        try {
            if (nodeRess.cancelled(reqId)) {
                GridH2QueryContext.clear(ctx.localNodeId(), node.id(), reqId, qctx.type());
                nodeRess.cancelRequest(reqId);
                throw new QueryCancelledException();
            }
            // Run queries.
            int qryIdx = 0;
            boolean evt = mainCctx != null && ctx.event().isRecordable(EVT_CACHE_QUERY_EXECUTED);
            for (GridCacheSqlQuery qry : qrys) {
                ResultSet rs = null;
                // If we are not the target node for this replicated query, just ignore it.
                if (qry.node() == null || (segmentId == 0 && qry.node().equals(ctx.localNodeId()))) {
                    rs = h2.executeSqlQueryWithTimer(conn, qry.query(), F.asList(qry.parameters(params)), true, timeout, qr.cancels[qryIdx]);
                    if (evt) {
                        assert mainCctx != null;
                        ctx.event().record(new CacheQueryExecutedEvent<>(node, "SQL query executed.", EVT_CACHE_QUERY_EXECUTED, CacheQueryType.SQL.name(), mainCctx.name(), null, qry.query(), null, null, params, node.id(), null));
                    }
                    assert rs instanceof JdbcResultSet : rs.getClass();
                }
                qr.addResult(qryIdx, qry, node.id(), rs, params);
                if (qr.canceled) {
                    qr.result(qryIdx).close();
                    throw new QueryCancelledException();
                }
                // Send the first page.
                sendNextPage(nodeRess, node, qr, qryIdx, segmentId, pageSize);
                qryIdx++;
            }
        } finally {
            GridH2QueryContext.clearThreadLocal();
            if (distributedJoinMode == OFF)
                qctx.clearContext(false);
            if (!F.isEmpty(snapshotedTbls)) {
                for (GridH2Table dataTbl : snapshotedTbls) dataTbl.releaseSnapshots();
            }
        }
    } catch (Throwable e) {
        if (qr != null) {
            nodeRess.remove(reqId, segmentId, qr);
            qr.cancel(false);
        }
        if (X.hasCause(e, GridH2RetryException.class))
            sendRetry(node, reqId, segmentId);
        else {
            U.error(log, "Failed to execute local query.", e);
            sendError(node, reqId, e);
            if (e instanceof Error)
                throw (Error) e;
        }
    } finally {
        if (reserved != null) {
            // Release reserved partitions.
            for (int i = 0; i < reserved.size(); i++) reserved.get(i).release();
        }
    }
}
Also used : ArrayList(java.util.ArrayList) Connection(java.sql.Connection) GridH2RetryException(org.apache.ignite.internal.processors.query.h2.opt.GridH2RetryException) GridReservable(org.apache.ignite.internal.processors.cache.distributed.dht.GridReservable) QueryTable(org.apache.ignite.internal.processors.cache.query.QueryTable) GridH2Table(org.apache.ignite.internal.processors.query.h2.opt.GridH2Table) ResultSet(java.sql.ResultSet) JdbcResultSet(org.h2.jdbc.JdbcResultSet) GridCacheSqlQuery(org.apache.ignite.internal.processors.cache.query.GridCacheSqlQuery) QueryCancelledException(org.apache.ignite.cache.query.QueryCancelledException) GridH2QueryContext(org.apache.ignite.internal.processors.query.h2.opt.GridH2QueryContext) JdbcResultSet(org.h2.jdbc.JdbcResultSet)

Aggregations

ResultSet (java.sql.ResultSet)12 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)10 PreparedStatement (java.sql.PreparedStatement)9 Statement (java.sql.Statement)9 ArrayList (java.util.ArrayList)9 IgniteSQLException (org.apache.ignite.internal.processors.query.IgniteSQLException)9 SimpleResultSet (org.h2.tools.SimpleResultSet)9 List (java.util.List)8 Schema (io.s4.schema.Schema)7 Connection (java.sql.Connection)7 SQLException (java.sql.SQLException)7 Property (io.s4.schema.Schema.Property)6 LinkedHashMap (java.util.LinkedHashMap)4 Map (java.util.Map)4 IgniteException (org.apache.ignite.IgniteException)4 IgniteSystemProperties.getString (org.apache.ignite.IgniteSystemProperties.getString)4 GridH2QueryContext (org.apache.ignite.internal.processors.query.h2.opt.GridH2QueryContext)4 GridSqlStatement (org.apache.ignite.internal.processors.query.h2.sql.GridSqlStatement)4 Schema (org.h2.schema.Schema)4 TypeLiteral (com.google.inject.TypeLiteral)3