Java Code Examples for org.apache.ignite.cache.query.SqlFieldsQuery#setLocal()

The following examples show how to use org.apache.ignite.cache.query.SqlFieldsQuery#setLocal() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: IgniteDialect.java    From hibernate-ogm-ignite with GNU Lesser General Public License v2.1 6 votes vote down vote up
private Iterable<List<?>> executeWithHints(IgniteCache<Object, BinaryObject> cache, SqlFieldsQuery sqlQuery, QueryHints hints) {
	Iterable<List<?>> result;

	if ( hints.isLocal() ) {
		if ( !provider.isClientMode() ) {
			sqlQuery.setLocal( true );
		}
	}
	if ( hints.isAffinityRun() ) {
		result = provider.affinityCall( cache.getName(), hints.getAffinityKey(), sqlQuery );
	}
	else {
		result = cache.query( sqlQuery );
	}

	return result;
}
 
Example 2
Source File: IgniteCacheAbstractQuerySelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testLocalSqlFieldsQueryFromClient() throws Exception {
    try (Ignite g = startClientGrid("client")) {
        IgniteCache<UUID, Person> c = jcache(g, UUID.class, Person.class);

        Person p = new Person("Jon", 1500);

        c.put(p.id(), p);

        SqlFieldsQuery qry = new SqlFieldsQuery("select count(*) from Person");

        qry.setLocal(true);

        assertThrowsWithCause(() -> c.query(qry), CacheException.class);
    }
}
 
Example 3
Source File: IgniteH2Indexing.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@SuppressWarnings("deprecation")
@Override public SqlFieldsQuery generateFieldsQuery(String cacheName, SqlQuery qry) {
    String schemaName = schema(cacheName);

    String type = qry.getType();

    H2TableDescriptor tblDesc = schemaMgr.tableForType(schemaName, cacheName, type);

    if (tblDesc == null)
        throw new IgniteSQLException("Failed to find SQL table for type: " + type,
            IgniteQueryErrorCode.TABLE_NOT_FOUND);

    String sql;

    try {
        sql = generateFieldsQueryString(qry.getSql(), qry.getAlias(), tblDesc);
    }
    catch (IgniteCheckedException e) {
        throw new IgniteException(e);
    }

    SqlFieldsQuery res = new SqlFieldsQuery(sql);

    res.setArgs(qry.getArgs());
    res.setDistributedJoins(qry.isDistributedJoins());
    res.setLocal(qry.isLocal());
    res.setPageSize(qry.getPageSize());
    res.setPartitions(qry.getPartitions());
    res.setReplicatedOnly(qry.isReplicatedOnly());
    res.setSchema(schemaName);
    res.setSql(sql);

    if (qry.getTimeout() > 0)
        res.setTimeout(qry.getTimeout(), TimeUnit.MILLISECONDS);

    return res;
}
 
Example 4
Source File: IgniteBinaryObjectQueryArgumentsTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Test simple query by key.
 *
 * @param cacheName Cache name.
 * @param key1 Key 1.
 * @param key2 Key 2.
 * @param <T> Key type.
 */
private <T> void testKeyQuery(final String cacheName, final T key1, final T key2) {
    final IgniteCache<T, Person> cache = ignite(0).cache(cacheName);

    final Person p1 = new Person("p1");
    final Person p2 = new Person("p2");

    cache.put(key1, p1);
    cache.put(key2, p2);

    final SqlQuery<T, Person> qry = new SqlQuery<>(Person.class, "where _key=?");

    final SqlFieldsQuery fieldsQry = new SqlFieldsQuery("select _key, _val, * from Person where _key=?");

    qry.setLocal(isLocal());
    fieldsQry.setLocal(isLocal());

    qry.setArgs(key1);
    fieldsQry.setArgs(key1);

    final List<Cache.Entry<T, Person>> res = cache.query(qry).getAll();
    final List<List<?>> fieldsRes = cache.query(fieldsQry).getAll();

    assertEquals(1, res.size());
    assertEquals(1, fieldsRes.size());

    assertEquals(p1, res.get(0).getValue());
    assertEquals(key1, res.get(0).getKey());

    assertTrue(fieldsRes.get(0).size() >= 2);
    assertEquals(key1, fieldsRes.get(0).get(0));
    assertEquals(p1, fieldsRes.get(0).get(1));
}
 
Example 5
Source File: IgniteBinaryObjectQueryArgumentsTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Test simple query by value.
 *
 * @param cacheName Cache name.
 * @param val1 Value 1.
 * @param val2 Value 2.
 * @param <T> Value type.
 */
private <T> void testValQuery(final String cacheName, final T val1, final T val2) {
    final IgniteCache<Person, T> cache = ignite(0).cache(cacheName);

    final Class<?> valType = val1.getClass();

    final Person p1 = new Person("p1");
    final Person p2 = new Person("p2");

    cache.put(p1, val1);
    cache.put(p2, val2);

    final SqlQuery<Person, T> qry = new SqlQuery<>(valType, "where _val=?");

    final SqlFieldsQuery fieldsQry = new SqlFieldsQuery("select _key, _val, * from " + valType.getSimpleName() + " where _val=?");

    qry.setLocal(isLocal());
    fieldsQry.setLocal(isLocal());

    qry.setArgs(val1);
    fieldsQry.setArgs(val1);

    final List<Cache.Entry<Person, T>> res = cache.query(qry).getAll();
    final List<List<?>> fieldsRes = cache.query(fieldsQry).getAll();

    assertEquals(1, res.size());
    assertEquals(1, fieldsRes.size());

    assertEquals(p1, res.get(0).getKey());
    assertEquals(val1, res.get(0).getValue());

    assertTrue(fieldsRes.get(0).size() >= 2);
    assertEquals(p1, fieldsRes.get(0).get(0));
    assertEquals(val1, fieldsRes.get(0).get(1));
}
 
Example 6
Source File: GridCacheCrossCacheQuerySelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testMultiStatement() throws Exception {
    final IgniteInternalCache<Integer, FactPurchase> cache = ((IgniteKernal)ignite).getCache(PART_CACHE_NAME);

    final GridQueryProcessor qryProc = ((IgniteKernal) ignite).context().query();

    final SqlFieldsQuery qry = new SqlFieldsQuery(
        "insert into FactPurchase(_key, id, productId, storeId, price) values (555, 555, 555, 555, 555);" +
        "select count(*) from FactPurchase"
    );

    GridTestUtils.assertThrows(log,
        new Callable<Object>() {
            @Override public Object call() throws Exception {
                qryProc.querySqlFields(cache.context(), qry, null, false, true);

                return null;
            }
        }, IgniteSQLException.class, "Multiple statements queries are not supported");

    List<FieldsQueryCursor<List<?>>> cursors = qryProc.querySqlFields(cache.context(), qry, null, false, false);

    assertEquals(2, cursors.size());

    for (FieldsQueryCursor<List<?>> cur : cursors)
        U.closeQuiet(cur);

    qry.setLocal(true);

    GridTestUtils.assertThrows(log,
        new Callable<Object>() {
            @Override public Object call() throws Exception {
                qryProc.querySqlFields(cache.context(), qry, null, false, false);

                return null;
            }
        }, IgniteSQLException.class, "Multiple statements queries are not supported for local queries");
}
 
Example 7
Source File: IgniteCacheDistributedPartitionQuerySelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** Tests local query over partitions. */
@Test
public void testLocalQuery() {
    Affinity<Object> affinity = grid(0).affinity("cl");

    int[] parts = affinity.primaryPartitions(grid(0).localNode());

    Arrays.sort(parts);

    IgniteCache<ClientKey, Client> cl = grid(0).cache("cl");

    SqlQuery<ClientKey, Client> qry1 = new SqlQuery<>(Client.class, "1=1");
    qry1.setLocal(true);
    qry1.setPartitions(parts[0]);

    List<Cache.Entry<ClientKey, Client>> clients = cl.query(qry1).getAll();

    for (Cache.Entry<ClientKey, Client> client : clients)
        assertEquals("Incorrect partition", parts[0], affinity.partition(client.getKey()));

    SqlFieldsQuery qry2 = new SqlFieldsQuery("select cl._KEY, cl._VAL from \"cl\".Client cl");
    qry2.setLocal(true);
    qry2.setPartitions(parts[0]);

    List<List<?>> rows = cl.query(qry2).getAll();

    for (List<?> row : rows)
        assertEquals("Incorrect partition", parts[0], affinity.partition(row.get(0)));
}
 
Example 8
Source File: JdbcStatement.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Sets parameters to query object. Logic should be consistent with {@link JdbcQueryTask#call()} and {@link
 * JdbcQueryMultipleStatementsTask#call()}. Parameters are determined from context: connection state and this
 * statement state.
 *
 * @param qry query which parameters to set up
 */
protected void setupQuery(SqlFieldsQuery qry) {
    qry.setPageSize(fetchSize);
    qry.setLocal(conn.nodeId() == null);
    qry.setCollocated(conn.isCollocatedQuery());
    qry.setDistributedJoins(conn.isDistributedJoins());
    qry.setEnforceJoinOrder(conn.isEnforceJoinOrder());
    qry.setLazy(conn.isLazy());
    qry.setSchema(conn.schemaName());
}
 
Example 9
Source File: IgniteDatastoreProvider.java    From hibernate-ogm-ignite with GNU Lesser General Public License v2.1 4 votes vote down vote up
public ComputeForLocalQueries(String cacheName, SqlFieldsQuery query) {
	this.cacheName = cacheName;
	this.query = query.setLocal( true );
}
 
Example 10
Source File: GridMapQueryExecutor.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @param node Node.
 * @param req DML request.
 */
public void onDmlRequest(final ClusterNode node, final GridH2DmlRequest req) {
    int[] parts = req.queryPartitions();

    List<Integer> cacheIds = req.caches();

    long reqId = req.requestId();

    AffinityTopologyVersion topVer = req.topologyVersion();

    PartitionReservation reserved = null;

    MapNodeResults nodeResults = resultsForNode(node.id());

    try {
        reserved = h2.partitionReservationManager().reservePartitions(
            cacheIds,
            topVer,
            parts,
            node.id(),
            reqId
        );

        if (reserved.failed()) {
            U.error(log, "Failed to reserve partitions for DML request. [localNodeId=" + ctx.localNodeId() +
                ", nodeId=" + node.id() + ", reqId=" + req.requestId() + ", cacheIds=" + cacheIds +
                ", topVer=" + topVer + ", parts=" + Arrays.toString(parts) + ']');

            sendUpdateResponse(node, reqId, null,
                "Failed to reserve partitions for DML request. " + reserved.error());

            return;
        }

        IndexingQueryFilter filter = h2.backupFilter(topVer, parts);

        GridQueryCancel cancel = nodeResults.putUpdate(reqId);

        SqlFieldsQuery fldsQry = new SqlFieldsQuery(req.query());

        if (req.parameters() != null)
            fldsQry.setArgs(req.parameters());

        fldsQry.setEnforceJoinOrder(req.isFlagSet(GridH2QueryRequest.FLAG_ENFORCE_JOIN_ORDER));
        fldsQry.setTimeout(req.timeout(), TimeUnit.MILLISECONDS);
        fldsQry.setPageSize(req.pageSize());
        fldsQry.setLocal(true);

        boolean local = true;

        final boolean replicated = req.isFlagSet(GridH2QueryRequest.FLAG_REPLICATED);

        if (!replicated && !F.isEmpty(cacheIds) &&
            CU.firstPartitioned(ctx.cache().context(), cacheIds).config().getQueryParallelism() > 1) {
            fldsQry.setDistributedJoins(true);

            local = false;
        }

        UpdateResult updRes = h2.executeUpdateOnDataNode(req.schemaName(), fldsQry, filter, cancel, local);

        GridCacheContext<?, ?> mainCctx =
            !F.isEmpty(cacheIds) ? ctx.cache().context().cacheContext(cacheIds.get(0)) : null;

        boolean evt = local && mainCctx != null && mainCctx.events().isRecordable(EVT_CACHE_QUERY_EXECUTED);

        if (evt) {
            ctx.event().record(new CacheQueryExecutedEvent<>(
                node,
                "SQL query executed.",
                EVT_CACHE_QUERY_EXECUTED,
                CacheQueryType.SQL.name(),
                mainCctx.name(),
                null,
                req.query(),
                null,
                null,
                req.parameters(),
                node.id(),
                null));
        }

        sendUpdateResponse(node, reqId, updRes, null);
    }
    catch (Exception e) {
        U.error(log, "Error processing dml request. [localNodeId=" + ctx.localNodeId() +
            ", nodeId=" + node.id() + ", req=" + req + ']', e);

        sendUpdateResponse(node, reqId, null, e.getMessage());
    }
    finally {
        if (reserved != null)
            reserved.release();

        nodeResults.removeUpdate(reqId);
    }
}
 
Example 11
Source File: H2ResultSetIteratorNullifyOnEndSelfTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * Local SQL Fields check nullification after close
 */
@Test
public void testSqlFieldsQueryLocalClose() {
    SqlFieldsQuery qry = new SqlFieldsQuery(SELECT_MAX_SAL_SQLF);

    qry.setLocal(true);

    QueryCursor<List<?>> qryCurs = cache().query(qry);

    qryCurs.iterator();

    qryCurs.close();

    H2ResultSetIterator h2It = extractGridIteratorInnerH2ResultSetIterator(qryCurs);

    checkIterator(h2It);
}
 
Example 12
Source File: IgniteCacheLocalQuerySelfTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Test
@Override public void testLocalSqlFieldsQueryFromClient() throws Exception {
    try (Ignite g = startClientGrid("client")) {
        IgniteCache<UUID, Person> c = jcache(g, UUID.class, Person.class);

        Person p = new Person("Jon", 1500);

        c.put(p.id(), p);

        SqlFieldsQuery qry = new SqlFieldsQuery("select * from Person");

        qry.setLocal(true);

        try (FieldsQueryCursor<List<?>> qryCursor = c.query(qry)) {
            assertNotNull(qryCursor);

            List<List<?>> res = qryCursor.getAll();

            assertNotNull(res);

            assertEquals(1, res.size());
        }
    }
}
 
Example 13
Source File: JdbcBatchUpdateTask.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * Performs update.
 *
 * @param cache Cache.
 * @param sqlText SQL text.
 * @param args Parameters.
 * @return Update counter.
 * @throws SQLException If failed.
 */
private Integer doSingleUpdate(IgniteCache<?, ?> cache, String sqlText, List<Object> args) throws SQLException {
    SqlFieldsQuery qry = new SqlFieldsQueryEx(sqlText, false);

    qry.setPageSize(fetchSize);
    qry.setLocal(locQry);
    qry.setCollocated(collocatedQry);
    qry.setDistributedJoins(distributedJoins);
    qry.setSchema(schemaName);
    qry.setArgs(args == null ? null : args.toArray());

    QueryCursorImpl<List<?>> qryCursor = (QueryCursorImpl<List<?>>)cache.withKeepBinary().query(qry);

    if (qryCursor.isQuery()) {
        throw createJdbcSqlException(getError("Query produced result set", qry),
            IgniteQueryErrorCode.STMT_TYPE_MISMATCH);
    }

    List<List<?>> rows = qryCursor.getAll();

    if (F.isEmpty(rows))
        return SUCCESS_NO_INFO;

    if (rows.size() != 1)
        throw new SQLException(getError("Expected single row for update operation result", qry));

    List<?> row = rows.get(0);

    if (F.isEmpty(row) || row.size() != 1)
        throw new SQLException(getError("Expected row size of 1 for update operation", qry));

    Object objRes = row.get(0);

    if (!(objRes instanceof Long))
        throw new SQLException(getError("Unexpected update result type", qry));

    Long longRes = (Long)objRes;

    if (longRes > Integer.MAX_VALUE) {
        IgniteLogger log = ignite.log();

        if (log != null)
            log.warning(getError("Query updated row counter (" + longRes + ") exceeds integer range", qry));

        return Integer.MAX_VALUE;
    }

    return longRes.intValue();
}
 
Example 14
Source File: H2ResultSetIteratorNullifyOnEndSelfTest.java    From ignite with Apache License 2.0 3 votes vote down vote up
/**
 * Local SQL Fields check nullification after complete
 */
@Test
public void testSqlFieldsQueryLocalComplete() {
    SqlFieldsQuery qry = new SqlFieldsQuery(SELECT_MAX_SAL_SQLF);

    qry.setLocal(true);

    QueryCursor<List<?>> qryCurs = cache().query(qry);

    qryCurs.getAll();

    H2ResultSetIterator h2It = extractGridIteratorInnerH2ResultSetIterator(qryCurs);

    checkIterator(h2It);
}
 
Example 15
Source File: CacheSqlQueryValueCopySelfTest.java    From ignite with Apache License 2.0 3 votes vote down vote up
/**
 * Test collecting info about running.
 *
 * @throws Exception If failed.
 */
@Test
public void testRunningSqlFieldsQuery() throws Exception {
    IgniteInternalFuture<?> fut = runQueryAsync(new SqlFieldsQuery("select _val, sleep(1000) from Value limit 3"));

    Thread.sleep(500);

    GridQueryProcessor qryProc = grid(0).context().query();

    Collection<GridRunningQueryInfo> queries = qryProc.runningQueries(0);

    assertEquals(1, queries.size());

    fut.get();

    queries = qryProc.runningQueries(0);

    assertEquals(0, queries.size());

    SqlFieldsQuery qry = new SqlFieldsQuery("select _val, sleep(1000) from Value limit 3");
    qry.setLocal(true);

    fut = runQueryAsync(qry);

    Thread.sleep(500);

    queries = qryProc.runningQueries(0);

    assertEquals(1, queries.size());

    fut.get();

    queries = qryProc.runningQueries(0);

    assertEquals(0, queries.size());
}