Skip to content

Commit 91139fa

Browse files
committed
DOCSP-41995: transaction
1 parent 55a44c1 commit 91139fa

File tree

4 files changed

+222
-0
lines changed

4 files changed

+222
-0
lines changed

snooty.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,4 @@ stable-api = "Stable API"
3030
mdb-server = "MongoDB Server"
3131
api = "https://www.mongodb.com/docs/php-library/current/reference"
3232
php-manual = "https://www.php.net/manual/en"
33+
extension-short = "PHP extension"

source/includes/write/transaction.php

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
<?php
2+
require 'vendor/autoload.php';
3+
4+
$uri = getenv('MONGODB_URI') ?: throw new RuntimeException('Set the MONGODB_URI variable to your Atlas URI that connects to the sample dataset');
5+
$client = new MongoDB\Client($uri);
6+
7+
// begin-callback
8+
$receipts = $client->bank->receipts;
9+
$checking = $client->bank->checking_accounts;
10+
$saving = $client->bank->saving_accounts;
11+
12+
$accountId = '5678';
13+
$transferAmount = 1000.00;
14+
15+
$callback = function (MongoDB\Driver\Session $session)
16+
use ($checking, $saving, $receipts, $accountId, $transferAmount): void {
17+
18+
$checking->updateOne(
19+
['account_id' => $accountId],
20+
['$inc' => ['balance' => -$transferAmount]],
21+
['session' => $session]
22+
);
23+
24+
$saving->updateOne(
25+
['account_id' => $accountId],
26+
['$inc' => ['balance' => $transferAmount]],
27+
['session' => $session]
28+
);
29+
30+
$summary = sprintf(
31+
"SAVINGS +%u CHECKING -%u.", $transferAmount, $transferAmount
32+
);
33+
34+
$receipts->insertOne([
35+
'account_id' => $accountId,
36+
'description' => $summary,
37+
'timestamp' => new MongoDB\BSON\UTCDateTime((new DateTime())->getTimestamp()*1000),
38+
], ['session' => $session]);
39+
40+
echo 'Successfully performed transaction!\n';
41+
};
42+
// end-callback
43+
44+
// begin-txn
45+
$session = $client->startSession();
46+
47+
try {
48+
MongoDB\with_transaction($session, $callback);
49+
} catch (Exception $e) {
50+
echo 'Caught exception: ', $e->getMessage(), '\n';
51+
}
52+
// end-txn

source/write.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,4 @@ Write Data to MongoDB
1212
/write/replace
1313
/write/insert
1414
/write/update
15+
/write/transaction

source/write/transaction.txt

Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
.. _php-transactions:
2+
3+
=====================
4+
Perform a Transaction
5+
=====================
6+
7+
.. facet::
8+
:name: genre
9+
:values: reference
10+
11+
.. meta::
12+
:keywords: code example, ACID compliance, multi-document
13+
14+
.. contents:: On this page
15+
:local:
16+
:backlinks: none
17+
:depth: 2
18+
:class: singlecol
19+
20+
Overview
21+
--------
22+
23+
In this guide, you can learn how to use the {+driver-short+} to perform
24+
**transactions**. Transactions allow you to perform a series of operations
25+
that change data only if the entire transaction is committed.
26+
If any operation in the transaction does not succeed, the driver stops the
27+
transaction and discards all data changes before they ever become
28+
visible. This feature is called **atomicity**.
29+
30+
In MongoDB, transactions run within logical sessions. A
31+
session is a grouping of related read or write operations that you
32+
want to run sequentially. Sessions enable causal consistency for a group
33+
of operations and allow you to run operations in an **ACID-compliant**
34+
transaction, which is a transaction that meets an expectation of
35+
atomicity, consistency, isolation, and durability. MongoDB guarantees
36+
that the data involved in your transaction operations remains
37+
consistent, even if the operations encounter unexpected errors.
38+
39+
When using the {+php-library+}, you can create a new session from a
40+
``MongoDB\Client`` instance. Then, you can use the resulting
41+
``MongoDB\Driver\Session`` instance to perform transactions. You can
42+
improve your app's performance by reusing your client for multiple
43+
sessions and transactions instead of instantiating a new client each
44+
time.
45+
46+
.. warning::
47+
48+
Use a ``Session`` only in operations running on the
49+
``Client`` that created it. Using a ``Session`` with a
50+
different ``Client`` results in operation errors.
51+
52+
Methods
53+
-------
54+
55+
Create a ``Session`` by using the ``MongoDB\Client::startSession()``
56+
method on your ``Client`` instance. The {+php-library+} provides a
57+
Convenient Transaction API to manage the transaction lifecyle. Use the
58+
``MongoDB\with_transaction()`` method to run custom callback within a
59+
transaction. The ``with_transaction()`` method starts the transaction,
60+
then either commits it or ends it if there are errors. The
61+
:ref:`php-txn-example` section of this guide demonstrates how to use
62+
this API to perform a transaction.
63+
64+
Alternatively, you can have more control over your transaction lifecyle
65+
by using the methods provided by the ``Session`` class. The
66+
following table describes these methods:
67+
68+
.. list-table::
69+
:widths: 25 75
70+
:stub-columns: 1
71+
:header-rows: 1
72+
73+
* - Method
74+
- Description
75+
76+
* - ``startTransaction()``
77+
- | Starts a new transaction on this session. The session
78+
must be passed into each operation within the transaction, or
79+
the operation will run outside of the transaction.
80+
|
81+
| You can set transaction options by passing an options parameter.
82+
83+
* - ``commitTransaction()``
84+
- | Commits the active transaction for this session. This method returns an
85+
error if there is no active transaction for the session or the
86+
transaction was previously ended.
87+
88+
* - ``abortTransaction()``
89+
- | Ends the active transaction for this session. This method returns an
90+
error if there is no active transaction for the session or if the
91+
transaction was committed or ended.
92+
93+
.. _php-txn-example:
94+
95+
Transaction Example
96+
-------------------
97+
98+
The following code defines the ``transferTxn()`` callback function that
99+
modifies data in the ``saving_accounts``, ``checking_accounts``, and ``receipts``
100+
collections of the ``bank`` database:
101+
102+
.. literalinclude:: /includes/write/transaction.php
103+
:language: php
104+
:dedent:
105+
:start-after: begin-callback
106+
:end-before: end-callback
107+
108+
Then, run the following code to perform the transaction. This code
109+
completes the following actions:
110+
111+
1. Creates a session from the client by using the ``startSession()`` method.
112+
#. Calls the ``with_transaction()`` method to manage the transaction,
113+
passing the session and the callback as parameters.
114+
115+
.. io-code-block::
116+
117+
.. input:: /includes/write/transaction.php
118+
:language: php
119+
:dedent:
120+
:start-after: begin-txn
121+
:end-before: end-txn
122+
123+
.. output::
124+
:language: console
125+
:visible: false
126+
127+
Successfully committed transaction!
128+
129+
Additional Information
130+
----------------------
131+
132+
To learn more about the concepts mentioned in this guide, see the
133+
following pages in the {+mdb-server+} manual:
134+
135+
- :manual:`Transactions </core/transactions/>`
136+
- :manual:`Server Sessions </reference/server-sessions/>`
137+
- :manual:`Read Isolation, Consistency, and Recency
138+
</core/read-isolation-consistency-recency/#causal-consistency>`
139+
140+
To learn more about ACID compliance, see the :website:`What are ACID
141+
Properties in Database Management Systems? </basics/acid-transactions>`
142+
article on the MongoDB website.
143+
144+
To learn more about insert operations, see the
145+
:ref:`php-write-insert` guide.
146+
147+
API Documentation
148+
~~~~~~~~~~~~~~~~~
149+
150+
To learn more about the methods and types mentioned in this
151+
guide, see the following API documentation:
152+
153+
- :phpclass:`MongoDB\Client`
154+
- :phpmethod:`MongoDB\Client::startSession()`
155+
- :phpmethod:`MongoDB\Collection::updateOne()`
156+
- :phpmethod:`MongoDB\Collection::insertOne()`
157+
158+
To learn more about the ``Session`` class and methods,
159+
see the following {+extension-short+} API documentation:
160+
161+
- `MongoDB\\Driver\\Session
162+
<https://www.php.net/manual/en/class.mongodb-driver-session.php>`__
163+
- `MongoDB\\Driver\\Session::abortTransaction()
164+
<https://www.php.net/manual/en/mongodb-driver-session.aborttransaction.php>`__
165+
- `MongoDB\\Driver\\Session::commitTransaction()
166+
<https://www.php.net/manual/en/mongodb-driver-session.committransaction.php>`__
167+
- `MongoDB\\Driver\\Session::startTransaction()
168+
<https://www.php.net/manual/en/mongodb-driver-session.starttransaction.php>`__

0 commit comments

Comments
 (0)