diff --git a/core/src/test/kotlin/net/corda/core/flows/ContractUpgradeFlowTest.kt b/core/src/test/kotlin/net/corda/core/flows/ContractUpgradeFlowTest.kt index a0ba0eed78..8e497d5f8f 100644 --- a/core/src/test/kotlin/net/corda/core/flows/ContractUpgradeFlowTest.kt +++ b/core/src/test/kotlin/net/corda/core/flows/ContractUpgradeFlowTest.kt @@ -14,7 +14,7 @@ import net.corda.flows.ContractUpgradeFlow import net.corda.flows.FinalityFlow import net.corda.node.internal.CordaRPCOpsImpl import net.corda.node.services.startFlowPermission -import net.corda.node.utilities.databaseTransaction +import net.corda.node.utilities.transaction import net.corda.nodeapi.CURRENT_RPC_USER import net.corda.nodeapi.User import net.corda.testing.node.MockNetwork @@ -60,8 +60,8 @@ class ContractUpgradeFlowTest { a.services.startFlow(FinalityFlow(stx, setOf(a.info.legalIdentity, b.info.legalIdentity))) mockNet.runNetwork() - val atx = databaseTransaction(a.database) { a.services.storageService.validatedTransactions.getTransaction(stx.id) } - val btx = databaseTransaction(b.database) { b.services.storageService.validatedTransactions.getTransaction(stx.id) } + val atx = a.database.transaction { a.services.storageService.validatedTransactions.getTransaction(stx.id) } + val btx = b.database.transaction { b.services.storageService.validatedTransactions.getTransaction(stx.id) } requireNotNull(atx) requireNotNull(btx) @@ -80,13 +80,13 @@ class ContractUpgradeFlowTest { val result = resultFuture.get() fun check(node: MockNetwork.MockNode) { - val nodeStx = databaseTransaction(node.database) { + val nodeStx = node.database.transaction { node.services.storageService.validatedTransactions.getTransaction(result.ref.txhash) } requireNotNull(nodeStx) // Verify inputs. - val input = databaseTransaction(node.database) { + val input = node.database.transaction { node.services.storageService.validatedTransactions.getTransaction(nodeStx!!.tx.inputs.single().txhash) } requireNotNull(input) @@ -110,8 +110,8 @@ class ContractUpgradeFlowTest { a.services.startFlow(FinalityFlow(stx, setOf(a.info.legalIdentity, b.info.legalIdentity))) mockNet.runNetwork() - val atx = databaseTransaction(a.database) { a.services.storageService.validatedTransactions.getTransaction(stx.id) } - val btx = databaseTransaction(b.database) { b.services.storageService.validatedTransactions.getTransaction(stx.id) } + val atx = a.database.transaction { a.services.storageService.validatedTransactions.getTransaction(stx.id) } + val btx = b.database.transaction { b.services.storageService.validatedTransactions.getTransaction(stx.id) } requireNotNull(atx) requireNotNull(btx) @@ -143,11 +143,11 @@ class ContractUpgradeFlowTest { val result = resultFuture.get() // Check results. listOf(a, b).forEach { - val signedTX = databaseTransaction(a.database) { a.services.storageService.validatedTransactions.getTransaction(result.ref.txhash) } + val signedTX = a.database.transaction { a.services.storageService.validatedTransactions.getTransaction(result.ref.txhash) } requireNotNull(signedTX) // Verify inputs. - val input = databaseTransaction(a.database) { a.services.storageService.validatedTransactions.getTransaction(signedTX!!.tx.inputs.single().txhash) } + val input = a.database.transaction { a.services.storageService.validatedTransactions.getTransaction(signedTX!!.tx.inputs.single().txhash) } requireNotNull(input) assertTrue(input!!.tx.outputs.single().data is DummyContract.State) @@ -166,7 +166,7 @@ class ContractUpgradeFlowTest { a.services.startFlow(ContractUpgradeFlow.Instigator(stateAndRef, CashV2::class.java)) mockNet.runNetwork() // Get contract state from the vault. - val firstState = databaseTransaction(a.database) { a.vault.unconsumedStates().single() } + val firstState = a.database.transaction { a.vault.unconsumedStates().single() } assertTrue(firstState.state.data is CashV2.State, "Contract state is upgraded to the new version.") assertEquals(Amount(1000000, USD).`issued by`(a.info.legalIdentity.ref(1)), (firstState.state.data as CashV2.State).amount, "Upgraded cash contain the correct amount.") assertEquals(listOf(a.info.legalIdentity.owningKey), (firstState.state.data as CashV2.State).owners, "Upgraded cash belongs to the right owner.") diff --git a/core/src/test/kotlin/net/corda/core/flows/ResolveTransactionsFlowTest.kt b/core/src/test/kotlin/net/corda/core/flows/ResolveTransactionsFlowTest.kt index fa508597e1..7408dd54a4 100644 --- a/core/src/test/kotlin/net/corda/core/flows/ResolveTransactionsFlowTest.kt +++ b/core/src/test/kotlin/net/corda/core/flows/ResolveTransactionsFlowTest.kt @@ -9,7 +9,7 @@ import net.corda.core.serialization.opaque import net.corda.core.transactions.SignedTransaction import net.corda.core.utilities.DUMMY_NOTARY_KEY import net.corda.flows.ResolveTransactionsFlow -import net.corda.node.utilities.databaseTransaction +import net.corda.node.utilities.transaction import net.corda.testing.MEGA_CORP import net.corda.testing.MEGA_CORP_KEY import net.corda.testing.MINI_CORP_PUBKEY @@ -57,7 +57,7 @@ class ResolveTransactionsFlowTest { net.runNetwork() val results = future.getOrThrow() assertEquals(listOf(stx1.id, stx2.id), results.map { it.id }) - databaseTransaction(b.database) { + b.database.transaction { assertEquals(stx1, b.storage.validatedTransactions.getTransaction(stx1.id)) assertEquals(stx2, b.storage.validatedTransactions.getTransaction(stx2.id)) } @@ -80,7 +80,7 @@ class ResolveTransactionsFlowTest { val future = b.services.startFlow(p).resultFuture net.runNetwork() future.getOrThrow() - databaseTransaction(b.database) { + b.database.transaction { assertEquals(stx1, b.storage.validatedTransactions.getTransaction(stx1.id)) // But stx2 wasn't inserted, just stx1. assertNull(b.storage.validatedTransactions.getTransaction(stx2.id)) @@ -97,7 +97,7 @@ class ResolveTransactionsFlowTest { val stx = DummyContract.move(cursor.tx.outRef(0), MINI_CORP_PUBKEY) .addSignatureUnchecked(NullSignature) .toSignedTransaction(false) - databaseTransaction(a.database) { + a.database.transaction { a.services.recordTransactions(stx) } cursor = stx @@ -125,7 +125,7 @@ class ResolveTransactionsFlowTest { toSignedTransaction() } - databaseTransaction(a.database) { + a.database.transaction { a.services.recordTransactions(stx2, stx3) } @@ -147,7 +147,7 @@ class ResolveTransactionsFlowTest { return bs.toByteArray().opaque().open() } // TODO: this operation should not require an explicit transaction - val id = databaseTransaction(a.database) { + val id = a.database.transaction { a.services.storageService.attachments.importAttachment(makeJar()) } val stx2 = makeTransactions(withAttachment = id).second @@ -157,7 +157,7 @@ class ResolveTransactionsFlowTest { future.getOrThrow() // TODO: this operation should not require an explicit transaction - databaseTransaction(b.database) { + b.database.transaction { assertNotNull(b.services.storageService.attachments.openAttachment(id)) } } @@ -178,7 +178,7 @@ class ResolveTransactionsFlowTest { it.signWith(DUMMY_NOTARY_KEY) it.toSignedTransaction() } - databaseTransaction(a.database) { + a.database.transaction { a.services.recordTransactions(dummy1, dummy2) } return Pair(dummy1, dummy2) diff --git a/docs/source/changelog.rst b/docs/source/changelog.rst index cbf9d3e932..41bd9905e1 100644 --- a/docs/source/changelog.rst +++ b/docs/source/changelog.rst @@ -3,6 +3,12 @@ Changelog Here are brief summaries of what's changed between each snapshot release. +UNRELEASED +---------- + +* API changes: + * Added extension function ``Database.transaction`` to replace ``databaseTransaction``, which is now deprecated. + Milestone 10.0 -------------- diff --git a/docs/source/example-code/src/test/kotlin/net/corda/docs/FxTransactionBuildTutorialTest.kt b/docs/source/example-code/src/test/kotlin/net/corda/docs/FxTransactionBuildTutorialTest.kt index ce41490c63..b599d8f67b 100644 --- a/docs/source/example-code/src/test/kotlin/net/corda/docs/FxTransactionBuildTutorialTest.kt +++ b/docs/source/example-code/src/test/kotlin/net/corda/docs/FxTransactionBuildTutorialTest.kt @@ -11,7 +11,7 @@ import net.corda.flows.CashIssueFlow import net.corda.flows.CashPaymentFlow import net.corda.node.services.network.NetworkMapService import net.corda.node.services.transactions.ValidatingNotaryService -import net.corda.node.utilities.databaseTransaction +import net.corda.node.utilities.transaction import net.corda.testing.node.MockNetwork import org.junit.After import org.junit.Before @@ -80,11 +80,11 @@ class FxTransactionBuildTutorialTest { doIt.resultFuture.getOrThrow() // Get the balances when the vault updates nodeAVaultUpdate.get() - val balancesA = databaseTransaction(nodeA.database) { + val balancesA = nodeA.database.transaction { nodeA.services.vaultService.cashBalances } nodeBVaultUpdate.get() - val balancesB = databaseTransaction(nodeB.database) { + val balancesB = nodeB.database.transaction { nodeB.services.vaultService.cashBalances } println("BalanceA\n" + balancesA) @@ -98,10 +98,10 @@ class FxTransactionBuildTutorialTest { private fun printBalances() { // Print out the balances - databaseTransaction(nodeA.database) { + nodeA.database.transaction { println("BalanceA\n" + nodeA.services.vaultService.cashBalances) } - databaseTransaction(nodeB.database) { + nodeB.database.transaction { println("BalanceB\n" + nodeB.services.vaultService.cashBalances) } } diff --git a/docs/source/example-code/src/test/kotlin/net/corda/docs/WorkflowTransactionBuildTutorialTest.kt b/docs/source/example-code/src/test/kotlin/net/corda/docs/WorkflowTransactionBuildTutorialTest.kt index 70558a35a6..6815a205e2 100644 --- a/docs/source/example-code/src/test/kotlin/net/corda/docs/WorkflowTransactionBuildTutorialTest.kt +++ b/docs/source/example-code/src/test/kotlin/net/corda/docs/WorkflowTransactionBuildTutorialTest.kt @@ -13,7 +13,7 @@ import net.corda.core.utilities.DUMMY_NOTARY import net.corda.core.utilities.DUMMY_NOTARY_KEY import net.corda.node.services.network.NetworkMapService import net.corda.node.services.transactions.ValidatingNotaryService -import net.corda.node.utilities.databaseTransaction +import net.corda.node.utilities.transaction import net.corda.testing.node.MockNetwork import org.junit.After import org.junit.Before @@ -66,10 +66,10 @@ class WorkflowTransactionBuildTutorialTest { // Wait for NodeB to include it's copy in the vault nodeBVaultUpdate.get() // Fetch the latest copy of the state from both nodes - val latestFromA = databaseTransaction(nodeA.database) { + val latestFromA = nodeA.database.transaction { nodeA.services.latest(proposalRef.ref) } - val latestFromB = databaseTransaction(nodeB.database) { + val latestFromB = nodeB.database.transaction { nodeB.services.latest(proposalRef.ref) } // Confirm the state as as expected @@ -90,10 +90,10 @@ class WorkflowTransactionBuildTutorialTest { nodeAVaultUpdate.get() secondNodeBVaultUpdate.get() // Fetch the latest copies from the vault - val finalFromA = databaseTransaction(nodeA.database) { + val finalFromA = nodeA.database.transaction { nodeA.services.latest(proposalRef.ref) } - val finalFromB = databaseTransaction(nodeB.database) { + val finalFromB = nodeB.database.transaction { nodeB.services.latest(proposalRef.ref) } // Confirm the state is as expected diff --git a/docs/source/flow-testing.rst b/docs/source/flow-testing.rst index 8101f0bf5f..73b062998d 100644 --- a/docs/source/flow-testing.rst +++ b/docs/source/flow-testing.rst @@ -76,7 +76,7 @@ It doesn't do anything else. This code simply creates a transaction that issues converts the builder to the final ``SignedTransaction``. It then does so again, but this time instead of issuing it re-assigns ownership instead. The chain of two transactions is finally committed to node A by sending them directly to the ``a.services.recordTransaction`` method (note that this method doesn't check the transactions are -valid) inside a ``databaseTransaction``. All node flows run within a database transaction in the nodes themselves, +valid) inside a ``database.transaction``. All node flows run within a database transaction in the nodes themselves, but any time we need to use the database directly from a unit test, you need to provide a database transaction as shown here. diff --git a/finance/src/test/kotlin/net/corda/contracts/CommercialPaperTests.kt b/finance/src/test/kotlin/net/corda/contracts/CommercialPaperTests.kt index 09bf473d81..b05ea0fa01 100644 --- a/finance/src/test/kotlin/net/corda/contracts/CommercialPaperTests.kt +++ b/finance/src/test/kotlin/net/corda/contracts/CommercialPaperTests.kt @@ -15,7 +15,7 @@ import net.corda.core.utilities.DUMMY_NOTARY_KEY import net.corda.core.utilities.DUMMY_PUBKEY_1 import net.corda.core.utilities.TEST_TX_TIME import net.corda.node.utilities.configureDatabase -import net.corda.node.utilities.databaseTransaction +import net.corda.node.utilities.transaction import net.corda.testing.* import net.corda.testing.node.MockServices import net.corda.testing.node.makeTestDataSourceProperties @@ -216,7 +216,7 @@ class CommercialPaperTestsGeneric { val dataSourcePropsAlice = makeTestDataSourceProperties() val dataSourceAndDatabaseAlice = configureDatabase(dataSourcePropsAlice) val databaseAlice = dataSourceAndDatabaseAlice.second - databaseTransaction(databaseAlice) { + databaseAlice.transaction { aliceServices = object : MockServices() { override val vaultService: VaultService = makeVaultService(dataSourcePropsAlice) @@ -236,7 +236,7 @@ class CommercialPaperTestsGeneric { val dataSourcePropsBigCorp = makeTestDataSourceProperties() val dataSourceAndDatabaseBigCorp = configureDatabase(dataSourcePropsBigCorp) val databaseBigCorp = dataSourceAndDatabaseBigCorp.second - databaseTransaction(databaseBigCorp) { + databaseBigCorp.transaction { bigCorpServices = object : MockServices() { override val vaultService: VaultService = makeVaultService(dataSourcePropsBigCorp) @@ -267,7 +267,7 @@ class CommercialPaperTestsGeneric { signWith(DUMMY_NOTARY_KEY) }.toSignedTransaction() - databaseTransaction(databaseAlice) { + databaseAlice.transaction { // Alice pays $9000 to BigCorp to own some of their debt. moveTX = run { val ptx = TransactionType.General.Builder(DUMMY_NOTARY) @@ -280,7 +280,7 @@ class CommercialPaperTestsGeneric { } } - databaseTransaction(databaseBigCorp) { + databaseBigCorp.transaction { // Verify the txns are valid and insert into both sides. listOf(issueTX, moveTX).forEach { it.toLedgerTransaction(aliceServices).verify() @@ -289,7 +289,7 @@ class CommercialPaperTestsGeneric { } } - databaseTransaction(databaseBigCorp) { + databaseBigCorp.transaction { fun makeRedeemTX(time: Instant): Pair { val ptx = TransactionType.General.Builder(DUMMY_NOTARY) ptx.setTime(time, 30.seconds) diff --git a/finance/src/test/kotlin/net/corda/contracts/asset/CashTests.kt b/finance/src/test/kotlin/net/corda/contracts/asset/CashTests.kt index 098ae492b7..f85860c545 100644 --- a/finance/src/test/kotlin/net/corda/contracts/asset/CashTests.kt +++ b/finance/src/test/kotlin/net/corda/contracts/asset/CashTests.kt @@ -11,7 +11,7 @@ import net.corda.core.transactions.WireTransaction import net.corda.core.utilities.* import net.corda.node.services.vault.NodeVaultService import net.corda.node.utilities.configureDatabase -import net.corda.node.utilities.databaseTransaction +import net.corda.node.utilities.transaction import net.corda.testing.* import net.corda.testing.node.MockKeyManagementService import net.corda.testing.node.MockServices @@ -53,7 +53,7 @@ class CashTests { val dataSourceAndDatabase = configureDatabase(dataSourceProps) dataSource = dataSourceAndDatabase.first database = dataSourceAndDatabase.second - databaseTransaction(database) { + database.transaction { services = object : MockServices() { override val keyManagementService: MockKeyManagementService = MockKeyManagementService(MINI_CORP_KEY, MEGA_CORP_KEY, OUR_KEY) override val vaultService: VaultService = makeVaultService(dataSourceProps) @@ -484,7 +484,7 @@ class CashTests { fun makeSpend(amount: Amount, dest: PublicKey): WireTransaction { val tx = TransactionType.General.Builder(DUMMY_NOTARY) - databaseTransaction(database) { + database.transaction { vault.generateSpend(tx, amount, dest) } return tx.toWireTransaction() @@ -562,7 +562,7 @@ class CashTests { @Test fun generateSimpleDirectSpend() { - databaseTransaction(database) { + database.transaction { val wtx = makeSpend(100.DOLLARS, THEIR_PUBKEY_1) @@ -577,7 +577,7 @@ class CashTests { @Test fun generateSimpleSpendWithParties() { - databaseTransaction(database) { + database.transaction { val tx = TransactionType.General.Builder(DUMMY_NOTARY) vault.generateSpend(tx, 80.DOLLARS, ALICE_PUBKEY, setOf(MINI_CORP.toAnonymous())) @@ -589,7 +589,7 @@ class CashTests { @Test fun generateSimpleSpendWithChange() { - databaseTransaction(database) { + database.transaction { val wtx = makeSpend(10.DOLLARS, THEIR_PUBKEY_1) @@ -605,7 +605,7 @@ class CashTests { @Test fun generateSpendWithTwoInputs() { - databaseTransaction(database) { + database.transaction { val wtx = makeSpend(500.DOLLARS, THEIR_PUBKEY_1) @Suppress("UNCHECKED_CAST") @@ -621,7 +621,7 @@ class CashTests { @Test fun generateSpendMixedDeposits() { - databaseTransaction(database) { + database.transaction { val wtx = makeSpend(580.DOLLARS, THEIR_PUBKEY_1) assertEquals(3, wtx.inputs.size) @@ -642,7 +642,7 @@ class CashTests { @Test fun generateSpendInsufficientBalance() { - databaseTransaction(database) { + database.transaction { val e: InsufficientBalanceException = assertFailsWith("balance") { makeSpend(1000.DOLLARS, THEIR_PUBKEY_1) diff --git a/node/src/integration-test/kotlin/net/corda/node/services/BFTNotaryServiceTests.kt b/node/src/integration-test/kotlin/net/corda/node/services/BFTNotaryServiceTests.kt index 0f4cc5ca0f..37de85bf19 100644 --- a/node/src/integration-test/kotlin/net/corda/node/services/BFTNotaryServiceTests.kt +++ b/node/src/integration-test/kotlin/net/corda/node/services/BFTNotaryServiceTests.kt @@ -17,7 +17,7 @@ import net.corda.node.internal.AbstractNode import net.corda.node.internal.Node import net.corda.node.services.transactions.BFTNonValidatingNotaryService import net.corda.node.utilities.ServiceIdentityGenerator -import net.corda.node.utilities.databaseTransaction +import net.corda.node.utilities.transaction import net.corda.testing.node.NodeBasedTest import org.junit.Test import java.security.KeyPair @@ -34,8 +34,8 @@ class BFTNotaryServiceTests : NodeBasedTest() { val alice = startNode(ALICE.name).getOrThrow() val notaryParty = alice.netMapCache.getNotary(notaryName)!! - val notaryNodeKeyPair = databaseTransaction(masterNode.database) { masterNode.services.notaryIdentityKey } - val aliceKey = databaseTransaction(alice.database) { alice.services.legalIdentityKey } + val notaryNodeKeyPair = with(masterNode) { database.transaction { services.notaryIdentityKey } } + val aliceKey = with(alice) { database.transaction { services.legalIdentityKey } } val inputState = issueState(alice, notaryParty, notaryNodeKeyPair) @@ -61,7 +61,7 @@ class BFTNotaryServiceTests : NodeBasedTest() { } private fun issueState(node: AbstractNode, notary: Party, notaryKey: KeyPair): StateAndRef<*> { - return databaseTransaction(node.database) { + return node.database.transaction { val tx = DummyContract.generateInitial(Random().nextInt(), notary, node.info.legalIdentity.ref(0)) tx.signWith(node.services.legalIdentityKey) tx.signWith(notaryKey) diff --git a/node/src/integration-test/kotlin/net/corda/node/services/RaftNotaryServiceTests.kt b/node/src/integration-test/kotlin/net/corda/node/services/RaftNotaryServiceTests.kt index 3097025b57..44fee7248e 100644 --- a/node/src/integration-test/kotlin/net/corda/node/services/RaftNotaryServiceTests.kt +++ b/node/src/integration-test/kotlin/net/corda/node/services/RaftNotaryServiceTests.kt @@ -13,7 +13,7 @@ import net.corda.flows.NotaryError import net.corda.flows.NotaryException import net.corda.flows.NotaryFlow import net.corda.node.internal.AbstractNode -import net.corda.node.utilities.databaseTransaction +import net.corda.node.utilities.transaction import net.corda.testing.node.NodeBasedTest import org.junit.Test import java.security.KeyPair @@ -32,8 +32,8 @@ class RaftNotaryServiceTests : NodeBasedTest() { ).getOrThrow() val notaryParty = alice.netMapCache.getNotary(notaryName)!! - val notaryNodeKeyPair = databaseTransaction(masterNode.database) { masterNode.services.notaryIdentityKey } - val aliceKey = databaseTransaction(alice.database) { alice.services.legalIdentityKey } + val notaryNodeKeyPair = with(masterNode) { database.transaction { services.notaryIdentityKey } } + val aliceKey = with(alice) { database.transaction { services.legalIdentityKey } } val inputState = issueState(alice, notaryParty, notaryNodeKeyPair) @@ -58,7 +58,7 @@ class RaftNotaryServiceTests : NodeBasedTest() { } private fun issueState(node: AbstractNode, notary: Party, notaryKey: KeyPair): StateAndRef<*> { - return databaseTransaction(node.database) { + return node.database.transaction { val tx = DummyContract.generateInitial(Random().nextInt(), notary, node.info.legalIdentity.ref(0)) tx.signWith(node.services.legalIdentityKey) tx.signWith(notaryKey) diff --git a/node/src/integration-test/kotlin/net/corda/node/utilities/JDBCHashMapTestSuite.kt b/node/src/integration-test/kotlin/net/corda/node/utilities/JDBCHashMapTestSuite.kt index 7d6f5b0cf6..261aaff04f 100644 --- a/node/src/integration-test/kotlin/net/corda/node/utilities/JDBCHashMapTestSuite.kt +++ b/node/src/integration-test/kotlin/net/corda/node/utilities/JDBCHashMapTestSuite.kt @@ -246,17 +246,17 @@ class JDBCHashMapTestSuite { @Test fun `fill map and check content after reconstruction`() { - databaseTransaction(database) { + database.transaction { val persistentMap = JDBCHashMap("the_table") // Populate map the first time. applyOpsToMap(persistentMap) assertThat(persistentMap.entries).containsExactly(*transientMapForComparison.entries.toTypedArray()) } - databaseTransaction(database) { + database.transaction { val persistentMap = JDBCHashMap("the_table", loadOnInit = false) assertThat(persistentMap.entries).containsExactly(*transientMapForComparison.entries.toTypedArray()) } - databaseTransaction(database) { + database.transaction { val persistentMap = JDBCHashMap("the_table", loadOnInit = true) assertThat(persistentMap.entries).containsExactly(*transientMapForComparison.entries.toTypedArray()) } diff --git a/node/src/main/kotlin/net/corda/node/internal/AbstractNode.kt b/node/src/main/kotlin/net/corda/node/internal/AbstractNode.kt index 7801e18c4d..2f0bddf309 100644 --- a/node/src/main/kotlin/net/corda/node/internal/AbstractNode.kt +++ b/node/src/main/kotlin/net/corda/node/internal/AbstractNode.kt @@ -49,7 +49,7 @@ import net.corda.node.services.vault.VaultSoftLockManager import net.corda.node.utilities.AddOrRemove.ADD import net.corda.node.utilities.AffinityExecutor import net.corda.node.utilities.configureDatabase -import net.corda.node.utilities.databaseTransaction +import net.corda.node.utilities.transaction import org.apache.activemq.artemis.utils.ReusableLatch import org.jetbrains.exposed.sql.Database import org.slf4j.Logger @@ -141,7 +141,7 @@ abstract class AbstractNode(open val configuration: NodeConfiguration, } override fun recordTransactions(txs: Iterable) { - databaseTransaction(database) { + database.transaction { recordTransactionsInternal(storage, txs) } } @@ -339,7 +339,7 @@ abstract class AbstractNode(open val configuration: NodeConfiguration, log.info("Connected to ${database.vendor} database.") dbCloser = Runnable { toClose.close() } runOnStop += dbCloser!! - databaseTransaction(database) { + database.transaction { insideTransaction() } } else { diff --git a/node/src/main/kotlin/net/corda/node/internal/CordaRPCOpsImpl.kt b/node/src/main/kotlin/net/corda/node/internal/CordaRPCOpsImpl.kt index b60ef5c511..34394bcd1a 100644 --- a/node/src/main/kotlin/net/corda/node/internal/CordaRPCOpsImpl.kt +++ b/node/src/main/kotlin/net/corda/node/internal/CordaRPCOpsImpl.kt @@ -22,7 +22,7 @@ import net.corda.node.services.startFlowPermission import net.corda.node.services.statemachine.FlowStateMachineImpl import net.corda.node.services.statemachine.StateMachineManager import net.corda.node.utilities.AddOrRemove -import net.corda.node.utilities.databaseTransaction +import net.corda.node.utilities.transaction import org.jetbrains.exposed.sql.Database import rx.Observable import java.io.InputStream @@ -42,26 +42,26 @@ class CordaRPCOpsImpl( override val protocolVersion: Int get() = 0 override fun networkMapUpdates(): Pair, Observable> { - return databaseTransaction(database) { + return database.transaction { services.networkMapCache.track() } } override fun vaultAndUpdates(): Pair>, Observable> { - return databaseTransaction(database) { + return database.transaction { val (vault, updates) = services.vaultService.track() Pair(vault.states.toList(), updates) } } override fun verifiedTransactions(): Pair, Observable> { - return databaseTransaction(database) { + return database.transaction { services.storageService.validatedTransactions.track() } } override fun stateMachinesAndUpdates(): Pair, Observable> { - return databaseTransaction(database) { + return database.transaction { val (allStateMachines, changes) = smm.track() Pair( allStateMachines.map { stateMachineInfoFromFlowLogic(it.id, it.logic) }, @@ -71,7 +71,7 @@ class CordaRPCOpsImpl( } override fun stateMachineRecordedTransactionMapping(): Pair, Observable> { - return databaseTransaction(database) { + return database.transaction { services.storageService.stateMachineRecordedTransactionMapping.track() } } @@ -81,19 +81,19 @@ class CordaRPCOpsImpl( } override fun addVaultTransactionNote(txnId: SecureHash, txnNote: String) { - return databaseTransaction(database) { + return database.transaction { services.vaultService.addNoteToTransaction(txnId, txnNote) } } override fun getVaultTransactionNotes(txnId: SecureHash): Iterable { - return databaseTransaction(database) { + return database.transaction { services.vaultService.getTransactionNotes(txnId) } } override fun getCashBalances(): Map> { - return databaseTransaction(database) { + return database.transaction { services.vaultService.cashBalances } } @@ -111,21 +111,21 @@ class CordaRPCOpsImpl( override fun attachmentExists(id: SecureHash): Boolean { // TODO: this operation should not require an explicit transaction - return databaseTransaction(database) { + return database.transaction { services.storageService.attachments.openAttachment(id) != null } } override fun openAttachment(id: SecureHash): InputStream { // TODO: this operation should not require an explicit transaction - return databaseTransaction(database) { + return database.transaction { services.storageService.attachments.openAttachment(id)!!.open() } } override fun uploadAttachment(jar: InputStream): SecureHash { // TODO: this operation should not require an explicit transaction - return databaseTransaction(database) { + return database.transaction { services.storageService.attachments.importAttachment(jar) } } @@ -136,7 +136,7 @@ class CordaRPCOpsImpl( @Suppress("OverridingDeprecatedMember", "DEPRECATION") override fun uploadFile(dataType: String, name: String?, file: InputStream): String { val acceptor = services.storageService.uploaders.firstOrNull { it.accepts(dataType) } - return databaseTransaction(database) { + return database.transaction { acceptor?.upload(file) ?: throw RuntimeException("Cannot find file upload acceptor for $dataType") } } diff --git a/node/src/main/kotlin/net/corda/node/services/messaging/NodeMessagingClient.kt b/node/src/main/kotlin/net/corda/node/services/messaging/NodeMessagingClient.kt index e0c5d463dd..a59cb484ed 100644 --- a/node/src/main/kotlin/net/corda/node/services/messaging/NodeMessagingClient.kt +++ b/node/src/main/kotlin/net/corda/node/services/messaging/NodeMessagingClient.kt @@ -338,7 +338,7 @@ class NodeMessagingClient(override val config: NodeConfiguration, // Note that handlers may re-enter this class. We aren't holding any locks and methods like // start/run/stop have re-entrancy assertions at the top, so it is OK. nodeExecutor.fetchFrom { - databaseTransaction(database) { + database.transaction { if (msg.uniqueMessageId in processedMessages) { log.trace { "Discard duplicate message ${msg.uniqueMessageId} for ${msg.topicSession}" } } else { diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/FlowStateMachineImpl.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/FlowStateMachineImpl.kt index 1b36e82b6c..0467398fb0 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/FlowStateMachineImpl.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/FlowStateMachineImpl.kt @@ -21,7 +21,7 @@ import net.corda.core.utilities.debug import net.corda.core.utilities.trace import net.corda.node.services.api.ServiceHubInternal import net.corda.node.utilities.StrandLocalTransactionManager -import net.corda.node.utilities.createDatabaseTransaction +import net.corda.node.utilities.createTransaction import org.jetbrains.exposed.sql.Database import org.jetbrains.exposed.sql.Transaction import org.jetbrains.exposed.sql.transactions.TransactionManager @@ -133,7 +133,7 @@ class FlowStateMachineImpl(override val id: StateMachineRunId, private fun createTransaction() { // Make sure we have a database transaction - createDatabaseTransaction(database) + database.createTransaction() logger.trace { "Starting database transaction ${TransactionManager.currentOrNull()} on ${Strand.currentStrand()}" } } diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/StateMachineManager.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/StateMachineManager.kt index fc2b8383f8..e263fe89d2 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/StateMachineManager.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/StateMachineManager.kt @@ -243,7 +243,7 @@ class StateMachineManager(val serviceHub: ServiceHubInternal, val waitingForResponse = fiber.waitingForResponse if (waitingForResponse != null) { if (waitingForResponse is WaitForLedgerCommit) { - val stx = databaseTransaction(database) { + val stx = database.transaction { serviceHub.storageService.validatedTransactions.getTransaction(waitingForResponse.hash) } if (stx != null) { @@ -457,7 +457,7 @@ class StateMachineManager(val serviceHub: ServiceHubInternal, // on the flow completion future inside that context. The problem is that any progress checkpoints are // unable to acquire the table lock and move forward till the calling transaction finishes. // Committing in line here on a fresh context ensure we can progress. - val fiber = isolatedTransaction(database) { + val fiber = database.isolatedTransaction { val fiber = createFiber(logic) updateCheckpoint(fiber) fiber @@ -508,7 +508,7 @@ class StateMachineManager(val serviceHub: ServiceHubInternal, } } else if (ioRequest is WaitForLedgerCommit) { // Is it already committed? - val stx = databaseTransaction(database) { + val stx = database.transaction { serviceHub.storageService.validatedTransactions.getTransaction(ioRequest.hash) } if (stx != null) { diff --git a/node/src/main/kotlin/net/corda/node/services/transactions/BFTSMaRt.kt b/node/src/main/kotlin/net/corda/node/services/transactions/BFTSMaRt.kt index 19b48eecc0..89f7a98510 100644 --- a/node/src/main/kotlin/net/corda/node/services/transactions/BFTSMaRt.kt +++ b/node/src/main/kotlin/net/corda/node/services/transactions/BFTSMaRt.kt @@ -26,7 +26,7 @@ import net.corda.node.services.api.ServiceHubInternal import net.corda.node.services.transactions.BFTSMaRt.Client import net.corda.node.services.transactions.BFTSMaRt.Server import net.corda.node.utilities.JDBCHashMap -import net.corda.node.utilities.databaseTransaction +import net.corda.node.utilities.transaction import org.jetbrains.exposed.sql.Database import java.util.* @@ -144,7 +144,7 @@ object BFTSMaRt { // TODO: Use Requery with proper DB schema instead of JDBCHashMap. // Must be initialised before ServiceReplica is started - val commitLog = databaseTransaction(db) { JDBCHashMap(tableName) } + val commitLog = db.transaction { JDBCHashMap(tableName) } init { // TODO: Looks like this statement is blocking. Investigate the bft-smart node startup. @@ -171,7 +171,7 @@ object BFTSMaRt { protected fun commitInputStates(states: List, txId: SecureHash, callerIdentity: Party) { log.debug { "Attempting to commit inputs for transaction: $txId" } val conflicts = mutableMapOf() - databaseTransaction(db) { + db.transaction { states.forEach { state -> commitLog[state]?.let { conflicts[state] = it } } @@ -197,7 +197,7 @@ object BFTSMaRt { } protected fun sign(bytes: ByteArray): DigitalSignature.WithKey { - val mySigningKey = databaseTransaction(db) { services.notaryIdentityKey } + val mySigningKey = db.transaction { services.notaryIdentityKey } return mySigningKey.signWithECDSA(bytes) } @@ -207,7 +207,7 @@ object BFTSMaRt { override fun getSnapshot(): ByteArray { // LinkedHashMap for deterministic serialisation val m = LinkedHashMap() - databaseTransaction(db) { + db.transaction { commitLog.forEach { m[it.key] = it.value } } return m.serialize().bytes @@ -215,7 +215,7 @@ object BFTSMaRt { override fun installSnapshot(bytes: ByteArray) { val m = bytes.deserialize>() - databaseTransaction(db) { + db.transaction { commitLog.clear() commitLog.putAll(m) } diff --git a/node/src/main/kotlin/net/corda/node/services/transactions/DistributedImmutableMap.kt b/node/src/main/kotlin/net/corda/node/services/transactions/DistributedImmutableMap.kt index 7c09b7fdd3..6cfed03980 100644 --- a/node/src/main/kotlin/net/corda/node/services/transactions/DistributedImmutableMap.kt +++ b/node/src/main/kotlin/net/corda/node/services/transactions/DistributedImmutableMap.kt @@ -9,7 +9,7 @@ import io.atomix.copycat.server.storage.snapshot.SnapshotReader import io.atomix.copycat.server.storage.snapshot.SnapshotWriter import net.corda.core.utilities.loggerFor import net.corda.node.utilities.JDBCHashMap -import net.corda.node.utilities.databaseTransaction +import net.corda.node.utilities.transaction import org.jetbrains.exposed.sql.Database import java.util.* @@ -39,13 +39,13 @@ class DistributedImmutableMap(val db: Database, tableName: Str class Get(val key: K) : Query } - private val map = databaseTransaction(db) { JDBCHashMap(tableName) } + private val map = db.transaction { JDBCHashMap(tableName) } /** Gets a value for the given [Commands.Get.key] */ fun get(commit: Commit>): V? { commit.use { val key = it.operation().key - return databaseTransaction(db) { map[key] } + return db.transaction { map[key] } } } @@ -57,7 +57,7 @@ class DistributedImmutableMap(val db: Database, tableName: Str fun put(commit: Commit>): Map { commit.use { commit -> val conflicts = LinkedHashMap() - databaseTransaction(db) { + db.transaction { val entries = commit.operation().entries log.debug("State machine commit: storing entries with keys (${entries.keys.joinToString()})") for (key in entries.keys) map[key]?.let { conflicts[key] = it } @@ -69,7 +69,7 @@ class DistributedImmutableMap(val db: Database, tableName: Str fun size(commit: Commit): Int { commit.use { commit -> - return databaseTransaction(db) { map.size } + return db.transaction { map.size } } } @@ -79,7 +79,7 @@ class DistributedImmutableMap(val db: Database, tableName: Str * fixed number of recently accessed entries to ever be kept in memory. */ override fun snapshot(writer: SnapshotWriter) { - databaseTransaction(db) { + db.transaction { writer.writeInt(map.size) map.entries.forEach { writer.writeObject(it.key to it.value) } } @@ -88,7 +88,7 @@ class DistributedImmutableMap(val db: Database, tableName: Str /** Reads entries from disk and adds them to [map]. */ override fun install(reader: SnapshotReader) { val size = reader.readInt() - databaseTransaction(db) { + db.transaction { map.clear() // TODO: read & put entries in batches for (i in 1..size) { @@ -97,4 +97,4 @@ class DistributedImmutableMap(val db: Database, tableName: Str } } } -} \ No newline at end of file +} diff --git a/node/src/main/kotlin/net/corda/node/services/vault/CashBalanceAsMetricsObserver.kt b/node/src/main/kotlin/net/corda/node/services/vault/CashBalanceAsMetricsObserver.kt index 9360e8613a..9eb1719ef6 100644 --- a/node/src/main/kotlin/net/corda/node/services/vault/CashBalanceAsMetricsObserver.kt +++ b/node/src/main/kotlin/net/corda/node/services/vault/CashBalanceAsMetricsObserver.kt @@ -3,7 +3,7 @@ package net.corda.node.services.vault import com.codahale.metrics.Gauge import net.corda.core.node.services.VaultService import net.corda.node.services.api.ServiceHubInternal -import net.corda.node.utilities.databaseTransaction +import net.corda.node.utilities.transaction import org.jetbrains.exposed.sql.Database import java.util.* @@ -31,7 +31,7 @@ class CashBalanceAsMetricsObserver(val serviceHubInternal: ServiceHubInternal, v // // Note: exported as pennies. val m = serviceHubInternal.monitoringService.metrics - databaseTransaction(database) { + database.transaction { for ((key, value) in vault.cashBalances) { val metric = balanceMetrics.getOrPut(key) { val newMetric = BalanceMetric() diff --git a/node/src/main/kotlin/net/corda/node/utilities/DatabaseSupport.kt b/node/src/main/kotlin/net/corda/node/utilities/DatabaseSupport.kt index ef527e9aec..eed2db06f7 100644 --- a/node/src/main/kotlin/net/corda/node/utilities/DatabaseSupport.kt +++ b/node/src/main/kotlin/net/corda/node/utilities/DatabaseSupport.kt @@ -32,16 +32,19 @@ import java.util.concurrent.CopyOnWriteArrayList */ const val NODE_DATABASE_PREFIX = "node_" +@Deprecated("Use Database.transaction instead.") +fun databaseTransaction(db: Database, statement: Transaction.() -> T) = db.transaction(statement) + // TODO: Handle commit failure due to database unavailable. Better to shutdown and await database reconnect/recovery. -fun databaseTransaction(db: Database, statement: Transaction.() -> T): T { +fun Database.transaction(statement: Transaction.() -> T): T { // We need to set the database for the current [Thread] or [Fiber] here as some tests share threads across databases. - StrandLocalTransactionManager.database = db + StrandLocalTransactionManager.database = this return org.jetbrains.exposed.sql.transactions.transaction(Connection.TRANSACTION_REPEATABLE_READ, 1, statement) } -fun createDatabaseTransaction(db: Database): Transaction { +fun Database.createTransaction(): Transaction { // We need to set the database for the current [Thread] or [Fiber] here as some tests share threads across databases. - StrandLocalTransactionManager.database = db + StrandLocalTransactionManager.database = this return TransactionManager.currentOrNew(Connection.TRANSACTION_REPEATABLE_READ) } @@ -50,16 +53,16 @@ fun configureDatabase(props: Properties): Pair { val dataSource = HikariDataSource(config) val database = Database.connect(dataSource) { db -> StrandLocalTransactionManager(db) } // Check not in read-only mode. - databaseTransaction(database) { + database.transaction { check(!database.metadata.isReadOnly) { "Database should not be readonly." } } return Pair(dataSource, database) } -fun isolatedTransaction(database: Database, block: Transaction.() -> T): T { +fun Database.isolatedTransaction(block: Transaction.() -> T): T { val oldContext = StrandLocalTransactionManager.setThreadLocalTx(null) return try { - databaseTransaction(database, block) + transaction(block) } finally { StrandLocalTransactionManager.restoreThreadLocalTx(oldContext) } @@ -73,7 +76,7 @@ fun isolatedTransaction(database: Database, block: Transaction.() -> T): T { * our tests involving two [MockNode]s effectively replace the database instances of each other and continue to trample * over each other. So here we use a companion object to hold them as [ThreadLocal] and [StrandLocalTransactionManager] * is otherwise effectively stateless so it's replacement does not matter. The [ThreadLocal] is then set correctly and - * explicitly just prior to initiating a transaction in [databaseTransaction] and [createDatabaseTransaction] above. + * explicitly just prior to initiating a transaction in [transaction] and [createTransaction] above. * * The [StrandLocalTransactionManager] instances have an [Observable] of the transaction close [Boundary]s which * facilitates the use of [Observable.afterDatabaseCommit] to create event streams that only emit once the database @@ -121,7 +124,7 @@ class StrandLocalTransactionManager(initWithDatabase: Database) : TransactionMan init { // Found a unit test that was forgetting to close the database transactions. When you close() on the top level // database transaction it will reset the threadLocalTx back to null, so if it isn't then there is still a - // databae transaction open. The [databaseTransaction] helper above handles this in a finally clause for you + // databae transaction open. The [transaction] helper above handles this in a finally clause for you // but any manual database transaction management is liable to have this problem. if (threadLocalTx.get() != null) { throw IllegalStateException("Was not expecting to find existing database transaction on current strand when setting database: ${Strand.currentStrand()}, ${threadLocalTx.get()}") @@ -197,7 +200,7 @@ private class DatabaseTransactionWrappingSubscriber(val db: Database?) : Subs val delegates = CopyOnWriteArrayList>() fun forEachSubscriberWithDbTx(block: Subscriber.() -> Unit) { - databaseTransaction(db ?: StrandLocalTransactionManager.database) { + (db ?: StrandLocalTransactionManager.database).transaction { delegates.filter { !it.isUnsubscribed }.forEach { it.block() } diff --git a/node/src/main/kotlin/net/corda/node/utilities/JDBCHashMap.kt b/node/src/main/kotlin/net/corda/node/utilities/JDBCHashMap.kt index 8979ea6fc9..26df75020b 100644 --- a/node/src/main/kotlin/net/corda/node/utilities/JDBCHashMap.kt +++ b/node/src/main/kotlin/net/corda/node/utilities/JDBCHashMap.kt @@ -189,7 +189,7 @@ abstract class AbstractJDBCHashSet(protected v * number of hash "buckets", where one bucket represents all entries with the same hash code. There is a default value * for maximum buckets. * - * All operations require a [databaseTransaction] to be started. + * All operations require a [transaction] to be started. * * The keys/values/entries collections are really designed just for iterating and other uses might turn out to be * costly in terms of performance. Beware when loadOnInit=true, the iterator first sorts the entries which could be diff --git a/node/src/test/kotlin/net/corda/node/CordaRPCOpsImplTest.kt b/node/src/test/kotlin/net/corda/node/CordaRPCOpsImplTest.kt index ab75a32253..fe161205d0 100644 --- a/node/src/test/kotlin/net/corda/node/CordaRPCOpsImplTest.kt +++ b/node/src/test/kotlin/net/corda/node/CordaRPCOpsImplTest.kt @@ -18,7 +18,7 @@ import net.corda.node.internal.CordaRPCOpsImpl import net.corda.node.services.network.NetworkMapService import net.corda.node.services.startFlowPermission import net.corda.node.services.transactions.SimpleNotaryService -import net.corda.node.utilities.databaseTransaction +import net.corda.node.utilities.transaction import net.corda.nodeapi.CURRENT_RPC_USER import net.corda.nodeapi.PermissionException import net.corda.nodeapi.User @@ -63,7 +63,7 @@ class CordaRPCOpsImplTest { startFlowPermission() ))) - databaseTransaction(aliceNode.database) { + aliceNode.database.transaction { stateMachineUpdates = rpc.stateMachinesAndUpdates().second transactions = rpc.verifiedTransactions().second vaultUpdates = rpc.vaultAndUpdates().second @@ -76,7 +76,7 @@ class CordaRPCOpsImplTest { val ref = OpaqueBytes(ByteArray(1) { 1 }) // Check the monitoring service wallet is empty - databaseTransaction(aliceNode.database) { + aliceNode.database.transaction { assertFalse(aliceNode.services.vaultService.unconsumedStates().iterator().hasNext()) } diff --git a/node/src/test/kotlin/net/corda/node/messaging/AttachmentTests.kt b/node/src/test/kotlin/net/corda/node/messaging/AttachmentTests.kt index 1975010503..f0322fb400 100644 --- a/node/src/test/kotlin/net/corda/node/messaging/AttachmentTests.kt +++ b/node/src/test/kotlin/net/corda/node/messaging/AttachmentTests.kt @@ -14,8 +14,8 @@ import net.corda.node.services.network.NetworkMapService import net.corda.node.services.persistence.NodeAttachmentService import net.corda.node.services.persistence.schemas.AttachmentEntity import net.corda.node.services.transactions.SimpleNotaryService -import net.corda.node.utilities.databaseTransaction import net.corda.testing.node.MockNetwork +import net.corda.node.utilities.transaction import net.corda.testing.node.makeTestDataSourceProperties import org.jetbrains.exposed.sql.Database import org.junit.Before @@ -60,7 +60,7 @@ class AttachmentTests { val (n0, n1) = network.createTwoNodes() // Insert an attachment into node zero's store directly. - val id = databaseTransaction(n0.database) { + val id = n0.database.transaction { n0.storage.attachments.importAttachment(ByteArrayInputStream(fakeAttachment())) } @@ -71,7 +71,7 @@ class AttachmentTests { assertEquals(0, f1.resultFuture.getOrThrow().fromDisk.size) // Verify it was inserted into node one's store. - val attachment = databaseTransaction(n1.database) { + val attachment = n1.database.transaction { n1.storage.attachments.openAttachment(id)!! } @@ -118,7 +118,7 @@ class AttachmentTests { val attachment = fakeAttachment() // Insert an attachment into node zero's store directly. - val id = databaseTransaction(n0.database) { + val id = n0.database.transaction { n0.storage.attachments.importAttachment(ByteArrayInputStream(attachment)) } @@ -129,7 +129,7 @@ class AttachmentTests { val corruptAttachment = AttachmentEntity() corruptAttachment.attId = id corruptAttachment.content = attachment - databaseTransaction(n0.database) { + n0.database.transaction { (n0.storage.attachments as NodeAttachmentService).session.update(corruptAttachment) } diff --git a/node/src/test/kotlin/net/corda/node/messaging/TwoPartyTradeFlowTests.kt b/node/src/test/kotlin/net/corda/node/messaging/TwoPartyTradeFlowTests.kt index 7096ce7622..7e479e39a4 100644 --- a/node/src/test/kotlin/net/corda/node/messaging/TwoPartyTradeFlowTests.kt +++ b/node/src/test/kotlin/net/corda/node/messaging/TwoPartyTradeFlowTests.kt @@ -28,7 +28,7 @@ import net.corda.node.services.config.NodeConfiguration import net.corda.node.services.persistence.DBTransactionStorage import net.corda.node.services.persistence.StorageServiceImpl import net.corda.node.services.persistence.checkpoints -import net.corda.node.utilities.databaseTransaction +import net.corda.node.utilities.transaction import net.corda.testing.* import net.corda.testing.node.InMemoryMessagingNetwork import net.corda.testing.node.MockNetwork @@ -89,11 +89,11 @@ class TwoPartyTradeFlowTests { aliceNode.disableDBCloseOnStop() bobNode.disableDBCloseOnStop() - databaseTransaction(bobNode.database) { + bobNode.database.transaction { bobNode.services.fillWithSomeTestCash(2000.DOLLARS, outputNotary = notaryNode.info.notaryIdentity) } - val alicesFakePaper = databaseTransaction(aliceNode.database) { + val alicesFakePaper = aliceNode.database.transaction { fillUpForSeller(false, aliceNode.info.legalIdentity.owningKey, 1200.DOLLARS `issued by` DUMMY_CASH_ISSUER, null, notaryNode.info.notaryIdentity).second } @@ -110,11 +110,11 @@ class TwoPartyTradeFlowTests { aliceNode.stop() bobNode.stop() - databaseTransaction(aliceNode.database) { + aliceNode.database.transaction { assertThat(aliceNode.checkpointStorage.checkpoints()).isEmpty() } aliceNode.manuallyCloseDB() - databaseTransaction(bobNode.database) { + bobNode.database.transaction { assertThat(bobNode.checkpointStorage.checkpoints()).isEmpty() } bobNode.manuallyCloseDB() @@ -137,10 +137,10 @@ class TwoPartyTradeFlowTests { net.runNetwork() // Clear network map registration messages - databaseTransaction(bobNode.database) { + bobNode.database.transaction { bobNode.services.fillWithSomeTestCash(2000.DOLLARS, outputNotary = notaryNode.info.notaryIdentity) } - val alicesFakePaper = databaseTransaction(aliceNode.database) { + val alicesFakePaper = aliceNode.database.transaction { fillUpForSeller(false, aliceNode.info.legalIdentity.owningKey, 1200.DOLLARS `issued by` DUMMY_CASH_ISSUER, null, notaryNode.info.notaryIdentity).second } @@ -160,12 +160,12 @@ class TwoPartyTradeFlowTests { bobNode.pumpReceive() // OK, now Bob has sent the partial transaction back to Alice and is waiting for Alice's signature. - databaseTransaction(bobNode.database) { + bobNode.database.transaction { assertThat(bobNode.checkpointStorage.checkpoints()).hasSize(1) } val storage = bobNode.storage.validatedTransactions - val bobTransactionsBeforeCrash = databaseTransaction(bobNode.database) { + val bobTransactionsBeforeCrash = bobNode.database.transaction { (storage as DBTransactionStorage).transactions } assertThat(bobTransactionsBeforeCrash).isNotEmpty @@ -197,14 +197,14 @@ class TwoPartyTradeFlowTests { assertThat(bobFuture.getOrThrow()).isEqualTo(aliceFuture.getOrThrow()) assertThat(bobNode.smm.findStateMachines(Buyer::class.java)).isEmpty() - databaseTransaction(bobNode.database) { + bobNode.database.transaction { assertThat(bobNode.checkpointStorage.checkpoints()).isEmpty() } - databaseTransaction(aliceNode.database) { + aliceNode.database.transaction { assertThat(aliceNode.checkpointStorage.checkpoints()).isEmpty() } - databaseTransaction(bobNode.database) { + bobNode.database.transaction { val restoredBobTransactions = bobTransactionsBeforeCrash.filter { bobNode.storage.validatedTransactions.getTransaction(it.id) != null } assertThat(restoredBobTransactions).containsAll(bobTransactionsBeforeCrash) } @@ -255,7 +255,7 @@ class TwoPartyTradeFlowTests { it.write("Our commercial paper is top notch stuff".toByteArray()) it.closeEntry() } - val attachmentID = databaseTransaction(aliceNode.database) { + val attachmentID = aliceNode.database.transaction { attachment(ByteArrayInputStream(stream.toByteArray())) } @@ -264,7 +264,7 @@ class TwoPartyTradeFlowTests { DUMMY_CASH_ISSUER.party, notaryNode.info.notaryIdentity).second val bobsSignedTxns = insertFakeTransactions(bobsFakeCash, bobNode, notaryNode, bobNode.services.legalIdentityKey, extraKey) - val alicesFakePaper = databaseTransaction(aliceNode.database) { + val alicesFakePaper = aliceNode.database.transaction { fillUpForSeller(false, aliceNode.info.legalIdentity.owningKey, 1200.DOLLARS `issued by` DUMMY_CASH_ISSUER, attachmentID, notaryNode.info.notaryIdentity).second } @@ -294,7 +294,7 @@ class TwoPartyTradeFlowTests { } // Bob has downloaded the attachment. - databaseTransaction(bobNode.database) { + bobNode.database.transaction { bobNode.storage.attachments.openAttachment(attachmentID)!!.openAsJAR().use { it.nextJarEntry val contents = it.reader().readText() @@ -356,7 +356,7 @@ class TwoPartyTradeFlowTests { it.write("Our commercial paper is top notch stuff".toByteArray()) it.closeEntry() } - val attachmentID = databaseTransaction(aliceNode.database) { + val attachmentID = aliceNode.database.transaction { attachment(ByteArrayInputStream(stream.toByteArray())) } @@ -365,7 +365,7 @@ class TwoPartyTradeFlowTests { notaryNode.info.notaryIdentity).second insertFakeTransactions(bobsFakeCash, bobNode, notaryNode) - val alicesFakePaper = databaseTransaction(aliceNode.database) { + val alicesFakePaper = aliceNode.database.transaction { fillUpForSeller(false, aliceNode.info.legalIdentity.owningKey, 1200.DOLLARS `issued by` DUMMY_CASH_ISSUER, attachmentID, notaryNode.info.notaryIdentity).second } @@ -375,11 +375,7 @@ class TwoPartyTradeFlowTests { net.runNetwork() // Clear network map registration messages val aliceTxStream = aliceNode.storage.validatedTransactions.track().second - // TODO: Had to put this temp val here to avoid compiler crash. Put back inside [databaseTransaction] if the compiler stops crashing. - val aliceMappingsStorage = aliceNode.storage.stateMachineRecordedTransactionMapping - val aliceTxMappings = databaseTransaction(aliceNode.database) { - aliceMappingsStorage.track().second - } + val aliceTxMappings = with(aliceNode) { database.transaction { storage.stateMachineRecordedTransactionMapping.track().second } } val aliceSmId = runBuyerAndSeller(notaryNode, aliceNode, bobNode, "alice's paper".outputStateAndRef()).sellerId @@ -463,7 +459,7 @@ class TwoPartyTradeFlowTests { val bobsBadCash = fillUpForBuyer(bobError, bobKey.public, DUMMY_CASH_ISSUER.party, notaryNode.info.notaryIdentity).second - val alicesFakePaper = databaseTransaction(aliceNode.database) { + val alicesFakePaper = aliceNode.database.transaction { fillUpForSeller(aliceError, aliceNode.info.legalIdentity.owningKey, 1200.DOLLARS `issued by` issuer, null, notaryNode.info.notaryIdentity).second } @@ -496,13 +492,13 @@ class TwoPartyTradeFlowTests { notaryNode: MockNetwork.MockNode, vararg extraKeys: KeyPair): Map { val signed: List = signAll(wtxToSign, extraKeys.toList() + notaryNode.services.notaryIdentityKey + DUMMY_CASH_ISSUER_KEY) - return databaseTransaction(node.database) { + return node.database.transaction { node.services.recordTransactions(signed) val validatedTransactions = node.services.storageService.validatedTransactions if (validatedTransactions is RecordingTransactionStorage) { validatedTransactions.records.clear() } - return@databaseTransaction signed.associateBy { it.id } + signed.associateBy { it.id } } } @@ -581,7 +577,7 @@ class TwoPartyTradeFlowTests { class RecordingTransactionStorage(val database: Database, val delegate: TransactionStorage) : TransactionStorage { override fun track(): Pair, Observable> { - return databaseTransaction(database) { + return database.transaction { delegate.track() } } @@ -591,7 +587,7 @@ class TwoPartyTradeFlowTests { get() = delegate.updates override fun addTransaction(transaction: SignedTransaction): Boolean { - databaseTransaction(database) { + database.transaction { records.add(TxRecord.Add(transaction)) delegate.addTransaction(transaction) } @@ -599,7 +595,7 @@ class TwoPartyTradeFlowTests { } override fun getTransaction(id: SecureHash): SignedTransaction? { - return databaseTransaction(database) { + return database.transaction { records.add(TxRecord.Get(id)) delegate.getTransaction(id) } diff --git a/node/src/test/kotlin/net/corda/node/services/HibernateObserverTests.kt b/node/src/test/kotlin/net/corda/node/services/HibernateObserverTests.kt index d2e0a7ca6a..eb985f5a56 100644 --- a/node/src/test/kotlin/net/corda/node/services/HibernateObserverTests.kt +++ b/node/src/test/kotlin/net/corda/node/services/HibernateObserverTests.kt @@ -14,7 +14,7 @@ import net.corda.core.utilities.LogHelper import net.corda.node.services.api.SchemaService import net.corda.node.services.schema.HibernateObserver import net.corda.node.utilities.configureDatabase -import net.corda.node.utilities.databaseTransaction +import net.corda.node.utilities.transaction import net.corda.testing.MEGA_CORP import net.corda.testing.node.makeTestDataSourceProperties import org.hibernate.annotations.Cascade @@ -110,7 +110,7 @@ class HibernateObserverTests { @Suppress("UNUSED_VARIABLE") val observer = HibernateObserver(rawUpdatesPublisher, schemaService) - databaseTransaction(database) { + database.transaction { rawUpdatesPublisher.onNext(Vault.Update(emptySet(), setOf(StateAndRef(TransactionState(TestState(), MEGA_CORP), StateRef(SecureHash.sha256("dummy"), 0))))) val parentRowCountResult = TransactionManager.current().connection.prepareStatement("select count(*) from contract_Parents").executeQuery() parentRowCountResult.next() diff --git a/node/src/test/kotlin/net/corda/node/services/InMemoryNetworkMapCacheTest.kt b/node/src/test/kotlin/net/corda/node/services/InMemoryNetworkMapCacheTest.kt index acac6c76ee..932b9dc859 100644 --- a/node/src/test/kotlin/net/corda/node/services/InMemoryNetworkMapCacheTest.kt +++ b/node/src/test/kotlin/net/corda/node/services/InMemoryNetworkMapCacheTest.kt @@ -3,7 +3,7 @@ package net.corda.node.services import net.corda.core.getOrThrow import net.corda.core.node.services.ServiceInfo import net.corda.node.services.network.NetworkMapService -import net.corda.node.utilities.databaseTransaction +import net.corda.node.utilities.transaction import net.corda.testing.node.MockNetwork import org.junit.Test import java.math.BigInteger @@ -30,7 +30,7 @@ class InMemoryNetworkMapCacheTest { // Node A currently knows only about itself, so this returns node A assertEquals(nodeA.netMapCache.getNodeByLegalIdentityKey(nodeA.info.legalIdentity.owningKey), nodeA.info) - databaseTransaction(nodeA.database) { + nodeA.database.transaction { nodeA.netMapCache.addNode(nodeB.info) } // The details of node B write over those for node A diff --git a/node/src/test/kotlin/net/corda/node/services/NodeSchedulerServiceTest.kt b/node/src/test/kotlin/net/corda/node/services/NodeSchedulerServiceTest.kt index 6c3b906c57..64c2dc90bd 100644 --- a/node/src/test/kotlin/net/corda/node/services/NodeSchedulerServiceTest.kt +++ b/node/src/test/kotlin/net/corda/node/services/NodeSchedulerServiceTest.kt @@ -17,7 +17,7 @@ import net.corda.core.utilities.ALICE_KEY import net.corda.node.utilities.AddOrRemove import net.corda.node.utilities.AffinityExecutor import net.corda.node.utilities.configureDatabase -import net.corda.node.utilities.databaseTransaction +import net.corda.node.utilities.transaction import net.corda.testing.node.InMemoryMessagingNetwork import net.corda.testing.node.MockKeyManagementService import net.corda.testing.node.TestClock @@ -78,7 +78,7 @@ class NodeSchedulerServiceTest : SingletonSerializeAsToken() { dataSource = dataSourceAndDatabase.first database = dataSourceAndDatabase.second - databaseTransaction(database) { + database.transaction { val kms = MockKeyManagementService(ALICE_KEY) val mockMessagingService = InMemoryMessagingNetwork(false).InMemoryMessaging(false, InMemoryMessagingNetwork.PeerHandle(0, "None"), AffinityExecutor.ServiceAffinityExecutor("test", 1), database) services = object : MockServiceHubInternal(overrideClock = testClock, keyManagement = kms, net = mockMessagingService), TestReference { @@ -235,7 +235,7 @@ class NodeSchedulerServiceTest : SingletonSerializeAsToken() { scheduleTX(time, 3) backgroundExecutor.execute { schedulerGatedExecutor.waitAndRun() } - databaseTransaction(database) { + database.transaction { scheduler.unscheduleStateActivity(scheduledRef1!!.ref) } testClock.advanceBy(1.days) @@ -253,7 +253,7 @@ class NodeSchedulerServiceTest : SingletonSerializeAsToken() { backgroundExecutor.execute { schedulerGatedExecutor.waitAndRun() } assertThat(calls).isEqualTo(0) - databaseTransaction(database) { + database.transaction { scheduler.unscheduleStateActivity(scheduledRef1!!.ref) } testClock.advanceBy(1.days) @@ -264,7 +264,7 @@ class NodeSchedulerServiceTest : SingletonSerializeAsToken() { private fun scheduleTX(instant: Instant, increment: Int = 1): ScheduledStateRef? { var scheduledRef: ScheduledStateRef? = null - databaseTransaction(database) { + database.transaction { apply { val freshKey = services.keyManagementService.freshKey() val state = TestState(factory.create(TestFlowLogic::class.java, increment), instant) diff --git a/node/src/test/kotlin/net/corda/node/services/PersistentNetworkMapServiceTest.kt b/node/src/test/kotlin/net/corda/node/services/PersistentNetworkMapServiceTest.kt index 40b6305926..aae8eb0e46 100644 --- a/node/src/test/kotlin/net/corda/node/services/PersistentNetworkMapServiceTest.kt +++ b/node/src/test/kotlin/net/corda/node/services/PersistentNetworkMapServiceTest.kt @@ -6,7 +6,7 @@ import net.corda.node.services.api.ServiceHubInternal import net.corda.node.services.config.NodeConfiguration import net.corda.node.services.network.NetworkMapService import net.corda.node.services.network.PersistentNetworkMapService -import net.corda.node.utilities.databaseTransaction +import net.corda.node.utilities.transaction import net.corda.testing.node.MockNetwork import net.corda.testing.node.MockNetwork.MockNode import java.math.BigInteger @@ -24,7 +24,7 @@ class PersistentNetworkMapServiceTest : AbstractNetworkMapServiceTest().values.first() } - val stateFromB = databaseTransaction(nodeB.database) { + val stateFromB = nodeB.database.transaction { nodeB.services.vaultService.linearHeadsOfType().values.first() } assertEquals(stateFromA, stateFromB, "Must be same copy on both nodes") @@ -133,10 +133,10 @@ class ScheduledFlowTests { nodeB.services.startFlow(InsertInitialStateFlow(nodeA.info.legalIdentity)) } net.waitQuiescent() - val statesFromA = databaseTransaction(nodeA.database) { + val statesFromA = nodeA.database.transaction { nodeA.services.vaultService.linearHeadsOfType() } - val statesFromB = databaseTransaction(nodeB.database) { + val statesFromB = nodeB.database.transaction { nodeB.services.vaultService.linearHeadsOfType() } assertEquals(2 * N, statesFromA.count(), "Expect all states to be present") diff --git a/node/src/test/kotlin/net/corda/node/services/VaultWithCashTest.kt b/node/src/test/kotlin/net/corda/node/services/VaultWithCashTest.kt index d3b2516b25..1c648414f2 100644 --- a/node/src/test/kotlin/net/corda/node/services/VaultWithCashTest.kt +++ b/node/src/test/kotlin/net/corda/node/services/VaultWithCashTest.kt @@ -15,7 +15,7 @@ import net.corda.core.utilities.DUMMY_NOTARY import net.corda.core.utilities.DUMMY_NOTARY_KEY import net.corda.core.utilities.LogHelper import net.corda.node.utilities.configureDatabase -import net.corda.node.utilities.databaseTransaction +import net.corda.node.utilities.transaction import net.corda.testing.BOB_PUBKEY import net.corda.testing.MEGA_CORP import net.corda.testing.MEGA_CORP_KEY @@ -49,7 +49,7 @@ class VaultWithCashTest { val dataSourceAndDatabase = configureDatabase(dataSourceProps) dataSource = dataSourceAndDatabase.first database = dataSourceAndDatabase.second - databaseTransaction(database) { + database.transaction { services = object : MockServices() { override val vaultService: VaultService = makeVaultService(dataSourceProps) @@ -72,7 +72,7 @@ class VaultWithCashTest { @Test fun splits() { - databaseTransaction(database) { + database.transaction { // Fix the PRNG so that we get the same splits every time. services.fillWithSomeTestCash(100.DOLLARS, DUMMY_NOTARY, 3, 3, Random(0L)) @@ -90,7 +90,7 @@ class VaultWithCashTest { @Test fun `issue and spend total correctly and irrelevant ignored`() { - databaseTransaction(database) { + database.transaction { // A tx that sends us money. val freshKey = services.keyManagementService.freshKey() val usefulTX = TransactionType.General.Builder(null).apply { @@ -131,7 +131,7 @@ class VaultWithCashTest { fun `issue and attempt double spend`() { val freshKey = services.keyManagementService.freshKey() - databaseTransaction(database) { + database.transaction { // A tx that sends us money. services.fillWithSomeTestCash(100.DOLLARS, DUMMY_NOTARY, 10, 10, Random(0L), issuedBy = MEGA_CORP.ref(1), @@ -147,7 +147,7 @@ class VaultWithCashTest { val countDown = CountDownLatch(2) // 1st tx that spends our money. backgroundExecutor.submit { - databaseTransaction(database) { + database.transaction { try { val txn1 = TransactionType.General.Builder(DUMMY_NOTARY).apply { @@ -179,7 +179,7 @@ class VaultWithCashTest { // 2nd tx that attempts to spend same money backgroundExecutor.submit { - databaseTransaction(database) { + database.transaction { try { val txn2 = TransactionType.General.Builder(DUMMY_NOTARY).apply { @@ -211,7 +211,7 @@ class VaultWithCashTest { } countDown.await() - databaseTransaction(database) { + database.transaction { println("Cash balance: ${vault.cashBalances[USD]}") assertThat(vault.cashBalances[USD]).isIn(DOLLARS(20), DOLLARS(40)) } @@ -219,7 +219,7 @@ class VaultWithCashTest { @Test fun `branching LinearStates fails to verify`() { - databaseTransaction(database) { + database.transaction { val freshKey = services.keyManagementService.freshKey() val linearId = UniqueIdentifier() @@ -239,7 +239,7 @@ class VaultWithCashTest { @Test fun `sequencing LinearStates works`() { - databaseTransaction(database) { + database.transaction { val freshKey = services.keyManagementService.freshKey() val linearId = UniqueIdentifier() @@ -274,7 +274,7 @@ class VaultWithCashTest { fun `spending cash in vault of mixed state types works`() { val freshKey = services.keyManagementService.freshKey() - databaseTransaction(database) { + database.transaction { services.fillWithSomeTestCash(100.DOLLARS, DUMMY_NOTARY, 3, 3, Random(0L), ownedBy = freshKey.public) services.fillWithSomeTestCash(100.SWISS_FRANCS, DUMMY_NOTARY, 2, 2, Random(0L)) services.fillWithSomeTestCash(100.POUNDS, DUMMY_NOTARY, 1, 1, Random(0L)) @@ -286,7 +286,7 @@ class VaultWithCashTest { deals.forEach { println(it.state.data.ref) } } - databaseTransaction(database) { + database.transaction { // A tx that spends our money. val spendTX = TransactionType.General.Builder(DUMMY_NOTARY).apply { vault.generateSpend(this, 80.DOLLARS, BOB_PUBKEY) @@ -307,7 +307,7 @@ class VaultWithCashTest { fun `consuming multiple contract state types in same transaction`() { val freshKey = services.keyManagementService.freshKey() - databaseTransaction(database) { + database.transaction { services.fillWithSomeTestDeals(listOf("123", "456", "789")) val deals = vault.unconsumedStates().toList() diff --git a/node/src/test/kotlin/net/corda/node/services/database/RequeryConfigurationTest.kt b/node/src/test/kotlin/net/corda/node/services/database/RequeryConfigurationTest.kt index ed9fe6ae4c..37956270ca 100644 --- a/node/src/test/kotlin/net/corda/node/services/database/RequeryConfigurationTest.kt +++ b/node/src/test/kotlin/net/corda/node/services/database/RequeryConfigurationTest.kt @@ -23,7 +23,7 @@ import net.corda.node.services.vault.schemas.VaultCashBalancesEntity import net.corda.node.services.vault.schemas.VaultSchema import net.corda.node.services.vault.schemas.VaultStatesEntity import net.corda.node.utilities.configureDatabase -import net.corda.node.utilities.databaseTransaction +import net.corda.node.utilities.transaction import net.corda.testing.node.makeTestDataSourceProperties import org.assertj.core.api.Assertions import org.jetbrains.exposed.sql.Database @@ -61,14 +61,14 @@ class RequeryConfigurationTest { fun `transaction inserts in same DB transaction scope across two persistence engines`() { val txn = newTransaction() - databaseTransaction(database) { + database.transaction { transactionStorage.addTransaction(txn) requerySession.withTransaction { insert(createVaultStateEntity(txn)) } } - databaseTransaction(database) { + database.transaction { Assertions.assertThat(transactionStorage.transactions).containsOnly(txn) requerySession.withTransaction { val result = select(VaultSchema.VaultStates::class) where (VaultSchema.VaultStates::txId eq txn.tx.inputs[0].txhash.toString()) @@ -81,7 +81,7 @@ class RequeryConfigurationTest { fun `transaction operations in same DB transaction scope across two persistence engines`() { val txn = newTransaction() - databaseTransaction(database) { + database.transaction { transactionStorage.addTransaction(txn) requerySession.withTransaction { upsert(createCashBalance()) @@ -90,7 +90,7 @@ class RequeryConfigurationTest { } } - databaseTransaction(database) { + database.transaction { Assertions.assertThat(transactionStorage.transactions).containsOnly(txn) requerySession.withTransaction { val cashQuery = select(VaultSchema.VaultCashBalances::class) where (VaultSchema.VaultCashBalances::currency eq "GBP") @@ -105,7 +105,7 @@ class RequeryConfigurationTest { fun `transaction rollback in same DB transaction scope across two persistence engines`() { val txn = newTransaction() - databaseTransaction(database) { + database.transaction { transactionStorage.addTransaction(txn) requerySession.withTransaction { insert(createVaultStateEntity(txn)) @@ -113,7 +113,7 @@ class RequeryConfigurationTest { rollback() } - databaseTransaction(database) { + database.transaction { Assertions.assertThat(transactionStorage.transactions).isEmpty() requerySession.withTransaction { val result = select(VaultSchema.VaultStates::class) where (VaultSchema.VaultStates::txId eq txn.tx.inputs[0].txhash.toString()) @@ -145,13 +145,13 @@ class RequeryConfigurationTest { } private fun newTransactionStorage() { - databaseTransaction(database) { + database.transaction { transactionStorage = DBTransactionStorage() } } private fun newRequeryStorage(dataSourceProperties: Properties) { - databaseTransaction(database) { + database.transaction { val configuration = RequeryConfiguration(dataSourceProperties, true) requerySession = configuration.sessionForModel(Models.VAULT) } diff --git a/node/src/test/kotlin/net/corda/node/services/messaging/ArtemisMessagingTests.kt b/node/src/test/kotlin/net/corda/node/services/messaging/ArtemisMessagingTests.kt index 68cb7d959c..b47d96125d 100644 --- a/node/src/test/kotlin/net/corda/node/services/messaging/ArtemisMessagingTests.kt +++ b/node/src/test/kotlin/net/corda/node/services/messaging/ArtemisMessagingTests.kt @@ -22,7 +22,7 @@ import net.corda.node.services.network.NetworkMapService import net.corda.node.services.transactions.PersistentUniquenessProvider import net.corda.node.utilities.AffinityExecutor.ServiceAffinityExecutor import net.corda.node.utilities.configureDatabase -import net.corda.node.utilities.databaseTransaction +import net.corda.node.utilities.transaction import net.corda.testing.MOCK_NODE_VERSION_INFO import net.corda.testing.TestNodeConfiguration import net.corda.testing.freeLocalHostAndPort @@ -220,7 +220,7 @@ class ArtemisMessagingTests { } private fun createMessagingClient(server: HostAndPort = hostAndPort): NodeMessagingClient { - return databaseTransaction(database) { + return database.transaction { NodeMessagingClient( config, MOCK_NODE_VERSION_INFO, diff --git a/node/src/test/kotlin/net/corda/node/services/persistence/DBCheckpointStorageTests.kt b/node/src/test/kotlin/net/corda/node/services/persistence/DBCheckpointStorageTests.kt index 260efba30d..095f20f9cb 100644 --- a/node/src/test/kotlin/net/corda/node/services/persistence/DBCheckpointStorageTests.kt +++ b/node/src/test/kotlin/net/corda/node/services/persistence/DBCheckpointStorageTests.kt @@ -7,7 +7,7 @@ import net.corda.node.services.api.Checkpoint import net.corda.node.services.api.CheckpointStorage import net.corda.node.services.transactions.PersistentUniquenessProvider import net.corda.node.utilities.configureDatabase -import net.corda.node.utilities.databaseTransaction +import net.corda.node.utilities.transaction import net.corda.testing.node.makeTestDataSourceProperties import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatExceptionOfType @@ -49,14 +49,14 @@ class DBCheckpointStorageTests { @Test fun `add new checkpoint`() { val checkpoint = newCheckpoint() - databaseTransaction(database) { + database.transaction { checkpointStorage.addCheckpoint(checkpoint) } - databaseTransaction(database) { + database.transaction { assertThat(checkpointStorage.checkpoints()).containsExactly(checkpoint) } newCheckpointStorage() - databaseTransaction(database) { + database.transaction { assertThat(checkpointStorage.checkpoints()).containsExactly(checkpoint) } } @@ -64,17 +64,17 @@ class DBCheckpointStorageTests { @Test fun `remove checkpoint`() { val checkpoint = newCheckpoint() - databaseTransaction(database) { + database.transaction { checkpointStorage.addCheckpoint(checkpoint) } - databaseTransaction(database) { + database.transaction { checkpointStorage.removeCheckpoint(checkpoint) } - databaseTransaction(database) { + database.transaction { assertThat(checkpointStorage.checkpoints()).isEmpty() } newCheckpointStorage() - databaseTransaction(database) { + database.transaction { assertThat(checkpointStorage.checkpoints()).isEmpty() } } @@ -83,16 +83,16 @@ class DBCheckpointStorageTests { fun `add and remove checkpoint in single commit operate`() { val checkpoint = newCheckpoint() val checkpoint2 = newCheckpoint() - databaseTransaction(database) { + database.transaction { checkpointStorage.addCheckpoint(checkpoint) checkpointStorage.addCheckpoint(checkpoint2) checkpointStorage.removeCheckpoint(checkpoint) } - databaseTransaction(database) { + database.transaction { assertThat(checkpointStorage.checkpoints()).containsExactly(checkpoint2) } newCheckpointStorage() - databaseTransaction(database) { + database.transaction { assertThat(checkpointStorage.checkpoints()).containsExactly(checkpoint2) } } @@ -100,7 +100,7 @@ class DBCheckpointStorageTests { @Test fun `remove unknown checkpoint`() { val checkpoint = newCheckpoint() - databaseTransaction(database) { + database.transaction { assertThatExceptionOfType(IllegalArgumentException::class.java).isThrownBy { checkpointStorage.removeCheckpoint(checkpoint) } @@ -110,21 +110,21 @@ class DBCheckpointStorageTests { @Test fun `add two checkpoints then remove first one`() { val firstCheckpoint = newCheckpoint() - databaseTransaction(database) { + database.transaction { checkpointStorage.addCheckpoint(firstCheckpoint) } val secondCheckpoint = newCheckpoint() - databaseTransaction(database) { + database.transaction { checkpointStorage.addCheckpoint(secondCheckpoint) } - databaseTransaction(database) { + database.transaction { checkpointStorage.removeCheckpoint(firstCheckpoint) } - databaseTransaction(database) { + database.transaction { assertThat(checkpointStorage.checkpoints()).containsExactly(secondCheckpoint) } newCheckpointStorage() - databaseTransaction(database) { + database.transaction { assertThat(checkpointStorage.checkpoints()).containsExactly(secondCheckpoint) } } @@ -132,26 +132,26 @@ class DBCheckpointStorageTests { @Test fun `add checkpoint and then remove after 'restart'`() { val originalCheckpoint = newCheckpoint() - databaseTransaction(database) { + database.transaction { checkpointStorage.addCheckpoint(originalCheckpoint) } newCheckpointStorage() - val reconstructedCheckpoint = databaseTransaction(database) { + val reconstructedCheckpoint = database.transaction { checkpointStorage.checkpoints().single() } - databaseTransaction(database) { + database.transaction { assertThat(reconstructedCheckpoint).isEqualTo(originalCheckpoint).isNotSameAs(originalCheckpoint) } - databaseTransaction(database) { + database.transaction { checkpointStorage.removeCheckpoint(reconstructedCheckpoint) } - databaseTransaction(database) { + database.transaction { assertThat(checkpointStorage.checkpoints()).isEmpty() } } private fun newCheckpointStorage() { - databaseTransaction(database) { + database.transaction { checkpointStorage = DBCheckpointStorage() } } diff --git a/node/src/test/kotlin/net/corda/node/services/persistence/DBTransactionStorageTests.kt b/node/src/test/kotlin/net/corda/node/services/persistence/DBTransactionStorageTests.kt index 8aee0b23d0..981a1ed894 100644 --- a/node/src/test/kotlin/net/corda/node/services/persistence/DBTransactionStorageTests.kt +++ b/node/src/test/kotlin/net/corda/node/services/persistence/DBTransactionStorageTests.kt @@ -12,7 +12,7 @@ import net.corda.core.utilities.DUMMY_NOTARY import net.corda.core.utilities.LogHelper import net.corda.node.services.transactions.PersistentUniquenessProvider import net.corda.node.utilities.configureDatabase -import net.corda.node.utilities.databaseTransaction +import net.corda.node.utilities.transaction import net.corda.testing.node.makeTestDataSourceProperties import org.assertj.core.api.Assertions.assertThat import org.jetbrains.exposed.sql.Database @@ -45,14 +45,14 @@ class DBTransactionStorageTests { @Test fun `empty store`() { - databaseTransaction(database) { + database.transaction { assertThat(transactionStorage.getTransaction(newTransaction().id)).isNull() } - databaseTransaction(database) { + database.transaction { assertThat(transactionStorage.transactions).isEmpty() } newTransactionStorage() - databaseTransaction(database) { + database.transaction { assertThat(transactionStorage.transactions).isEmpty() } } @@ -60,16 +60,16 @@ class DBTransactionStorageTests { @Test fun `one transaction`() { val transaction = newTransaction() - databaseTransaction(database) { + database.transaction { transactionStorage.addTransaction(transaction) } assertTransactionIsRetrievable(transaction) - databaseTransaction(database) { + database.transaction { assertThat(transactionStorage.transactions).containsExactly(transaction) } newTransactionStorage() assertTransactionIsRetrievable(transaction) - databaseTransaction(database) { + database.transaction { assertThat(transactionStorage.transactions).containsExactly(transaction) } } @@ -78,16 +78,16 @@ class DBTransactionStorageTests { fun `two transactions across restart`() { val firstTransaction = newTransaction() val secondTransaction = newTransaction() - databaseTransaction(database) { + database.transaction { transactionStorage.addTransaction(firstTransaction) } newTransactionStorage() - databaseTransaction(database) { + database.transaction { transactionStorage.addTransaction(secondTransaction) } assertTransactionIsRetrievable(firstTransaction) assertTransactionIsRetrievable(secondTransaction) - databaseTransaction(database) { + database.transaction { assertThat(transactionStorage.transactions).containsOnly(firstTransaction, secondTransaction) } } @@ -96,13 +96,13 @@ class DBTransactionStorageTests { fun `two transactions with rollback`() { val firstTransaction = newTransaction() val secondTransaction = newTransaction() - databaseTransaction(database) { + database.transaction { transactionStorage.addTransaction(firstTransaction) transactionStorage.addTransaction(secondTransaction) rollback() } - databaseTransaction(database) { + database.transaction { assertThat(transactionStorage.transactions).isEmpty() } } @@ -111,13 +111,13 @@ class DBTransactionStorageTests { fun `two transactions in same DB transaction scope`() { val firstTransaction = newTransaction() val secondTransaction = newTransaction() - databaseTransaction(database) { + database.transaction { transactionStorage.addTransaction(firstTransaction) transactionStorage.addTransaction(secondTransaction) } assertTransactionIsRetrievable(firstTransaction) assertTransactionIsRetrievable(secondTransaction) - databaseTransaction(database) { + database.transaction { assertThat(transactionStorage.transactions).containsOnly(firstTransaction, secondTransaction) } } @@ -126,7 +126,7 @@ class DBTransactionStorageTests { fun `updates are fired`() { val future = transactionStorage.updates.toFuture() val expected = newTransaction() - databaseTransaction(database) { + database.transaction { transactionStorage.addTransaction(expected) } val actual = future.get(1, TimeUnit.SECONDS) @@ -134,13 +134,13 @@ class DBTransactionStorageTests { } private fun newTransactionStorage() { - databaseTransaction(database) { + database.transaction { transactionStorage = DBTransactionStorage() } } private fun assertTransactionIsRetrievable(transaction: SignedTransaction) { - databaseTransaction(database) { + database.transaction { assertThat(transactionStorage.getTransaction(transaction.id)).isEqualTo(transaction) } } diff --git a/node/src/test/kotlin/net/corda/node/services/persistence/DataVendingServiceTests.kt b/node/src/test/kotlin/net/corda/node/services/persistence/DataVendingServiceTests.kt index 3d13cf548c..4538d64654 100644 --- a/node/src/test/kotlin/net/corda/node/services/persistence/DataVendingServiceTests.kt +++ b/node/src/test/kotlin/net/corda/node/services/persistence/DataVendingServiceTests.kt @@ -13,7 +13,7 @@ import net.corda.core.transactions.SignedTransaction import net.corda.core.utilities.DUMMY_NOTARY import net.corda.flows.BroadcastTransactionFlow.NotifyTxRequest import net.corda.node.services.persistence.DataVending.Service.NotifyTransactionHandler -import net.corda.node.utilities.databaseTransaction +import net.corda.node.utilities.transaction import net.corda.testing.MEGA_CORP import net.corda.testing.node.MockNetwork import net.corda.testing.node.MockNetwork.MockNode @@ -48,7 +48,7 @@ class DataVendingServiceTests { val registerKey = registerNode.services.legalIdentityKey ptx.signWith(registerKey) val tx = ptx.toSignedTransaction() - databaseTransaction(vaultServiceNode.database) { + vaultServiceNode.database.transaction { assertThat(vaultServiceNode.services.vaultService.unconsumedStates()).isEmpty() registerNode.sendNotifyTx(tx, vaultServiceNode) @@ -78,7 +78,7 @@ class DataVendingServiceTests { val registerKey = registerNode.services.legalIdentityKey ptx.signWith(registerKey) val tx = ptx.toSignedTransaction(false) - databaseTransaction(vaultServiceNode.database) { + vaultServiceNode.database.transaction { assertThat(vaultServiceNode.services.vaultService.unconsumedStates()).isEmpty() registerNode.sendNotifyTx(tx, vaultServiceNode) diff --git a/node/src/test/kotlin/net/corda/node/services/statemachine/StateMachineManagerTests.kt b/node/src/test/kotlin/net/corda/node/services/statemachine/StateMachineManagerTests.kt index 2f8a67987a..330f9e67b3 100644 --- a/node/src/test/kotlin/net/corda/node/services/statemachine/StateMachineManagerTests.kt +++ b/node/src/test/kotlin/net/corda/node/services/statemachine/StateMachineManagerTests.kt @@ -27,7 +27,7 @@ import net.corda.flows.FinalityFlow import net.corda.flows.NotaryFlow import net.corda.node.services.persistence.checkpoints import net.corda.node.services.transactions.ValidatingNotaryService -import net.corda.node.utilities.databaseTransaction +import net.corda.node.utilities.transaction import net.corda.testing.expect import net.corda.testing.expectEvents import net.corda.testing.initiateSingleShotFlow @@ -201,7 +201,7 @@ class StateMachineManagerTests { // Kick off first send and receive node2.services.startFlow(PingPongFlow(node3.info.legalIdentity, payload)) - databaseTransaction(node2.database) { + node2.database.transaction { assertEquals(1, node2.checkpointStorage.checkpoints().size) } // Make sure the add() has finished initial processing. @@ -209,7 +209,7 @@ class StateMachineManagerTests { node2.disableDBCloseOnStop() // Restart node and thus reload the checkpoint and resend the message with same UUID node2.stop() - databaseTransaction(node2.database) { + node2.database.transaction { assertEquals(1, node2.checkpointStorage.checkpoints().size) // confirm checkpoint } val node2b = net.createNode(node1.info.address, node2.id, advertisedServices = *node2.advertisedServices.toTypedArray()) @@ -225,10 +225,10 @@ class StateMachineManagerTests { assertEquals(4, receivedCount, "Flow should have exchanged 4 unique messages")// Two messages each way // can't give a precise value as every addMessageHandler re-runs the undelivered messages assertTrue(sentCount > receivedCount, "Node restart should have retransmitted messages") - databaseTransaction(node2b.database) { + node2b.database.transaction { assertEquals(0, node2b.checkpointStorage.checkpoints().size, "Checkpoints left after restored flow should have ended") } - databaseTransaction(node3.database) { + node3.database.transaction { assertEquals(0, node3.checkpointStorage.checkpoints().size, "Checkpoints left after restored flow should have ended") } assertEquals(payload2, firstAgain.receivedPayload, "Received payload does not match the first value on Node 3") @@ -429,7 +429,7 @@ class StateMachineManagerTests { .isThrownBy { receivingFiber.resultFuture.getOrThrow() } .withMessage("Nothing useful") .withStackTraceContaining(ReceiveFlow::class.java.name) // Make sure the stack trace is that of the receiving flow - databaseTransaction(node2.database) { + node2.database.transaction { assertThat(node2.checkpointStorage.checkpoints()).isEmpty() } diff --git a/node/src/test/kotlin/net/corda/node/services/vault/NodeVaultServiceTest.kt b/node/src/test/kotlin/net/corda/node/services/vault/NodeVaultServiceTest.kt index 22f1f739a7..a90f367498 100644 --- a/node/src/test/kotlin/net/corda/node/services/vault/NodeVaultServiceTest.kt +++ b/node/src/test/kotlin/net/corda/node/services/vault/NodeVaultServiceTest.kt @@ -13,7 +13,7 @@ import net.corda.core.transactions.SignedTransaction import net.corda.core.utilities.DUMMY_NOTARY import net.corda.core.utilities.LogHelper import net.corda.node.utilities.configureDatabase -import net.corda.node.utilities.databaseTransaction +import net.corda.node.utilities.transaction import net.corda.testing.BOC import net.corda.testing.BOC_KEY import net.corda.testing.MEGA_CORP @@ -46,7 +46,7 @@ class NodeVaultServiceTest { val dataSourceAndDatabase = configureDatabase(dataSourceProps) dataSource = dataSourceAndDatabase.first database = dataSourceAndDatabase.second - databaseTransaction(database) { + database.transaction { services = object : MockServices() { override val vaultService: VaultService = makeVaultService(dataSourceProps) @@ -69,7 +69,7 @@ class NodeVaultServiceTest { @Test fun `states not local to instance`() { - databaseTransaction(database) { + database.transaction { services.fillWithSomeTestCash(100.DOLLARS, DUMMY_NOTARY, 3, 3, Random(0L)) @@ -99,7 +99,7 @@ class NodeVaultServiceTest { @Test fun `states for refs`() { - databaseTransaction(database) { + database.transaction { services.fillWithSomeTestCash(100.DOLLARS, DUMMY_NOTARY, 3, 3, Random(0L)) @@ -114,7 +114,7 @@ class NodeVaultServiceTest { @Test fun `states soft locking reserve and release`() { - databaseTransaction(database) { + database.transaction { services.fillWithSomeTestCash(100.DOLLARS, DUMMY_NOTARY, 3, 3, Random(0L)) @@ -161,7 +161,7 @@ class NodeVaultServiceTest { val softLockId2 = UUID.randomUUID() val vaultStates = - databaseTransaction(database) { + database.transaction { assertNull(vault.cashBalances[USD]) services.fillWithSomeTestCash(100.DOLLARS, DUMMY_NOTARY, 3, 3, Random(0L)) } @@ -171,7 +171,7 @@ class NodeVaultServiceTest { // 1st tx locks states backgroundExecutor.submit { try { - databaseTransaction(database) { + database.transaction { vault.softLockReserve(softLockId1, stateRefsToSoftLock) assertThat(vault.softLockedStates(softLockId1)).hasSize(3) } @@ -187,7 +187,7 @@ class NodeVaultServiceTest { backgroundExecutor.submit { try { Thread.sleep(100) // let 1st thread soft lock them 1st - databaseTransaction(database) { + database.transaction { vault.softLockReserve(softLockId2, stateRefsToSoftLock) assertThat(vault.softLockedStates(softLockId2)).hasSize(3) } @@ -200,7 +200,7 @@ class NodeVaultServiceTest { } countDown.await() - databaseTransaction(database) { + database.transaction { val lockStatesId1 = vault.softLockedStates(softLockId1) println("SOFT LOCK #1 final states: $lockStatesId1") assertThat(lockStatesId1.size).isIn(0, 3) @@ -217,7 +217,7 @@ class NodeVaultServiceTest { val softLockId2 = UUID.randomUUID() val vaultStates = - databaseTransaction(database) { + database.transaction { assertNull(vault.cashBalances[USD]) services.fillWithSomeTestCash(100.DOLLARS, DUMMY_NOTARY, 3, 3, Random(0L)) } @@ -225,13 +225,13 @@ class NodeVaultServiceTest { println("State Refs:: $stateRefsToSoftLock") // lock 1st state with LockId1 - databaseTransaction(database) { + database.transaction { vault.softLockReserve(softLockId1, setOf(stateRefsToSoftLock.first())) assertThat(vault.softLockedStates(softLockId1)).hasSize(1) } // attempt to lock all 3 states with LockId2 - databaseTransaction(database) { + database.transaction { assertThatExceptionOfType(StatesNotAvailableException::class.java).isThrownBy( { vault.softLockReserve(softLockId2, stateRefsToSoftLock) } ).withMessageContaining("only 2 rows available").withNoCause() @@ -244,7 +244,7 @@ class NodeVaultServiceTest { val softLockId1 = UUID.randomUUID() val vaultStates = - databaseTransaction(database) { + database.transaction { assertNull(vault.cashBalances[USD]) services.fillWithSomeTestCash(100.DOLLARS, DUMMY_NOTARY, 3, 3, Random(0L)) } @@ -252,13 +252,13 @@ class NodeVaultServiceTest { println("State Refs:: $stateRefsToSoftLock") // lock states with LockId1 - databaseTransaction(database) { + database.transaction { vault.softLockReserve(softLockId1, stateRefsToSoftLock) assertThat(vault.softLockedStates(softLockId1)).hasSize(3) } // attempt to relock same states with LockId1 - databaseTransaction(database) { + database.transaction { vault.softLockReserve(softLockId1, stateRefsToSoftLock) assertThat(vault.softLockedStates(softLockId1)).hasSize(3) } @@ -270,7 +270,7 @@ class NodeVaultServiceTest { val softLockId1 = UUID.randomUUID() val vaultStates = - databaseTransaction(database) { + database.transaction { assertNull(vault.cashBalances[USD]) services.fillWithSomeTestCash(100.DOLLARS, DUMMY_NOTARY, 3, 3, Random(0L)) } @@ -278,13 +278,13 @@ class NodeVaultServiceTest { println("State Refs:: $stateRefsToSoftLock") // lock states with LockId1 - databaseTransaction(database) { + database.transaction { vault.softLockReserve(softLockId1, setOf(stateRefsToSoftLock.first())) assertThat(vault.softLockedStates(softLockId1)).hasSize(1) } // attempt to lock all states with LockId1 (including previously already locked one) - databaseTransaction(database) { + database.transaction { vault.softLockReserve(softLockId1, stateRefsToSoftLock) assertThat(vault.softLockedStates(softLockId1)).hasSize(3) } @@ -292,7 +292,7 @@ class NodeVaultServiceTest { @Test fun `unconsumedStatesForSpending exact amount`() { - databaseTransaction(database) { + database.transaction { services.fillWithSomeTestCash(100.DOLLARS, DUMMY_NOTARY, 1, 1, Random(0L)) @@ -309,7 +309,7 @@ class NodeVaultServiceTest { @Test fun `unconsumedStatesForSpending from two issuer parties`() { - databaseTransaction(database) { + database.transaction { services.fillWithSomeTestCash(100.DOLLARS, DUMMY_NOTARY, 1, 1, Random(0L), issuedBy = (DUMMY_CASH_ISSUER)) services.fillWithSomeTestCash(100.DOLLARS, DUMMY_NOTARY, 1, 1, Random(0L), issuedBy = (BOC.ref(1)), issuerKey = BOC_KEY) @@ -325,7 +325,7 @@ class NodeVaultServiceTest { @Test fun `unconsumedStatesForSpending from specific issuer party and refs`() { - databaseTransaction(database) { + database.transaction { services.fillWithSomeTestCash(100.DOLLARS, DUMMY_NOTARY, 1, 1, Random(0L), issuedBy = (DUMMY_CASH_ISSUER)) services.fillWithSomeTestCash(100.DOLLARS, DUMMY_NOTARY, 1, 1, Random(0L), issuedBy = (BOC.ref(1)), issuerKey = BOC_KEY, ref = OpaqueBytes.of(1)) @@ -346,7 +346,7 @@ class NodeVaultServiceTest { @Test fun `unconsumedStatesForSpending insufficient amount`() { - databaseTransaction(database) { + database.transaction { services.fillWithSomeTestCash(100.DOLLARS, DUMMY_NOTARY, 1, 1, Random(0L)) @@ -362,7 +362,7 @@ class NodeVaultServiceTest { @Test fun `unconsumedStatesForSpending small amount`() { - databaseTransaction(database) { + database.transaction { services.fillWithSomeTestCash(100.DOLLARS, DUMMY_NOTARY, 2, 2, Random(0L)) @@ -379,7 +379,7 @@ class NodeVaultServiceTest { @Test fun `states soft locking query granularity`() { - databaseTransaction(database) { + database.transaction { services.fillWithSomeTestCash(100.DOLLARS, DUMMY_NOTARY, 10, 10, Random(0L)) services.fillWithSomeTestCash(100.POUNDS, DUMMY_NOTARY, 10, 10, Random(0L)) @@ -399,7 +399,7 @@ class NodeVaultServiceTest { @Test fun addNoteToTransaction() { - databaseTransaction(database) { + database.transaction { val freshKey = services.legalIdentityKey diff --git a/node/src/test/kotlin/net/corda/node/utilities/ObservablesTests.kt b/node/src/test/kotlin/net/corda/node/utilities/ObservablesTests.kt index 95d99cc0c0..72213773fe 100644 --- a/node/src/test/kotlin/net/corda/node/utilities/ObservablesTests.kt +++ b/node/src/test/kotlin/net/corda/node/utilities/ObservablesTests.kt @@ -45,7 +45,7 @@ class ObservablesTests { observable.first().subscribe { firstEvent.set(it to isInDatabaseTransaction()) } observable.skip(1).first().subscribe { secondEvent.set(it to isInDatabaseTransaction()) } - databaseTransaction(database) { + database.transaction { val delayedSubject = source.bufferUntilDatabaseCommit() assertThat(source).isNotEqualTo(delayedSubject) delayedSubject.onNext(0) @@ -72,7 +72,7 @@ class ObservablesTests { observable.first().subscribe { firstEvent.set(it to isInDatabaseTransaction()) } observable.skip(1).first().subscribe { secondEvent.set(it to isInDatabaseTransaction()) } - databaseTransaction(database) { + database.transaction { val delayedSubject = source.bufferUntilDatabaseCommit() assertThat(source).isNotEqualTo(delayedSubject) delayedSubject.onNext(0) @@ -83,7 +83,7 @@ class ObservablesTests { assertThat(firstEvent.get()).isEqualTo(0 to false) assertThat(secondEvent.isDone).isFalse() - databaseTransaction(database) { + database.transaction { val delayedSubject = source.bufferUntilDatabaseCommit() assertThat(source).isNotEqualTo(delayedSubject) delayedSubject.onNext(1) @@ -140,7 +140,7 @@ class ObservablesTests { teed.first().subscribe { teedEvent.set(it to isInDatabaseTransaction()) } - databaseTransaction(database) { + database.transaction { val delayedSubject = source.bufferUntilDatabaseCommit().tee(teed) assertThat(source).isNotEqualTo(delayedSubject) delayedSubject.onNext(0) @@ -173,7 +173,7 @@ class ObservablesTests { observableWithDbTx.skip(1).first().subscribe { observeSecondEvent(it, delayedEventFromSecondObserver) } observableWithDbTx.skip(1).first().subscribe { observeSecondEvent(it, delayedEventFromThirdObserver) } - databaseTransaction(database) { + database.transaction { val commitDelayedSource = source.bufferUntilDatabaseCommit() assertThat(source).isNotEqualTo(commitDelayedSource) commitDelayedSource.onNext(0) diff --git a/samples/irs-demo/src/main/kotlin/net/corda/simulation/IRSSimulation.kt b/samples/irs-demo/src/main/kotlin/net/corda/simulation/IRSSimulation.kt index bca555c016..86096d1bd4 100644 --- a/samples/irs-demo/src/main/kotlin/net/corda/simulation/IRSSimulation.kt +++ b/samples/irs-demo/src/main/kotlin/net/corda/simulation/IRSSimulation.kt @@ -20,7 +20,7 @@ import net.corda.flows.TwoPartyDealFlow.AutoOffer import net.corda.flows.TwoPartyDealFlow.Instigator import net.corda.irs.contract.InterestRateSwap import net.corda.jackson.JacksonSupport -import net.corda.node.utilities.databaseTransaction +import net.corda.node.utilities.transaction import net.corda.testing.initiateSingleShotFlow import net.corda.testing.node.InMemoryMessagingNetwork import net.corda.testing.node.MockIdentityService @@ -75,7 +75,7 @@ class IRSSimulation(networkSendManuallyPumped: Boolean, runAsync: Boolean, laten } private fun loadLinearHeads(node: SimulatedNode): Map>> { - return databaseTransaction(node.database) { + return node.database.transaction { node.services.vaultService.linearHeadsOfType>() } } diff --git a/samples/irs-demo/src/main/kotlin/net/corda/simulation/Simulation.kt b/samples/irs-demo/src/main/kotlin/net/corda/simulation/Simulation.kt index f722b42519..2ccca41c29 100644 --- a/samples/irs-demo/src/main/kotlin/net/corda/simulation/Simulation.kt +++ b/samples/irs-demo/src/main/kotlin/net/corda/simulation/Simulation.kt @@ -18,7 +18,7 @@ import net.corda.node.services.config.NodeConfiguration import net.corda.node.services.network.NetworkMapService import net.corda.node.services.transactions.SimpleNotaryService import net.corda.node.utilities.AddOrRemove -import net.corda.node.utilities.databaseTransaction +import net.corda.node.utilities.transaction import net.corda.testing.TestNodeConfiguration import net.corda.testing.node.InMemoryMessagingNetwork import net.corda.testing.node.MockNetwork @@ -128,7 +128,7 @@ abstract class Simulation(val networkSendManuallyPumped: Boolean, override fun start(): MockNetwork.MockNode { super.start() javaClass.classLoader.getResourceAsStream("example.rates.txt").use { - databaseTransaction(database) { + database.transaction { findService().upload(it) } } diff --git a/samples/irs-demo/src/test/kotlin/net/corda/irs/testing/NodeInterestRatesTest.kt b/samples/irs-demo/src/test/kotlin/net/corda/irs/testing/NodeInterestRatesTest.kt index dfac04dd40..79a4bcd524 100644 --- a/samples/irs-demo/src/test/kotlin/net/corda/irs/testing/NodeInterestRatesTest.kt +++ b/samples/irs-demo/src/test/kotlin/net/corda/irs/testing/NodeInterestRatesTest.kt @@ -18,7 +18,7 @@ import net.corda.core.utilities.ProgressTracker import net.corda.irs.api.NodeInterestRates import net.corda.irs.flows.RatesFixFlow import net.corda.node.utilities.configureDatabase -import net.corda.node.utilities.databaseTransaction +import net.corda.node.utilities.transaction import net.corda.testing.ALICE_PUBKEY import net.corda.testing.MEGA_CORP import net.corda.testing.MEGA_CORP_KEY @@ -68,7 +68,7 @@ class NodeInterestRatesTest { val dataSourceAndDatabase = configureDatabase(makeTestDataSourceProperties()) dataSource = dataSourceAndDatabase.first database = dataSourceAndDatabase.second - databaseTransaction(database) { + database.transaction { oracle = NodeInterestRates.Oracle(MEGA_CORP, MEGA_CORP_KEY, clock).apply { knownFixes = TEST_DATA } } } @@ -80,7 +80,7 @@ class NodeInterestRatesTest { @Test fun `query successfully`() { - databaseTransaction(database) { + database.transaction { val q = NodeInterestRates.parseFixOf("LIBOR 2016-03-16 1M") val res = oracle.query(listOf(q), clock.instant()) assertEquals(1, res.size) @@ -91,7 +91,7 @@ class NodeInterestRatesTest { @Test fun `query with one success and one missing`() { - databaseTransaction(database) { + database.transaction { val q1 = NodeInterestRates.parseFixOf("LIBOR 2016-03-16 1M") val q2 = NodeInterestRates.parseFixOf("LIBOR 2016-03-15 1M") val e = assertFailsWith { oracle.query(listOf(q1, q2), clock.instant()) } @@ -101,7 +101,7 @@ class NodeInterestRatesTest { @Test fun `query successfully with interpolated rate`() { - databaseTransaction(database) { + database.transaction { val q = NodeInterestRates.parseFixOf("LIBOR 2016-03-16 5M") val res = oracle.query(listOf(q), clock.instant()) assertEquals(1, res.size) @@ -112,7 +112,7 @@ class NodeInterestRatesTest { @Test fun `rate missing and unable to interpolate`() { - databaseTransaction(database) { + database.transaction { val q = NodeInterestRates.parseFixOf("EURIBOR 2016-03-15 3M") assertFailsWith { oracle.query(listOf(q), clock.instant()) } } @@ -120,14 +120,14 @@ class NodeInterestRatesTest { @Test fun `empty query`() { - databaseTransaction(database) { + database.transaction { assertFailsWith { oracle.query(emptyList(), clock.instant()) } } } @Test fun `refuse to sign with no relevant commands`() { - databaseTransaction(database) { + database.transaction { val tx = makeTX() val wtx1 = tx.toWireTransaction() fun filterAllOutputs(elem: Any): Boolean { @@ -149,7 +149,7 @@ class NodeInterestRatesTest { @Test fun `sign successfully`() { - databaseTransaction(database) { + database.transaction { val tx = makeTX() val fix = oracle.query(listOf(NodeInterestRates.parseFixOf("LIBOR 2016-03-16 1M")), clock.instant()).first() tx.addCommand(fix, oracle.identity.owningKey) @@ -163,7 +163,7 @@ class NodeInterestRatesTest { @Test fun `do not sign with unknown fix`() { - databaseTransaction(database) { + database.transaction { val tx = makeTX() val fixOf = NodeInterestRates.parseFixOf("LIBOR 2016-03-16 1M") val badFix = Fix(fixOf, "0.6789".bd) @@ -177,7 +177,7 @@ class NodeInterestRatesTest { @Test fun `do not sign too many leaves`() { - databaseTransaction(database) { + database.transaction { val tx = makeTX() val fix = oracle.query(listOf(NodeInterestRates.parseFixOf("LIBOR 2016-03-16 1M")), clock.instant()).first() fun filtering(elem: Any): Boolean { @@ -207,7 +207,7 @@ class NodeInterestRatesTest { val net = MockNetwork() val n1 = net.createNotaryNode() val n2 = net.createNode(n1.info.address, advertisedServices = ServiceInfo(NodeInterestRates.type)) - databaseTransaction(n2.database) { + n2.database.transaction { n2.findService().oracle.knownFixes = TEST_DATA } val tx = TransactionType.General.Builder(null) diff --git a/test-utils/src/main/kotlin/net/corda/testing/node/InMemoryMessagingNetwork.kt b/test-utils/src/main/kotlin/net/corda/testing/node/InMemoryMessagingNetwork.kt index bde29f0ebc..9cbc1aa1d8 100644 --- a/test-utils/src/main/kotlin/net/corda/testing/node/InMemoryMessagingNetwork.kt +++ b/test-utils/src/main/kotlin/net/corda/testing/node/InMemoryMessagingNetwork.kt @@ -16,7 +16,7 @@ import net.corda.node.services.api.MessagingServiceBuilder import net.corda.node.services.api.MessagingServiceInternal import net.corda.node.utilities.AffinityExecutor import net.corda.node.utilities.JDBCHashSet -import net.corda.node.utilities.databaseTransaction +import net.corda.node.utilities.transaction import net.corda.testing.node.InMemoryMessagingNetwork.InMemoryMessaging import org.apache.activemq.artemis.utils.ReusableLatch import org.bouncycastle.asn1.x500.X500Name @@ -333,7 +333,7 @@ class InMemoryMessagingNetwork( val (handler, transfers) = state.locked { val handler = Handler(topicSession, callback).apply { handlers.add(this) } val pending = ArrayList() - databaseTransaction(database) { + database.transaction { pending.addAll(pendingRedelivery) pendingRedelivery.clear() } @@ -409,7 +409,7 @@ class InMemoryMessagingNetwork( // up a handler for yet. Most unit tests don't run threaded, but we want to test true parallelism at // least sometimes. log.warn("Message to ${transfer.message.topicSession} could not be delivered") - databaseTransaction(database) { + database.transaction { pendingRedelivery.add(transfer) } null @@ -431,7 +431,7 @@ class InMemoryMessagingNetwork( if (transfer.message.uniqueMessageId !in processedMessages) { executor.execute { - databaseTransaction(database) { + database.transaction { for (handler in deliverTo) { try { handler.callback(transfer.toReceivedMessage(), handler) diff --git a/test-utils/src/main/kotlin/net/corda/testing/node/SimpleNode.kt b/test-utils/src/main/kotlin/net/corda/testing/node/SimpleNode.kt index 1ab7fc886f..66a29d52fc 100644 --- a/test-utils/src/main/kotlin/net/corda/testing/node/SimpleNode.kt +++ b/test-utils/src/main/kotlin/net/corda/testing/node/SimpleNode.kt @@ -13,8 +13,8 @@ import net.corda.node.services.messaging.NodeMessagingClient import net.corda.node.services.network.InMemoryNetworkMapCache import net.corda.node.utilities.AffinityExecutor.ServiceAffinityExecutor import net.corda.node.utilities.configureDatabase -import net.corda.node.utilities.databaseTransaction import net.corda.testing.MOCK_NODE_VERSION_INFO +import net.corda.node.utilities.transaction import net.corda.testing.freeLocalHostAndPort import org.jetbrains.exposed.sql.Database import java.io.Closeable @@ -35,7 +35,7 @@ class SimpleNode(val config: NodeConfiguration, val address: HostAndPort = freeL val executor = ServiceAffinityExecutor(config.myLegalName, 1) val broker = ArtemisMessagingServer(config, address, rpcAddress, InMemoryNetworkMapCache(), userService) val networkMapRegistrationFuture: SettableFuture = SettableFuture.create() - val net = databaseTransaction(database) { + val net = database.transaction { NodeMessagingClient( config, MOCK_NODE_VERSION_INFO, @@ -65,4 +65,4 @@ class SimpleNode(val config: NodeConfiguration, val address: HostAndPort = freeL databaseWithCloseable.first.close() executor.shutdownNow() } -} \ No newline at end of file +}