-
Notifications
You must be signed in to change notification settings - Fork 20
DOCSP-41760 Add transactions page #167
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
stephmarie17
merged 21 commits into
mongodb:master
from
stephmarie17:docsp-41760-addTransactionsPage
Aug 29, 2024
Merged
Changes from 13 commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
af1fdaa
add transactions page
stephmarie17 3dad252
update include
stephmarie17 0c3d7b9
update links
stephmarie17 c30536e
fix typo
stephmarie17 71ddcf9
add spacing
stephmarie17 800c43a
update website link
stephmarie17 90daadf
update code example
stephmarie17 8bb6af1
remove extra reference
stephmarie17 795e1fd
update code examples
stephmarie17 e9b22ad
use include
stephmarie17 150f9fb
update constant
stephmarie17 07d902b
update source constants
stephmarie17 cf34824
update code examples and references
stephmarie17 ff52fb1
update code intros
stephmarie17 4324743
DOCSP-42086: server 8.0 compat (#168)
rustagir 31cb0e9
DOCSP-42514: kotlin user/pass placeholders (#169)
rustagir 163591b
DOCSP-42282: java avs type support (#170)
rustagir 442df94
Add files via upload
branberry a713c07
Merge branch 'master' of github.com:mongodb/docs-kotlin into docsp-41…
rustagir 580a5d2
ignore search indexes test
rustagir 2d7c437
update references
stephmarie17 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,86 @@ | ||
import com.mongodb.kotlin.client.coroutine.MongoClient | ||
import com.mongodb.client.model.Filters.eq | ||
import com.mongodb.client.model.Updates.inc | ||
import config.getConfig | ||
import kotlinx.coroutines.runBlocking | ||
import org.junit.jupiter.api.AfterAll | ||
import org.junit.jupiter.api.Assertions.assertNotNull | ||
import org.junit.jupiter.api.BeforeAll | ||
import org.junit.jupiter.api.Test | ||
import org.junit.jupiter.api.TestInstance | ||
|
||
@TestInstance(TestInstance.Lifecycle.PER_CLASS) | ||
class TransactionsTest { | ||
|
||
// :snippet-start: data-class | ||
data class Account( | ||
val accountId: String, | ||
val amount: Int | ||
) | ||
// :snippet-end: | ||
|
||
companion object { | ||
val config = getConfig() | ||
val client = MongoClient.create(config.connectionUri) | ||
val database = client.getDatabase("bank") | ||
|
||
@BeforeAll | ||
@JvmStatic | ||
fun beforeAll() { | ||
runBlocking { | ||
val savAcct = Account("9876", 900) | ||
database.getCollection<Account>("savings_accounts").insertOne(savAcct) | ||
|
||
val chkAcct = Account("9876", 50) | ||
database.getCollection<Account>("checking_accounts").insertOne(chkAcct) | ||
} | ||
} | ||
|
||
@AfterAll | ||
@JvmStatic | ||
fun afterAll() { | ||
runBlocking { | ||
database.drop() | ||
client.close() | ||
} | ||
} | ||
} | ||
|
||
@Test | ||
fun transactionTest() = runBlocking { | ||
// :snippet-start: transaction-function | ||
// Set up the session | ||
val session = client.startSession() | ||
|
||
try { | ||
session.startTransaction() | ||
|
||
val savingsColl = database | ||
.getCollection<Account>("savings_accounts") | ||
val checkingColl = database | ||
.getCollection<Account>("checking_accounts") | ||
|
||
savingsColl.findOneAndUpdate( | ||
session, | ||
eq(Account::accountId.name, "9876"), | ||
inc(Account::amount.name, -100), | ||
) | ||
|
||
checkingColl.findOneAndUpdate( | ||
session, | ||
eq(Account::accountId.name, "9876"), | ||
inc(Account::amount.name, 100) | ||
) | ||
|
||
// Commit the transaction | ||
val result = session.commitTransaction() | ||
println("Transaction committed.") | ||
assertNotNull(result) // :remove: | ||
} catch (error: Exception) { | ||
println("An error occurred during the transaction: ${error.message}") | ||
// Abort the transaction | ||
session.abortTransaction() | ||
} | ||
// :snippet-end: | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
4 changes: 4 additions & 0 deletions
4
source/examples/generated/TransactionsTest.snippet.data-class.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
data class Account( | ||
val accountId: String, | ||
val amount: Int | ||
) |
31 changes: 31 additions & 0 deletions
31
source/examples/generated/TransactionsTest.snippet.transaction-function.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
// Set up the session | ||
val session = client.startSession() | ||
|
||
try { | ||
session.startTransaction() | ||
|
||
val savingsColl = database | ||
.getCollection<Account>("savings_accounts") | ||
val checkingColl = database | ||
.getCollection<Account>("checking_accounts") | ||
|
||
savingsColl.findOneAndUpdate( | ||
session, | ||
eq(Account::accountId.name, "9876"), | ||
inc(Account::amount.name, -100), | ||
) | ||
|
||
checkingColl.findOneAndUpdate( | ||
session, | ||
eq(Account::accountId.name, "9876"), | ||
inc(Account::amount.name, 100) | ||
) | ||
|
||
// Commit the transaction | ||
val result = session.commitTransaction() | ||
println("Transaction committed.") | ||
} catch (error: Exception) { | ||
println("An error occurred during the transaction: ${error.message}") | ||
// Abort the transaction | ||
session.abortTransaction() | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,130 @@ | ||
.. _kotlin-fundamentals-transactions: | ||
|
||
============ | ||
Transactions | ||
============ | ||
|
||
.. facet:: | ||
:name: genre | ||
:values: reference | ||
|
||
.. meta:: | ||
:keywords: modify, customize | ||
|
||
.. contents:: On this page | ||
:local: | ||
:backlinks: none | ||
:depth: 2 | ||
:class: singlecol | ||
|
||
Overview | ||
-------- | ||
|
||
In this guide, you can learn how to use the {+driver-short+} to perform | ||
**transactions**. :manual:`Transactions </core/transactions/>` allow | ||
you to run a series of operations that do not change any data until the | ||
transaction is committed. If any operation in the transaction returns an | ||
error, the driver cancels the transaction and discards all data changes | ||
before they ever become visible. | ||
|
||
In MongoDB, transactions run within logical **sessions**. A | ||
:manual:`session </reference/server-sessions/>` is a grouping of related | ||
read or write operations that you intend to run sequentially. Sessions | ||
enable :manual:`causal consistency | ||
</core/read-isolation-consistency-recency/#causal-consistency>` for a | ||
group of operations or allow you to execute operations in an | ||
:website:`ACID transaction </basics/acid-transactions>`. MongoDB | ||
guarantees that the data involved in your transaction operations remains | ||
consistent, even if the operations encounter unexpected errors. | ||
|
||
When using the {+driver-short+}, you can create a new session from a | ||
``Client`` instance as a ``ClientSession``. We recommend that you reuse | ||
your client for multiple sessions and transactions instead of | ||
instantiating a new client each time. | ||
|
||
.. warning:: | ||
|
||
Use a ``Session`` only with the ``Client`` (or associated | ||
``Database`` or ``Collection``) that created it. Using a | ||
``Session`` with a different ``Client`` results in operation | ||
errors. | ||
|
||
Methods | ||
------- | ||
|
||
Create a ``ClientSession`` by using the ``startSession()`` method on your | ||
``Client`` instance. You can then modify the session state by using the | ||
following methods: | ||
|
||
.. list-table:: | ||
:widths: 25 75 | ||
:header-rows: 1 | ||
|
||
* - Method | ||
- Description | ||
|
||
* - ``startTransaction()`` | ||
- | Starts a new transaction for this session with the | ||
default transaction options. You cannot start a | ||
transaction if there's already an active transaction | ||
on the session. | ||
| | ||
| To set transaction options, use ``startTransaction(transactionOptions: TransactionOptions)``. | ||
|
||
* - ``abortTransaction()`` | ||
- | Ends the active transaction for this session. Returns an error | ||
if there is no active transaction for the | ||
session or the transaction was previously ended. | ||
|
||
* - ``commitTransaction()`` | ||
- | Commits the active transaction for this session. Returns an | ||
error if there is no active transaction for the session or if the | ||
transaction was ended. | ||
|
||
A ``Session`` also has methods to retrieve session properties and modify | ||
mutable session properties. View the `API documentation <{+api+}/apidocs/mongodb-driver-kotlin-coroutine/mongodb-driver-kotlin-coroutine/com.mongodb.kotlin.client.coroutine/-client-session/index.html>`__ | ||
to learn more about these methods. | ||
|
||
Example | ||
------- | ||
|
||
The following example demonstrates how you can create a session, create a transaction, | ||
and commit a changes to existing documents: | ||
|
||
1. Create a session from the client using the ``startSession()`` method. | ||
#. Use the ``startTransaction()`` method to start a transaction. | ||
#. Update the specified documents, then use the ``commitTransaction()`` method if all | ||
operations succeed, or ``abortTransaction()`` if any operations fail. | ||
|
||
This example uses the following {+language+} data classes to model its documents: | ||
|
||
.. literalinclude:: /examples/generated/TransactionsTest.snippet.data-class.kt | ||
:language: kotlin | ||
|
||
.. literalinclude:: /examples/generated/TransactionsTest.snippet.transaction-function.kt | ||
:language: kotlin | ||
|
||
Additional Information | ||
---------------------- | ||
|
||
To learn more about the concepts mentioned in this guide, see the following pages in | ||
the Server manual: | ||
|
||
- :manual:`Transactions </core/transactions/>` | ||
- :manual:`Server Sessions </reference/server-sessions>` | ||
- :manual:`Read Isolation, Consistency, and Recency </core/read-isolation-consistency-recency/#causal-consistency>` | ||
|
||
To learn more about ACID compliance, see the :website:`What are ACID | ||
Properties in Database Management Systems? </basics/acid-transactions>` | ||
article on the MongoDB website. | ||
|
||
API Documentation | ||
~~~~~~~~~~~~~~~~~ | ||
|
||
To learn more about any of the types or methods discussed in this | ||
guide, see the following API Documentation: | ||
|
||
- `ClientSession <{+api+}/apidocs/mongodb-driver-kotlin-coroutine/mongodb-driver-kotlin-coroutine/com.mongodb.kotlin.client.coroutine/-client-session/index.html>`__ | ||
- `startTransaction <{+api+}/apidocs/mongodb-driver-kotlin-coroutine/mongodb-driver-kotlin-coroutine/com.mongodb.kotlin.client.coroutine/-client-session/start-transaction.html>`__ | ||
- `commitTransaction <{+api+}/apidocs/mongodb-driver-kotlin-coroutine/mongodb-driver-kotlin-coroutine/com.mongodb.kotlin.client.coroutine/-client-session/commit-transaction.html>`__ | ||
- `abortTransaction <{+api+}/apidocs/mongodb-driver-kotlin-coroutine/mongodb-driver-kotlin-coroutine/com.mongodb.kotlin.client.coroutine/-client-session/abort-transaction.html>`__ |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.