zstan commented on code in PR #2846: URL: https://github.com/apache/ignite-3/pull/2846#discussion_r1411695771
########## modules/sql-engine/src/main/java/org/apache/ignite/internal/sql/engine/tx/QueryTransactionHandler.java: ########## @@ -0,0 +1,74 @@ +/* + * 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.sql.engine.tx; + +import static org.apache.ignite.lang.ErrorGroups.Sql.RUNTIME_ERR; + +import org.apache.ignite.internal.sql.engine.SqlQueryType; +import org.apache.ignite.internal.tx.InternalTransaction; +import org.apache.ignite.sql.SqlException; +import org.apache.ignite.tx.IgniteTransactions; +import org.apache.ignite.tx.TransactionOptions; +import org.jetbrains.annotations.Nullable; + +/** + * Starts an implicit transaction if there is no external transaction. + */ +public class QueryTransactionHandler { + final IgniteTransactions transactions; + final @Nullable InternalTransaction outerTransaction; Review Comment: lets use aligned naming i suppose outerTransaction = externalTransaction ? ########## modules/sql-engine/src/integrationTest/java/org/apache/ignite/internal/sql/engine/ItSqlMultiStatementTxTest.java: ########## @@ -0,0 +1,344 @@ +/* + * 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.sql.engine; + +import static org.apache.ignite.internal.lang.IgniteStringFormatter.format; +import static org.apache.ignite.internal.sql.engine.util.SqlTestUtils.assertThrowsSqlException; +import static org.apache.ignite.internal.testframework.IgniteTestUtils.await; +import static org.apache.ignite.internal.testframework.IgniteTestUtils.waitForCondition; +import static org.apache.ignite.lang.ErrorGroups.Sql.RUNTIME_ERR; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasSize; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrowsExactly; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +import java.util.List; +import org.apache.ignite.internal.sql.engine.util.Commons; +import org.apache.ignite.internal.tx.InternalTransaction; +import org.apache.ignite.internal.util.AsyncCursor.BatchedResult; +import org.apache.ignite.sql.ExternalTransactionNotSupportedException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +/** + * Tests to verify the execution of queries with transaction control statements. + * + * @see SqlQueryType#TX_CONTROL + */ +@SuppressWarnings("ThrowableNotThrown") +public class ItSqlMultiStatementTxTest extends BaseSqlMultiStatementTest { + /** Default number of rows in the big table. */ + private static final int BIG_TABLE_ROWS_COUNT = Commons.IN_BUFFER_SIZE * 6; + + /** Number of completed transactions before the test started. */ + private int numberOfFinishedTransactionsOnStart; + + @BeforeAll + void createTable() { + sql("CREATE TABLE test (id INT PRIMARY KEY)"); + + createTable("big", 1, 1); + sql("INSERT INTO big (id) SELECT x FROM TABLE(SYSTEM_RANGE(1, " + BIG_TABLE_ROWS_COUNT + "));"); + } + + @AfterEach + void clearTestTable() { + sql("DELETE FROM test"); + } + + @BeforeEach + void saveFinishedTxCount() { + numberOfFinishedTransactionsOnStart = txManager().finished(); + } + + @Test + void emptyTransactionControlStatement() { + List<AsyncSqlCursor<List<Object>>> cursors = fetchAllCursors( + runScript("START TRANSACTION; COMMIT")); + + assertThat(cursors, hasSize(2)); + + AsyncSqlCursor<List<Object>> cur = cursors.get(0); + assertTrue(cur.hasNextResult()); + validateSingleResult(cur); + + cur = cursors.get(1); + assertFalse(cur.hasNextResult()); + validateSingleResult(cur); + + verifyFinishedTxCount(1); + } + + @Test + void basicTxStatements() { + executeScript("START TRANSACTION;" + + "INSERT INTO test VALUES(0);" + + "INSERT INTO test VALUES(1);" + + "COMMIT;" + + + "START TRANSACTION;" + + "COMMIT;" + + + "START TRANSACTION;" + + "INSERT INTO test VALUES(2);" + + "COMMIT;"); + + verifyFinishedTxCount(3); + + assertQuery("select count(id) from test") + .returns(3L).check(); + } + + @ParameterizedTest(name = "ReadOnly: {0}") + @ValueSource(booleans = {true, false}) + void readMoreRowsThanCanBePrefetched(boolean readOnly) { + String txOptions = readOnly ? "READ ONLY" : "READ WRITE"; + String specificStatement = readOnly ? "SELECT 1::BIGINT" : "UPDATE big SET salary=1 WHERE id=1"; + String query = format("START TRANSACTION {};" + + "{};" + + "SELECT id FROM big;" + + "SELECT id FROM big;" + + "COMMIT;", txOptions, specificStatement); + + AsyncSqlCursor<List<Object>> cursor = runScript(query); + + assertTrue(cursor.hasNextResult()); + + AsyncSqlCursor<List<Object>> updateCursor = await(cursor.nextResult()); + assertNotNull(updateCursor); + validateSingleResult(updateCursor, 1L); + assertTrue(updateCursor.hasNextResult()); + + AsyncSqlCursor<List<Object>> selectCursor0 = await(updateCursor.nextResult()); + assertNotNull(selectCursor0); + + BatchedResult<List<Object>> res = await(selectCursor0.requestNextAsync(BIG_TABLE_ROWS_COUNT / 2)); + assertNotNull(res); + assertThat(res.items(), hasSize(BIG_TABLE_ROWS_COUNT / 2)); + assertEquals(1, txManager().pending(), "Transaction must not finished until the cursor is closed."); + + AsyncSqlCursor<List<Object>> selectCursor1 = await(selectCursor0.nextResult()); + assertNotNull(selectCursor1); + + res = await(selectCursor1.requestNextAsync(BIG_TABLE_ROWS_COUNT * 2)); + assertNotNull(res); + assertThat(res.items(), hasSize(BIG_TABLE_ROWS_COUNT)); + assertEquals(1, txManager().pending(), "Transaction must not finished until the cursor is closed."); + + await(selectCursor0.requestNextAsync(BIG_TABLE_ROWS_COUNT)); // Cursor must close implicitly. + assertFalse(res.hasMore()); + verifyFinishedTxCount(1); + } + + @ParameterizedTest + @ValueSource(strings = {"READ ONLY", "READ WRITE"}) + void openedScriptTransactionRollsBackImplicitly(String txOptions) { + String startTxStatement = format("START TRANSACTION {};", txOptions); + + { + runScript(startTxStatement); + + // Transaction does not depend on the START TRANSACTION statement cursor, + // so it rolls back without waiting for this cursor to close. + verifyFinishedTxCount(1); + } + + { + List<AsyncSqlCursor<List<Object>>> cursors = fetchAllCursors( + runScript(startTxStatement + + "SELECT * FROM TEST;" + + "SELECT * FROM TEST;" + ) + ); + + assertThat(cursors, hasSize(3)); + + // The transaction depends on the cursors of the SELECT statement, + // so it waits for them to close. + assertEquals(1, txManager().pending()); + + cursors.forEach(AsyncSqlCursor::closeAsync); + verifyFinishedTxCount(2); + } + + { + AsyncSqlCursor<List<Object>> cur = runScript("START TRANSACTION READ WRITE;" Review Comment: you not use @ParameterizedTest params is this case, thus it can be moved into different test. ########## modules/sql-engine/src/main/java/org/apache/ignite/internal/sql/engine/tx/ScriptTransactionWrapper.java: ########## @@ -0,0 +1,178 @@ +/* + * 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.sql.engine.tx; + +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Function; +import org.apache.ignite.internal.sql.engine.SqlQueryType; +import org.apache.ignite.internal.sql.engine.util.Commons; +import org.apache.ignite.internal.tx.InternalTransaction; +import org.apache.ignite.internal.util.AsyncCursor; +import org.apache.ignite.tx.Transaction; + +/** + * Wraps a transaction, which is managed by SQL engine via {@link SqlQueryType#TX_CONTROL} statements. + * Responsible for tracking and releasing resources associated with this transaction. + */ +class ScriptTransactionWrapper implements QueryTransactionWrapper { + private final InternalTransaction transaction; + + /** Future completes when all cursors associated with the current transaction are closed. */ + private final CompletableFuture<Void> txFinishFuture = new CompletableFuture<>(); + + /** Opened cursors that must be closed before the transaction can complete. */ + private final Map<UUID, CompletableFuture<? extends AsyncCursor<?>>> openedCursors = new ConcurrentHashMap<>(); + + /** Transaction action (commit or rollback) that will be performed when all dependent cursors are closed. */ + private final AtomicReference<Function<InternalTransaction, CompletableFuture<Void>>> finishTxAction = new AtomicReference<>(); + + ScriptTransactionWrapper(InternalTransaction transaction) { + this.transaction = transaction; + } + + @Override + public InternalTransaction unwrap() { + return transaction; + } + + @Override + public CompletableFuture<Void> commitImplicit() { + return Commons.completedFuture(); + } + + @Override + public CompletableFuture<Void> rollback(Throwable cause) { Review Comment: i see that `Throwable cause` is ignored in more cases, is it ok ? Also i found that sql parsing errors are not informative, for example - run openedScriptTransactionRollsBackImplicitly with wrong syntax, i think it would be hard to found a problem if script will consist from numerous of lines. Seems this is not belong to this issue, if you agree with me - lets fill additional issue ? ########## modules/sql-engine/src/main/java/org/apache/ignite/internal/sql/engine/tx/QueryTransactionHandler.java: ########## @@ -0,0 +1,74 @@ +/* + * 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.sql.engine.tx; + +import static org.apache.ignite.lang.ErrorGroups.Sql.RUNTIME_ERR; + +import org.apache.ignite.internal.sql.engine.SqlQueryType; +import org.apache.ignite.internal.tx.InternalTransaction; +import org.apache.ignite.sql.SqlException; +import org.apache.ignite.tx.IgniteTransactions; +import org.apache.ignite.tx.TransactionOptions; +import org.jetbrains.annotations.Nullable; + +/** + * Starts an implicit transaction if there is no external transaction. + */ +public class QueryTransactionHandler { + final IgniteTransactions transactions; + final @Nullable InternalTransaction outerTransaction; + + public QueryTransactionHandler(IgniteTransactions transactions, @Nullable InternalTransaction outerTransaction) { + this.transactions = transactions; + this.outerTransaction = outerTransaction; + } + + /** + * Starts a transaction if there is no external transaction. + * + * @param queryType Query type. + * @return Transaction wrapper. + */ + public QueryTransactionWrapper startTxIfNeeded(SqlQueryType queryType) { + InternalTransaction activeTx = activeTransaction(); + + if (activeTx == null) { + return new QueryTransactionWrapperImpl((InternalTransaction) transactions.begin( + new TransactionOptions().readOnly(queryType != SqlQueryType.DML)), true); + } + + validateStatement(queryType, activeTx); + + return new QueryTransactionWrapperImpl(activeTx, false); + } + + protected @Nullable InternalTransaction activeTransaction() { + return outerTransaction; Review Comment: externalTx ```suggestion return externalTtarnsaction; ``` ########## modules/sql-engine/src/main/java/org/apache/ignite/internal/sql/engine/tx/QueryTransactionHandler.java: ########## @@ -0,0 +1,74 @@ +/* + * 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.sql.engine.tx; + +import static org.apache.ignite.lang.ErrorGroups.Sql.RUNTIME_ERR; + +import org.apache.ignite.internal.sql.engine.SqlQueryType; +import org.apache.ignite.internal.tx.InternalTransaction; +import org.apache.ignite.sql.SqlException; +import org.apache.ignite.tx.IgniteTransactions; +import org.apache.ignite.tx.TransactionOptions; +import org.jetbrains.annotations.Nullable; + +/** + * Starts an implicit transaction if there is no external transaction. + */ +public class QueryTransactionHandler { + final IgniteTransactions transactions; + final @Nullable InternalTransaction outerTransaction; + + public QueryTransactionHandler(IgniteTransactions transactions, @Nullable InternalTransaction outerTransaction) { Review Comment: the same as above ########## modules/sql-engine/src/main/java/org/apache/ignite/internal/sql/engine/tx/QueryTransactionHandler.java: ########## @@ -0,0 +1,74 @@ +/* + * 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.sql.engine.tx; + +import static org.apache.ignite.lang.ErrorGroups.Sql.RUNTIME_ERR; + +import org.apache.ignite.internal.sql.engine.SqlQueryType; +import org.apache.ignite.internal.tx.InternalTransaction; +import org.apache.ignite.sql.SqlException; +import org.apache.ignite.tx.IgniteTransactions; +import org.apache.ignite.tx.TransactionOptions; +import org.jetbrains.annotations.Nullable; + +/** + * Starts an implicit transaction if there is no external transaction. + */ +public class QueryTransactionHandler { + final IgniteTransactions transactions; + final @Nullable InternalTransaction outerTransaction; + + public QueryTransactionHandler(IgniteTransactions transactions, @Nullable InternalTransaction outerTransaction) { + this.transactions = transactions; + this.outerTransaction = outerTransaction; + } + + /** + * Starts a transaction if there is no external transaction. + * + * @param queryType Query type. + * @return Transaction wrapper. + */ + public QueryTransactionWrapper startTxIfNeeded(SqlQueryType queryType) { + InternalTransaction activeTx = activeTransaction(); + + if (activeTx == null) { + return new QueryTransactionWrapperImpl((InternalTransaction) transactions.begin( + new TransactionOptions().readOnly(queryType != SqlQueryType.DML)), true); + } + + validateStatement(queryType, activeTx); Review Comment: probably we can change execution order for validation and start transaction ? ########## modules/sql-engine/src/main/java/org/apache/ignite/internal/sql/engine/SqlQueryProcessor.java: ########## @@ -681,66 +661,92 @@ private static void validateDynamicParameters(int expectedParamsCount, Object[] } } + /** Returns count of opened cursors. */ + @TestOnly + public int openedCursors() { + return openedCursors.size(); + } + private class MultiStatementHandler { private final String schemaName; - private final IgniteTransactions transactions; - private final @Nullable InternalTransaction explicitTransaction; + private final ScriptTransactionHandler transactionHandler; private final Queue<ScriptStatementParameters> statements; MultiStatementHandler( String schemaName, - IgniteTransactions transactions, - @Nullable InternalTransaction explicitTransaction, + ScriptTransactionHandler transactionHandler, List<ParsedResult> parsedResults, Object[] params ) { this.schemaName = schemaName; - this.transactions = transactions; - this.explicitTransaction = explicitTransaction; + this.transactionHandler = transactionHandler; this.statements = prepareStatementsQueue(parsedResults, params); } - CompletableFuture<AsyncSqlCursor<List<Object>>> processNext() { - if (statements == null) { - // TODO https://issues.apache.org/jira/browse/IGNITE-20463 Each tx control statement must return an empty cursor. - return CompletableFuture.completedFuture(null); + /** + * Returns a queue. each element of which represents parameters required to execute a single statement of the script. + */ + private Queue<ScriptStatementParameters> prepareStatementsQueue(List<ParsedResult> parsedResults0, Object[] params) { Review Comment: ```suggestion private Queue<ScriptStatementParameters> prepareStatementsQueue(List<ParsedResult> parsedResults, Object[] params) { ``` ########## modules/sql-engine/src/test/java/org/apache/ignite/internal/sql/engine/AsyncSqlCursorImplTest.java: ########## @@ -51,7 +52,7 @@ public class AsyncSqlCursorImplTest { /** Cursor should trigger commit of implicit transaction (if any) only if data is fully read. */ @ParameterizedTest(name = "{0}") @MethodSource("transactions") - public void testTriggerCommitAfterDataIsFullyRead(boolean implicit, QueryTransactionWrapper txWrapper) { + public void testTriggerCommitAfterDataIsFullyRead(boolean implicit, QueryTransactionWrapperImpl txWrapper) { Review Comment: why do you need concrete implementation here and below ? -- 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]
