zstan commented on code in PR #13366:
URL: https://github.com/apache/ignite/pull/13366#discussion_r3710839840
##########
modules/calcite/src/main/codegen/includes/parserImpls.ftl:
##########
@@ -816,3 +816,66 @@ SqlDrop SqlDropView(Span s, boolean replace) :
return SqlDdlNodes.dropView(s.end(this), ifExists, id);
}
}
+
+/**
+ * Parses a query optionally followed by FOR UPDATE [OF col [, col ...]] [WAIT
n | NOWAIT].
+ *
+ * When FOR UPDATE is absent the inner query node is returned unchanged, so
this rule
+ * transparently handles all queries that reach the StatementParser.
+ */
+SqlNode SqlSelectForUpdate() :
+{
+ final Span s;
+ SqlNode qry;
+ SqlNodeList ofList = null;
+ List<SqlNode> ofCols = null;
+ SqlIdentifier col;
+ Long waitSeconds = null;
+ String waitValue;
+}
+{
+ qry = OrderedQueryOrExpr(ExprContext.ACCEPT_QUERY) { s = span(); }
+ [
+ LOOKAHEAD(<FOR> <UPDATE>)
+ <FOR> <UPDATE>
+ [
+ LOOKAHEAD(<OF>)
+ <OF>
+ {
+ ofCols = new ArrayList<SqlNode>();
+ }
+ col = CompoundIdentifier() { ofCols.add(col); }
+ (
+ <COMMA> col = CompoundIdentifier() { ofCols.add(col); }
+ )*
+ { ofList = new SqlNodeList(ofCols, s.pos()); }
+ ]
+ [
+ LOOKAHEAD(<WAIT>)
+ <WAIT> <UNSIGNED_INTEGER_LITERAL>
+ {
+ waitValue = token.image;
+
+ try {
+ waitSeconds = Long.parseLong(waitValue);
+ }
Review Comment:
```suggestion
SqlIdentifier col;
Long waitSeconds = null;
}
{
qry = OrderedQueryOrExpr(ExprContext.ACCEPT_QUERY) { s = span(); }
[
LOOKAHEAD(<FOR> <UPDATE>)
<FOR> <UPDATE>
[
LOOKAHEAD(<OF>)
<OF>
{
List<SqlNode> columns = new ArrayList<SqlNode>();
}
col = CompoundIdentifier() { columns.add(col); }
(
<COMMA> col = CompoundIdentifier() { columns.add(col); }
)*
{ ofList = new SqlNodeList(columns, s.pos()); }
]
[
LOOKAHEAD(<WAIT>)
<WAIT> <UNSIGNED_INTEGER_LITERAL>
{
String waitValue = token.image;
try {
waitSeconds = Long.parseLong(waitValue);
}
```
##########
modules/calcite/src/main/codegen/includes/parserImpls.ftl:
##########
@@ -816,3 +816,66 @@ SqlDrop SqlDropView(Span s, boolean replace) :
return SqlDdlNodes.dropView(s.end(this), ifExists, id);
}
}
+
+/**
+ * Parses a query optionally followed by FOR UPDATE [OF col [, col ...]] [WAIT
n | NOWAIT].
+ *
+ * When FOR UPDATE is absent the inner query node is returned unchanged, so
this rule
+ * transparently handles all queries that reach the StatementParser.
+ */
+SqlNode SqlSelectForUpdate() :
+{
+ final Span s;
+ SqlNode qry;
+ SqlNodeList ofList = null;
Review Comment:
rename it plz
##########
modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/ExecutionServiceImpl.java:
##########
@@ -581,6 +598,228 @@ private FieldsQueryCursor<List<?>>
executeDdl(RootQuery<Row> qry, DdlPlan plan)
}
}
+ /**
+ * Executes a {@code SELECT ... FOR UPDATE} plan.
+ *
+ * <ol>
+ * <li>Validates that the current transaction is PESSIMISTIC.</li>
+ * <li>Runs the inner SELECT with hidden key, value, and version columns
and materialises all rows.</li>
+ * <li>Builds cache entries from the hidden columns.</li>
+ * <li>Creates a savepoint, acquires pessimistic locks via {@code
lockTxEntries()},
+ * and releases the savepoint on success (or rolls back on
failure).</li>
+ * <li>Repeats the SELECT and lock attempt after a concurrent version
change while the deadline permits.</li>
+ * <li>Returns a cursor with only the user-visible columns (the appended
_KEY is stripped).</li>
+ * </ol>
+ */
+ private FieldsQueryCursor<List<?>> executeForUpdate(RootQuery<Row> qry,
SelectForUpdatePlan plan) {
+ GridNearTxLocal userTx = Commons.queryTransaction(qry.context(),
ctx.cache().context());
+
+ if (userTx == null || !userTx.pessimistic())
+ throw new IgniteSQLException(
+
IgniteResource.INSTANCE.selectForUpdateRequiresPessimisticTx().str(),
+ IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
+
+ // waitSeconds: null = use tx remaining time (0), 0 = NOWAIT (-1),
positive = ms.
+ Long waitSeconds = plan.waitSeconds();
+ long waitMs;
+
+ if (waitSeconds == null)
+ waitMs = 0L;
+ else if (waitSeconds == 0L)
+ waitMs = -1L;
+ else
+ waitMs = waitSeconds * 1000L;
+
+ // Zero means that retries are limited only by the transaction or
query timeout.
+ long deadline = waitMs > 0
Review Comment:
```suggestion
long attemptsTimeout = waitMs > 0
```
##########
modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/ExecutionServiceImpl.java:
##########
@@ -581,6 +598,228 @@ private FieldsQueryCursor<List<?>>
executeDdl(RootQuery<Row> qry, DdlPlan plan)
}
}
+ /**
+ * Executes a {@code SELECT ... FOR UPDATE} plan.
+ *
+ * <ol>
+ * <li>Validates that the current transaction is PESSIMISTIC.</li>
+ * <li>Runs the inner SELECT with hidden key, value, and version columns
and materialises all rows.</li>
+ * <li>Builds cache entries from the hidden columns.</li>
+ * <li>Creates a savepoint, acquires pessimistic locks via {@code
lockTxEntries()},
+ * and releases the savepoint on success (or rolls back on
failure).</li>
+ * <li>Repeats the SELECT and lock attempt after a concurrent version
change while the deadline permits.</li>
+ * <li>Returns a cursor with only the user-visible columns (the appended
_KEY is stripped).</li>
+ * </ol>
+ */
+ private FieldsQueryCursor<List<?>> executeForUpdate(RootQuery<Row> qry,
SelectForUpdatePlan plan) {
+ GridNearTxLocal userTx = Commons.queryTransaction(qry.context(),
ctx.cache().context());
+
+ if (userTx == null || !userTx.pessimistic())
+ throw new IgniteSQLException(
+
IgniteResource.INSTANCE.selectForUpdateRequiresPessimisticTx().str(),
+ IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
+
+ // waitSeconds: null = use tx remaining time (0), 0 = NOWAIT (-1),
positive = ms.
Review Comment:
(0) and (-1) in braces are confused, what is the purpose of such a comment ?
plz extend it or remove
##########
modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/ExecutionServiceImpl.java:
##########
@@ -581,6 +598,228 @@ private FieldsQueryCursor<List<?>>
executeDdl(RootQuery<Row> qry, DdlPlan plan)
}
}
+ /**
+ * Executes a {@code SELECT ... FOR UPDATE} plan.
+ *
+ * <ol>
+ * <li>Validates that the current transaction is PESSIMISTIC.</li>
+ * <li>Runs the inner SELECT with hidden key, value, and version columns
and materialises all rows.</li>
+ * <li>Builds cache entries from the hidden columns.</li>
+ * <li>Creates a savepoint, acquires pessimistic locks via {@code
lockTxEntries()},
+ * and releases the savepoint on success (or rolls back on
failure).</li>
+ * <li>Repeats the SELECT and lock attempt after a concurrent version
change while the deadline permits.</li>
+ * <li>Returns a cursor with only the user-visible columns (the appended
_KEY is stripped).</li>
+ * </ol>
+ */
+ private FieldsQueryCursor<List<?>> executeForUpdate(RootQuery<Row> qry,
SelectForUpdatePlan plan) {
+ GridNearTxLocal userTx = Commons.queryTransaction(qry.context(),
ctx.cache().context());
+
+ if (userTx == null || !userTx.pessimistic())
+ throw new IgniteSQLException(
+
IgniteResource.INSTANCE.selectForUpdateRequiresPessimisticTx().str(),
Review Comment:
seems we need to align this 'strange' as for me message with :
```
org.apache.ignite.internal.processors.cache.GridCacheAdapter#lockTxEntriesAsync
->
new IgniteCheckedException("Failed to acquire transactional lock in
optimistic transaction."));
```
or ignore this check here and it will be raized a bit later, need to make
sure that SqlException will be raized.
##########
modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/ExecutionServiceImpl.java:
##########
@@ -581,6 +598,228 @@ private FieldsQueryCursor<List<?>>
executeDdl(RootQuery<Row> qry, DdlPlan plan)
}
}
+ /**
+ * Executes a {@code SELECT ... FOR UPDATE} plan.
+ *
+ * <ol>
+ * <li>Validates that the current transaction is PESSIMISTIC.</li>
+ * <li>Runs the inner SELECT with hidden key, value, and version columns
and materialises all rows.</li>
+ * <li>Builds cache entries from the hidden columns.</li>
+ * <li>Creates a savepoint, acquires pessimistic locks via {@code
lockTxEntries()},
+ * and releases the savepoint on success (or rolls back on
failure).</li>
+ * <li>Repeats the SELECT and lock attempt after a concurrent version
change while the deadline permits.</li>
+ * <li>Returns a cursor with only the user-visible columns (the appended
_KEY is stripped).</li>
+ * </ol>
+ */
+ private FieldsQueryCursor<List<?>> executeForUpdate(RootQuery<Row> qry,
SelectForUpdatePlan plan) {
+ GridNearTxLocal userTx = Commons.queryTransaction(qry.context(),
ctx.cache().context());
+
+ if (userTx == null || !userTx.pessimistic())
+ throw new IgniteSQLException(
+
IgniteResource.INSTANCE.selectForUpdateRequiresPessimisticTx().str(),
+ IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
+
+ // waitSeconds: null = use tx remaining time (0), 0 = NOWAIT (-1),
positive = ms.
+ Long waitSeconds = plan.waitSeconds();
+ long waitMs;
+
+ if (waitSeconds == null)
Review Comment:
what change between NOWAIT and without *WAIT definition ? I suppose that
'pure' = without WAIT syntax will waits indefinitely until the blocking
transaction finishes or i miss smth or this is not true for current
implmentation. Also it hard to read now all these : if - esle if branches.
tryExecuteForUpdate - can operate only with one 'waitMs' param for example.
##########
modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/ExecutionServiceImpl.java:
##########
@@ -581,6 +598,228 @@ private FieldsQueryCursor<List<?>>
executeDdl(RootQuery<Row> qry, DdlPlan plan)
}
}
+ /**
+ * Executes a {@code SELECT ... FOR UPDATE} plan.
+ *
+ * <ol>
+ * <li>Validates that the current transaction is PESSIMISTIC.</li>
+ * <li>Runs the inner SELECT with hidden key, value, and version columns
and materialises all rows.</li>
+ * <li>Builds cache entries from the hidden columns.</li>
+ * <li>Creates a savepoint, acquires pessimistic locks via {@code
lockTxEntries()},
+ * and releases the savepoint on success (or rolls back on
failure).</li>
+ * <li>Repeats the SELECT and lock attempt after a concurrent version
change while the deadline permits.</li>
+ * <li>Returns a cursor with only the user-visible columns (the appended
_KEY is stripped).</li>
+ * </ol>
+ */
+ private FieldsQueryCursor<List<?>> executeForUpdate(RootQuery<Row> qry,
SelectForUpdatePlan plan) {
+ GridNearTxLocal userTx = Commons.queryTransaction(qry.context(),
ctx.cache().context());
+
+ if (userTx == null || !userTx.pessimistic())
+ throw new IgniteSQLException(
+
IgniteResource.INSTANCE.selectForUpdateRequiresPessimisticTx().str(),
+ IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
+
+ // waitSeconds: null = use tx remaining time (0), 0 = NOWAIT (-1),
positive = ms.
+ Long waitSeconds = plan.waitSeconds();
+ long waitMs;
+
+ if (waitSeconds == null)
+ waitMs = 0L;
+ else if (waitSeconds == 0L)
+ waitMs = -1L;
+ else
+ waitMs = waitSeconds * 1000L;
+
+ // Zero means that retries are limited only by the transaction or
query timeout.
+ long deadline = waitMs > 0
+ ? U.currentTimeMillis() + waitMs
+ : waitMs < 0 ? U.currentTimeMillis() : 0L;
+
+ RootQuery<Row> selectQry = qry;
+
+ while (true) {
+ FieldsQueryCursor<List<?>> cursor = tryExecuteForUpdate(selectQry,
plan, userTx, waitMs, deadline);
+
+ if (cursor != null)
+ return cursor;
+
+ if (deadline != 0 && U.currentTimeMillis() >= deadline) {
+ throw new IgniteSQLException(
+ IgniteResource.INSTANCE.selectForUpdateLockFailed().str(),
+ IgniteQueryErrorCode.CONCURRENT_UPDATE);
+ }
+
+ // The previous query has already been closed after
materialisation, so retry with a fresh root query.
+ selectQry = qry.retryQuery();
+ qryReg.register(selectQry);
+ }
+ }
+
+ /**
+ * Executes the inner SELECT once and tries to lock the selected row
versions.
+ *
+ * @return Result cursor when locking succeeds, or {@code null} when the
SELECT must be executed again.
+ */
+ @Nullable private FieldsQueryCursor<List<?>> tryExecuteForUpdate(
+ RootQuery<Row> qry,
+ SelectForUpdatePlan plan,
+ GridNearTxLocal userTx,
+ long waitMs,
+ long deadline
+ ) {
+ // Run the inner SELECT (with _KEY, _VAL, _VER appended) and collect
all rows.
+ ListFieldsQueryCursor<?> innerCursor = mapAndExecutePlan(qry,
plan.innerPlan());
+ List<List<?>> rows = innerCursor.getAll();
+
+ int userColCnt = plan.userColumnCount();
+
+ if (rows.isEmpty()) {
+ // Nothing to lock – return an empty cursor with user-only field
metadata.
+ QueryCursorImpl<List<?>> resCur = new
QueryCursorImpl<>(Collections.emptyList(), null, false);
+
+ IgniteTypeFactory typeFactory = qry.context().typeFactory();
+ List<GridQueryFieldMetadata> meta =
plan.innerPlan().fieldsMetadata().queryFieldsMetadata(typeFactory);
+
+ resCur.fieldsMeta(meta.subList(0, userColCnt));
+
+ return resCur;
+ }
+
+ Map<IgniteInternalCache<Object, Object>, Map<Object,
CacheEntry<Object, Object>>> entriesByCache =
+ new LinkedHashMap<>();
+
+ for (LockTarget target : plan.lockTargets()) {
+ SchemaPlus schemaPlus = schemaHolder.schema(target.schemaName());
+
+ if (schemaPlus == null)
+ throw new IgniteSQLException("Schema not found: " +
target.schemaName(),
+ IgniteQueryErrorCode.SCHEMA_NOT_FOUND);
+
+ IgniteTable igniteTable =
(IgniteTable)schemaPlus.getTable(target.tableName());
+
+ if (igniteTable == null)
+ throw new IgniteSQLException("Table not found: " +
target.tableName(),
+ IgniteQueryErrorCode.TABLE_NOT_FOUND);
+
+ GridCacheContext<Object, Object> cctx =
+ (GridCacheContext<Object,
Object>)((CacheTableDescriptor)igniteTable.descriptor()).cacheContext();
+
+ IgniteInternalCache<Object, Object> cache =
cctx.cache().keepBinary();
+ Map<Object, CacheEntry<Object, Object>> entries =
+ entriesByCache.computeIfAbsent(cache, key -> new
LinkedHashMap<>());
+ int keyColumnIdx = target.keyColumnIndex();
+
+ for (List<?> row : rows) {
+ Object key = row.get(keyColumnIdx);
+
+ // An outer join has no row to lock on its non-matching side.
+ if (key == null)
+ continue;
+
+ Object val = row.get(keyColumnIdx + 1);
+ GridCacheVersion ver = (GridCacheVersion)row.get(keyColumnIdx
+ 2);
+
+ // JOINs can repeat a row, but a transaction needs only one
lock per cache key.
+ entries.put(key, new CacheEntryImplEx<>(key, val, ver));
+ }
+ }
+
+ List<Map.Entry<IgniteInternalCache<Object, Object>, Map<Object,
CacheEntry<Object, Object>>>> lockBatches =
+ new ArrayList<>(entriesByCache.entrySet());
+
+ lockBatches.sort(Comparator.comparingInt(left ->
left.getKey().context().cacheId()));
+
+ try {
+ // lockTxEntries() requires the transaction to be bound to the
current thread
+ // (it checks cctx.tm().threadLocalTx()). Resume it here and
suspend afterwards,
+ // following the same pattern as
ModifyNode.invokeInsideTransaction().
+ userTx.resume();
+
+ try {
+ // Create a savepoint so that a failed lock attempt can be
rolled back without aborting the whole tx.
+ String spName = "_for_update_" + UUID.randomUUID();
+
+ userTx.savepoint(spName, false);
+
+ boolean locked = true;
+
+ try {
+ for (Map.Entry<IgniteInternalCache<Object, Object>,
Map<Object, CacheEntry<Object, Object>>> batch :
+ lockBatches) {
+ if (batch.getValue().isEmpty())
+ continue;
+
+ long batchWaitMs = waitMs;
+
+ if (deadline > 0) {
+ batchWaitMs = deadline - U.currentTimeMillis();
+
+ if (batchWaitMs <= 0)
+ batchWaitMs = -1L;
Review Comment:
```suggestion
if (batchWaitMs == 0)
batchWaitMs = -1L;
```
also can you clarify why we need such a code ? I see this check :
CU.isWaitTimeoutExpiresFirst
but why it not work for '0' param ?
##########
modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/IgnitePlanner.java:
##########
@@ -423,6 +423,15 @@ public String dump() {
return w.toString();
}
+ /** Returns whether the SELECT changes row cardinality using aggregation.
*/
+ @SuppressWarnings("deprecation")
+ public boolean isAggregate(SqlSelect select) {
+ SqlValidator validator = validator();
+
+ return validator.isAggregate(select)
+ || (select.getOrderList() != null &&
validator.isAggregate(select.getOrderList()));
Review Comment:
let\`s avoid to use deprecations, also this branch i.e.:
`|| (select.getOrderList() != null &&
validator.isAggregate(select.getOrderList()))`
is not covered be tests ot i\`m wrong ?
##########
modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/ExecutionServiceImpl.java:
##########
@@ -581,6 +598,228 @@ private FieldsQueryCursor<List<?>>
executeDdl(RootQuery<Row> qry, DdlPlan plan)
}
}
+ /**
+ * Executes a {@code SELECT ... FOR UPDATE} plan.
+ *
+ * <ol>
+ * <li>Validates that the current transaction is PESSIMISTIC.</li>
+ * <li>Runs the inner SELECT with hidden key, value, and version columns
and materialises all rows.</li>
+ * <li>Builds cache entries from the hidden columns.</li>
+ * <li>Creates a savepoint, acquires pessimistic locks via {@code
lockTxEntries()},
+ * and releases the savepoint on success (or rolls back on
failure).</li>
+ * <li>Repeats the SELECT and lock attempt after a concurrent version
change while the deadline permits.</li>
+ * <li>Returns a cursor with only the user-visible columns (the appended
_KEY is stripped).</li>
+ * </ol>
+ */
+ private FieldsQueryCursor<List<?>> executeForUpdate(RootQuery<Row> qry,
SelectForUpdatePlan plan) {
+ GridNearTxLocal userTx = Commons.queryTransaction(qry.context(),
ctx.cache().context());
+
+ if (userTx == null || !userTx.pessimistic())
+ throw new IgniteSQLException(
+
IgniteResource.INSTANCE.selectForUpdateRequiresPessimisticTx().str(),
+ IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
+
+ // waitSeconds: null = use tx remaining time (0), 0 = NOWAIT (-1),
positive = ms.
+ Long waitSeconds = plan.waitSeconds();
+ long waitMs;
+
+ if (waitSeconds == null)
+ waitMs = 0L;
+ else if (waitSeconds == 0L)
+ waitMs = -1L;
+ else
+ waitMs = waitSeconds * 1000L;
+
+ // Zero means that retries are limited only by the transaction or
query timeout.
+ long deadline = waitMs > 0
+ ? U.currentTimeMillis() + waitMs
+ : waitMs < 0 ? U.currentTimeMillis() : 0L;
+
+ RootQuery<Row> selectQry = qry;
+
+ while (true) {
+ FieldsQueryCursor<List<?>> cursor = tryExecuteForUpdate(selectQry,
plan, userTx, waitMs, deadline);
+
+ if (cursor != null)
+ return cursor;
+
+ if (deadline != 0 && U.currentTimeMillis() >= deadline) {
+ throw new IgniteSQLException(
+ IgniteResource.INSTANCE.selectForUpdateLockFailed().str(),
+ IgniteQueryErrorCode.CONCURRENT_UPDATE);
+ }
+
+ // The previous query has already been closed after
materialisation, so retry with a fresh root query.
+ selectQry = qry.retryQuery();
+ qryReg.register(selectQry);
+ }
+ }
+
+ /**
+ * Executes the inner SELECT once and tries to lock the selected row
versions.
+ *
+ * @return Result cursor when locking succeeds, or {@code null} when the
SELECT must be executed again.
+ */
+ @Nullable private FieldsQueryCursor<List<?>> tryExecuteForUpdate(
+ RootQuery<Row> qry,
+ SelectForUpdatePlan plan,
+ GridNearTxLocal userTx,
+ long waitMs,
+ long deadline
+ ) {
+ // Run the inner SELECT (with _KEY, _VAL, _VER appended) and collect
all rows.
+ ListFieldsQueryCursor<?> innerCursor = mapAndExecutePlan(qry,
plan.innerPlan());
+ List<List<?>> rows = innerCursor.getAll();
+
+ int userColCnt = plan.userColumnCount();
+
+ if (rows.isEmpty()) {
+ // Nothing to lock – return an empty cursor with user-only field
metadata.
+ QueryCursorImpl<List<?>> resCur = new
QueryCursorImpl<>(Collections.emptyList(), null, false);
+
+ IgniteTypeFactory typeFactory = qry.context().typeFactory();
+ List<GridQueryFieldMetadata> meta =
plan.innerPlan().fieldsMetadata().queryFieldsMetadata(typeFactory);
+
+ resCur.fieldsMeta(meta.subList(0, userColCnt));
+
+ return resCur;
+ }
+
+ Map<IgniteInternalCache<Object, Object>, Map<Object,
CacheEntry<Object, Object>>> entriesByCache =
+ new LinkedHashMap<>();
+
+ for (LockTarget target : plan.lockTargets()) {
+ SchemaPlus schemaPlus = schemaHolder.schema(target.schemaName());
+
+ if (schemaPlus == null)
+ throw new IgniteSQLException("Schema not found: " +
target.schemaName(),
+ IgniteQueryErrorCode.SCHEMA_NOT_FOUND);
+
+ IgniteTable igniteTable =
(IgniteTable)schemaPlus.getTable(target.tableName());
+
+ if (igniteTable == null)
Review Comment:
is it sys view case ? if so - it need to be handled more informative i
suppose
##########
modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/integration/SelectForUpdateIntegrationTest.java:
##########
@@ -0,0 +1,611 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.query.calcite.integration;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.UUID;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import org.apache.ignite.Ignite;
+import org.apache.ignite.cache.query.SqlFieldsQuery;
+import org.apache.ignite.calcite.CalciteQueryEngineConfiguration;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.configuration.SqlConfiguration;
+import org.apache.ignite.configuration.TransactionConfiguration;
+import org.apache.ignite.internal.IgniteEx;
+import org.apache.ignite.internal.IgniteInternalFuture;
+import org.apache.ignite.internal.TestRecordingCommunicationSpi;
+import org.apache.ignite.internal.processors.query.IgniteSQLException;
+import
org.apache.ignite.internal.processors.query.calcite.message.QueryBatchMessage;
+import org.apache.ignite.testframework.GridTestUtils;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+import org.apache.ignite.transactions.Transaction;
+import org.junit.Test;
+
+import static org.apache.ignite.transactions.TransactionConcurrency.OPTIMISTIC;
+import static
org.apache.ignite.transactions.TransactionConcurrency.PESSIMISTIC;
+import static
org.apache.ignite.transactions.TransactionIsolation.READ_COMMITTED;
+import static org.apache.ignite.transactions.TransactionState.ACTIVE;
+
+/**
+ * Integration tests for {@code SELECT ... FOR UPDATE} syntax.
+ */
+public class SelectForUpdateIntegrationTest extends GridCommonAbstractTest {
Review Comment:
1. sys view tests are absent
2. virtual tables are absent table(system_range(1, 4)
3. non PK involved tests are bsent, or i miss ?
##########
modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/integration/SelectForUpdateIntegrationTest.java:
##########
@@ -0,0 +1,611 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.query.calcite.integration;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.UUID;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import org.apache.ignite.Ignite;
+import org.apache.ignite.cache.query.SqlFieldsQuery;
+import org.apache.ignite.calcite.CalciteQueryEngineConfiguration;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.configuration.SqlConfiguration;
+import org.apache.ignite.configuration.TransactionConfiguration;
+import org.apache.ignite.internal.IgniteEx;
+import org.apache.ignite.internal.IgniteInternalFuture;
+import org.apache.ignite.internal.TestRecordingCommunicationSpi;
+import org.apache.ignite.internal.processors.query.IgniteSQLException;
+import
org.apache.ignite.internal.processors.query.calcite.message.QueryBatchMessage;
+import org.apache.ignite.testframework.GridTestUtils;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+import org.apache.ignite.transactions.Transaction;
+import org.junit.Test;
+
+import static org.apache.ignite.transactions.TransactionConcurrency.OPTIMISTIC;
+import static
org.apache.ignite.transactions.TransactionConcurrency.PESSIMISTIC;
+import static
org.apache.ignite.transactions.TransactionIsolation.READ_COMMITTED;
+import static org.apache.ignite.transactions.TransactionState.ACTIVE;
+
+/**
+ * Integration tests for {@code SELECT ... FOR UPDATE} syntax.
+ */
+public class SelectForUpdateIntegrationTest extends GridCommonAbstractTest {
+ /** */
+ private static Ignite ignite0;
+
+ /** */
+ private static Ignite ignite1;
+
+ /** */
+ private static Ignite client;
+
+ /** {@inheritDoc} */
+ @Override protected IgniteConfiguration getConfiguration(String
igniteInstanceName) throws Exception {
+ return super.getConfiguration(igniteInstanceName)
+ .setTransactionConfiguration(new TransactionConfiguration()
+ .setTxAwareQueriesEnabled(true))
+ .setSqlConfiguration(new SqlConfiguration()
+ .setQueryEnginesConfiguration(new
CalciteQueryEngineConfiguration()
+ .setDefault(true)))
+ .setCommunicationSpi(new TestRecordingCommunicationSpi());
+ }
+
+ /** {@inheritDoc} */
+ @Override protected void beforeTestsStarted() throws Exception {
+ super.beforeTestsStarted();
+
+ ignite0 = startGridsMultiThreaded(3);
+ ignite1 = grid(1);
+ client = startClientGrid();
+
+ awaitPartitionMapExchange();
+ }
+
+ /** {@inheritDoc} */
+ @Override protected void afterTestsStopped() throws Exception {
+ stopAllGrids();
+
+ ignite0 = null;
+ ignite1 = null;
+ client = null;
+
+ super.afterTestsStopped();
+ }
+
+ /** {@inheritDoc} */
+ @Override protected void beforeTest() throws Exception {
+ super.beforeTest();
+
+ sql("CREATE TABLE Person (id INT PRIMARY KEY, name VARCHAR, age INT,
deptId INT, managerId INT) " +
+ "WITH atomicity=TRANSACTIONAL");
+ sql("INSERT INTO Person (id, name, age) VALUES " +
+ "(1, 'Alice', 20), (2, 'Bob', 21), (3, 'Ann', 22), (4, 'Bill',
23)" +
+ ", (5, 'Alex', 24), (6, 'Ben', 25), (7, 'Cathy', 26), (8, 'Carl',
27), (9, 'Diana', 28)" +
+ ", (10, 'David', 29), (11, 'Eva', 30), (12, 'Evan', 31), (13,
'Fiona', 32), (14, 'Frank', 33)" +
+ ", (15, 'Grace', 34), (16, 'George', 35), (17, 'Hannah', 36), (18,
'Harry', 37), (19, 'Ivy', 38)" +
+ ", (20, 'Ian', 39), (21, 'Jack', 40), (22, 'Jill', 41), (23,
'Karen', 42), (24, 'Kyle', 43)" +
+ ", (25, 'Laura', 44), (26, 'Leo', 45), (27, 'Mia', 46), (28,
'Mike', 47), (29, 'Nina', 48)" +
+ ", (30, 'Nick', 49)");
+ sql("UPDATE Person SET deptId = 1, managerId = 2 WHERE id = 1");
+ }
+
+ /** {@inheritDoc} */
+ @Override protected void afterTest() throws Exception {
+ sql("DROP TABLE IF EXISTS Dept");
+ sql("DROP TABLE IF EXISTS Person");
+
+ super.afterTest();
+ }
+
+ /** SELECT FOR UPDATE without OF locks rows of every table participating
in a JOIN. */
+ @Test
+ public void testSelectForUpdateJoinLocksAllTables() throws Exception {
+ createDeptTable();
+
+ CountDownLatch locked = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+
+ IgniteInternalFuture<?> lockFut = GridTestUtils.runAsync(() -> {
+ try (Transaction tx = ignite0.transactions().txStart(PESSIMISTIC,
READ_COMMITTED)) {
+ assertRows(
+ sql("SELECT p.id FROM Person p JOIN Dept d ON p.deptId =
d.id WHERE p.id = 1 FOR UPDATE"),
+ Arrays.asList(1)
+ );
+
+ locked.countDown();
+
+ assertTrue("Timed out waiting to release JOIN locks",
release.await(30, TimeUnit.SECONDS));
+
+ tx.commit();
+ }
+ });
+
+ try {
+ assertTrue("JOIN transaction did not acquire locks in time",
locked.await(10, TimeUnit.SECONDS));
+
+ assertTableRowLocked(ignite1, "Person", 1);
+ assertTableRowLocked(ignite1, "Dept", 1);
+ }
+ finally {
+ release.countDown();
+ }
+
+ lockFut.get(10_000);
+ }
+
+ /** FOR UPDATE OF locks only the table owning the specified JOIN column. */
+ @Test
+ public void testSelectForUpdateJoinOfLocksSelectedTable() throws Exception
{
+ createDeptTable();
+
+ CountDownLatch locked = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+
+ IgniteInternalFuture<?> lockFut = GridTestUtils.runAsync(() -> {
+ try (Transaction tx = ignite0.transactions().txStart(PESSIMISTIC,
READ_COMMITTED)) {
+ assertRows(
+ sql("SELECT p.id FROM Person p JOIN Dept d ON p.deptId =
d.id WHERE p.id = 1 FOR UPDATE OF p.id"),
+ Arrays.asList(1)
+ );
+
+ locked.countDown();
+
+ assertTrue("Timed out waiting to release JOIN locks",
release.await(30, TimeUnit.SECONDS));
+
+ tx.commit();
+ }
+ });
+
+ try {
+ assertTrue("JOIN transaction did not acquire locks in time",
locked.await(10, TimeUnit.SECONDS));
+
+ assertTableRowLocked(ignite1, "Person", 1);
+
+ try (Transaction tx = ignite1.transactions().txStart(PESSIMISTIC,
READ_COMMITTED)) {
+ assertRows(sql(ignite1, "SELECT * FROM Dept WHERE id = 1 FOR
UPDATE NOWAIT"),
+ Arrays.asList(1, "Engineering"));
+
+ tx.commit();
+ }
+ }
+ finally {
+ release.countDown();
+ }
+
+ lockFut.get(10_000);
+ }
+
+ /** A qualified OF column selects a particular table occurrence in a
self-join. */
+ @Test
+ public void testSelectForUpdateSelfJoinOfUsesAlias() throws Exception {
+ assertSelfJoinOfLocks("employee", 1, 2);
+ assertSelfJoinOfLocks("manager", 2, 1);
+ }
+
+ /** Creates a second transactional table used by JOIN tests. */
+ private void createDeptTable() {
+ sql("CREATE TABLE Dept (id INT PRIMARY KEY, name VARCHAR) WITH
atomicity=TRANSACTIONAL");
+ sql("INSERT INTO Dept VALUES (1, 'Engineering'), (2, 'Sales'), (3,
'HR')");
+ }
+
+ /** Verifies that OF resolves an alias to the correct side of a self-join.
*/
+ private void assertSelfJoinOfLocks(String alias, int lockedId, int
unlockedId) throws Exception {
+ CountDownLatch locked = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+
+ IgniteInternalFuture<?> lockFut = GridTestUtils.runAsync(() -> {
+ try (Transaction tx = ignite0.transactions().txStart(PESSIMISTIC,
READ_COMMITTED)) {
+ assertRows(sql("SELECT employee.id, manager.id FROM Person
employee " +
+ "JOIN Person manager ON employee.managerId = manager.id " +
+ "WHERE employee.id = 1 FOR UPDATE OF " + alias + ".id"),
Arrays.asList(1, 2));
+
+ locked.countDown();
+
+ assertTrue("Timed out waiting to release self-join lock",
release.await(30, TimeUnit.SECONDS));
+
+ tx.commit();
+ }
+ });
+
+ try {
+ assertTrue("Self-join transaction did not acquire lock in time",
locked.await(10, TimeUnit.SECONDS));
+
+ assertTableRowLocked(ignite1, "Person", lockedId);
+ assertTableRowUnlocked(ignite1, "Person", unlockedId);
+ }
+ finally {
+ release.countDown();
+ }
+
+ lockFut.get(10_000);
+ }
+
+ /** FOR UPDATE without an active transaction produces "requires an active
PESSIMISTIC transaction". */
+ @Test
+ public void testSelectForUpdateOutsideTransaction() {
+ GridTestUtils.assertThrowsAnyCause(log, () -> sql("SELECT id FROM
Person FOR UPDATE"),
+ IgniteSQLException.class, "SELECT FOR UPDATE requires an active
PESSIMISTIC transaction");
Review Comment:
```suggestion
IgniteSQLException.class,
IgniteResource.INSTANCE.selectForUpdateRequiresPessimisticTx().str());
```
##########
modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/integration/SelectForUpdateIntegrationTest.java:
##########
@@ -0,0 +1,611 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.query.calcite.integration;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.UUID;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import org.apache.ignite.Ignite;
+import org.apache.ignite.cache.query.SqlFieldsQuery;
+import org.apache.ignite.calcite.CalciteQueryEngineConfiguration;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.configuration.SqlConfiguration;
+import org.apache.ignite.configuration.TransactionConfiguration;
+import org.apache.ignite.internal.IgniteEx;
+import org.apache.ignite.internal.IgniteInternalFuture;
+import org.apache.ignite.internal.TestRecordingCommunicationSpi;
+import org.apache.ignite.internal.processors.query.IgniteSQLException;
+import
org.apache.ignite.internal.processors.query.calcite.message.QueryBatchMessage;
+import org.apache.ignite.testframework.GridTestUtils;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+import org.apache.ignite.transactions.Transaction;
+import org.junit.Test;
+
+import static org.apache.ignite.transactions.TransactionConcurrency.OPTIMISTIC;
+import static
org.apache.ignite.transactions.TransactionConcurrency.PESSIMISTIC;
+import static
org.apache.ignite.transactions.TransactionIsolation.READ_COMMITTED;
+import static org.apache.ignite.transactions.TransactionState.ACTIVE;
+
+/**
+ * Integration tests for {@code SELECT ... FOR UPDATE} syntax.
+ */
+public class SelectForUpdateIntegrationTest extends GridCommonAbstractTest {
+ /** */
+ private static Ignite ignite0;
+
+ /** */
+ private static Ignite ignite1;
+
+ /** */
+ private static Ignite client;
+
+ /** {@inheritDoc} */
+ @Override protected IgniteConfiguration getConfiguration(String
igniteInstanceName) throws Exception {
+ return super.getConfiguration(igniteInstanceName)
+ .setTransactionConfiguration(new TransactionConfiguration()
+ .setTxAwareQueriesEnabled(true))
+ .setSqlConfiguration(new SqlConfiguration()
+ .setQueryEnginesConfiguration(new
CalciteQueryEngineConfiguration()
+ .setDefault(true)))
+ .setCommunicationSpi(new TestRecordingCommunicationSpi());
+ }
+
+ /** {@inheritDoc} */
+ @Override protected void beforeTestsStarted() throws Exception {
+ super.beforeTestsStarted();
+
+ ignite0 = startGridsMultiThreaded(3);
+ ignite1 = grid(1);
+ client = startClientGrid();
+
+ awaitPartitionMapExchange();
+ }
+
+ /** {@inheritDoc} */
+ @Override protected void afterTestsStopped() throws Exception {
+ stopAllGrids();
+
+ ignite0 = null;
+ ignite1 = null;
+ client = null;
+
+ super.afterTestsStopped();
+ }
+
+ /** {@inheritDoc} */
+ @Override protected void beforeTest() throws Exception {
+ super.beforeTest();
+
+ sql("CREATE TABLE Person (id INT PRIMARY KEY, name VARCHAR, age INT,
deptId INT, managerId INT) " +
+ "WITH atomicity=TRANSACTIONAL");
+ sql("INSERT INTO Person (id, name, age) VALUES " +
+ "(1, 'Alice', 20), (2, 'Bob', 21), (3, 'Ann', 22), (4, 'Bill',
23)" +
+ ", (5, 'Alex', 24), (6, 'Ben', 25), (7, 'Cathy', 26), (8, 'Carl',
27), (9, 'Diana', 28)" +
+ ", (10, 'David', 29), (11, 'Eva', 30), (12, 'Evan', 31), (13,
'Fiona', 32), (14, 'Frank', 33)" +
+ ", (15, 'Grace', 34), (16, 'George', 35), (17, 'Hannah', 36), (18,
'Harry', 37), (19, 'Ivy', 38)" +
+ ", (20, 'Ian', 39), (21, 'Jack', 40), (22, 'Jill', 41), (23,
'Karen', 42), (24, 'Kyle', 43)" +
+ ", (25, 'Laura', 44), (26, 'Leo', 45), (27, 'Mia', 46), (28,
'Mike', 47), (29, 'Nina', 48)" +
+ ", (30, 'Nick', 49)");
+ sql("UPDATE Person SET deptId = 1, managerId = 2 WHERE id = 1");
+ }
+
+ /** {@inheritDoc} */
+ @Override protected void afterTest() throws Exception {
+ sql("DROP TABLE IF EXISTS Dept");
+ sql("DROP TABLE IF EXISTS Person");
+
+ super.afterTest();
+ }
+
+ /** SELECT FOR UPDATE without OF locks rows of every table participating
in a JOIN. */
+ @Test
+ public void testSelectForUpdateJoinLocksAllTables() throws Exception {
+ createDeptTable();
+
+ CountDownLatch locked = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+
+ IgniteInternalFuture<?> lockFut = GridTestUtils.runAsync(() -> {
+ try (Transaction tx = ignite0.transactions().txStart(PESSIMISTIC,
READ_COMMITTED)) {
+ assertRows(
+ sql("SELECT p.id FROM Person p JOIN Dept d ON p.deptId =
d.id WHERE p.id = 1 FOR UPDATE"),
Review Comment:
why you avoid to inherit from AbstractBasicIntegrationTest ? and use all
infrastructure like :
```
assertQuery("SELECT p.id FROM Person p JOIN Dept d ON
p.deptId = d.id WHERE p.id = 1 FOR UPDATE")
.returns(1)
.check();
```
##########
modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/ExecutionServiceImpl.java:
##########
@@ -581,6 +598,228 @@ private FieldsQueryCursor<List<?>>
executeDdl(RootQuery<Row> qry, DdlPlan plan)
}
}
+ /**
+ * Executes a {@code SELECT ... FOR UPDATE} plan.
+ *
+ * <ol>
+ * <li>Validates that the current transaction is PESSIMISTIC.</li>
+ * <li>Runs the inner SELECT with hidden key, value, and version columns
and materialises all rows.</li>
+ * <li>Builds cache entries from the hidden columns.</li>
+ * <li>Creates a savepoint, acquires pessimistic locks via {@code
lockTxEntries()},
+ * and releases the savepoint on success (or rolls back on
failure).</li>
+ * <li>Repeats the SELECT and lock attempt after a concurrent version
change while the deadline permits.</li>
+ * <li>Returns a cursor with only the user-visible columns (the appended
_KEY is stripped).</li>
+ * </ol>
+ */
+ private FieldsQueryCursor<List<?>> executeForUpdate(RootQuery<Row> qry,
SelectForUpdatePlan plan) {
+ GridNearTxLocal userTx = Commons.queryTransaction(qry.context(),
ctx.cache().context());
+
+ if (userTx == null || !userTx.pessimistic())
+ throw new IgniteSQLException(
+
IgniteResource.INSTANCE.selectForUpdateRequiresPessimisticTx().str(),
+ IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
+
+ // waitSeconds: null = use tx remaining time (0), 0 = NOWAIT (-1),
positive = ms.
+ Long waitSeconds = plan.waitSeconds();
+ long waitMs;
+
+ if (waitSeconds == null)
+ waitMs = 0L;
+ else if (waitSeconds == 0L)
+ waitMs = -1L;
+ else
+ waitMs = waitSeconds * 1000L;
+
+ // Zero means that retries are limited only by the transaction or
query timeout.
+ long deadline = waitMs > 0
+ ? U.currentTimeMillis() + waitMs
+ : waitMs < 0 ? U.currentTimeMillis() : 0L;
+
+ RootQuery<Row> selectQry = qry;
+
+ while (true) {
+ FieldsQueryCursor<List<?>> cursor = tryExecuteForUpdate(selectQry,
plan, userTx, waitMs, deadline);
+
+ if (cursor != null)
+ return cursor;
+
+ if (deadline != 0 && U.currentTimeMillis() >= deadline) {
+ throw new IgniteSQLException(
+ IgniteResource.INSTANCE.selectForUpdateLockFailed().str(),
+ IgniteQueryErrorCode.CONCURRENT_UPDATE);
+ }
+
+ // The previous query has already been closed after
materialisation, so retry with a fresh root query.
+ selectQry = qry.retryQuery();
+ qryReg.register(selectQry);
+ }
+ }
+
+ /**
+ * Executes the inner SELECT once and tries to lock the selected row
versions.
+ *
+ * @return Result cursor when locking succeeds, or {@code null} when the
SELECT must be executed again.
Review Comment:
"when the SELECT must be executed again" - you write implementation approach
but need to be a some kind of contract, isn\`t it ? i.e. smth like :
or {@code null} when locks can\`t be aquired ?
##########
modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/ExecutionServiceImpl.java:
##########
@@ -581,6 +598,228 @@ private FieldsQueryCursor<List<?>>
executeDdl(RootQuery<Row> qry, DdlPlan plan)
}
}
+ /**
+ * Executes a {@code SELECT ... FOR UPDATE} plan.
+ *
+ * <ol>
+ * <li>Validates that the current transaction is PESSIMISTIC.</li>
+ * <li>Runs the inner SELECT with hidden key, value, and version columns
and materialises all rows.</li>
+ * <li>Builds cache entries from the hidden columns.</li>
+ * <li>Creates a savepoint, acquires pessimistic locks via {@code
lockTxEntries()},
+ * and releases the savepoint on success (or rolls back on
failure).</li>
+ * <li>Repeats the SELECT and lock attempt after a concurrent version
change while the deadline permits.</li>
+ * <li>Returns a cursor with only the user-visible columns (the appended
_KEY is stripped).</li>
+ * </ol>
+ */
+ private FieldsQueryCursor<List<?>> executeForUpdate(RootQuery<Row> qry,
SelectForUpdatePlan plan) {
+ GridNearTxLocal userTx = Commons.queryTransaction(qry.context(),
ctx.cache().context());
+
+ if (userTx == null || !userTx.pessimistic())
+ throw new IgniteSQLException(
+
IgniteResource.INSTANCE.selectForUpdateRequiresPessimisticTx().str(),
+ IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
+
+ // waitSeconds: null = use tx remaining time (0), 0 = NOWAIT (-1),
positive = ms.
+ Long waitSeconds = plan.waitSeconds();
+ long waitMs;
+
+ if (waitSeconds == null)
+ waitMs = 0L;
+ else if (waitSeconds == 0L)
+ waitMs = -1L;
+ else
+ waitMs = waitSeconds * 1000L;
+
+ // Zero means that retries are limited only by the transaction or
query timeout.
+ long deadline = waitMs > 0
+ ? U.currentTimeMillis() + waitMs
+ : waitMs < 0 ? U.currentTimeMillis() : 0L;
+
+ RootQuery<Row> selectQry = qry;
+
+ while (true) {
+ FieldsQueryCursor<List<?>> cursor = tryExecuteForUpdate(selectQry,
plan, userTx, waitMs, deadline);
+
+ if (cursor != null)
+ return cursor;
+
+ if (deadline != 0 && U.currentTimeMillis() >= deadline) {
+ throw new IgniteSQLException(
+ IgniteResource.INSTANCE.selectForUpdateLockFailed().str(),
+ IgniteQueryErrorCode.CONCURRENT_UPDATE);
+ }
+
+ // The previous query has already been closed after
materialisation, so retry with a fresh root query.
+ selectQry = qry.retryQuery();
+ qryReg.register(selectQry);
+ }
+ }
+
+ /**
+ * Executes the inner SELECT once and tries to lock the selected row
versions.
+ *
+ * @return Result cursor when locking succeeds, or {@code null} when the
SELECT must be executed again.
+ */
+ @Nullable private FieldsQueryCursor<List<?>> tryExecuteForUpdate(
+ RootQuery<Row> qry,
+ SelectForUpdatePlan plan,
+ GridNearTxLocal userTx,
+ long waitMs,
+ long deadline
+ ) {
+ // Run the inner SELECT (with _KEY, _VAL, _VER appended) and collect
all rows.
+ ListFieldsQueryCursor<?> innerCursor = mapAndExecutePlan(qry,
plan.innerPlan());
Review Comment:
let`s close cursor explicitly ?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]