|
27 | 27 | from pymongo.write_concern import WriteConcern
|
28 | 28 |
|
29 | 29 | from test import client_context, unittest, IntegrationTest
|
30 |
| -from test.utils import rs_or_single_client |
31 |
| - |
| 30 | +from test.utils import rs_client, rs_or_single_client |
32 | 31 |
|
33 | 32 | class TestSampleShellCommands(unittest.TestCase):
|
34 | 33 |
|
@@ -1037,6 +1036,44 @@ def update_employee_info(session):
|
1037 | 1036 | self.assertIsNotNone(employee)
|
1038 | 1037 | self.assertEqual(employee['status'], 'Inactive')
|
1039 | 1038 |
|
| 1039 | + MongoClient = lambda _: rs_client() |
| 1040 | + uriString = None |
| 1041 | + |
| 1042 | + # Start Transactions withTxn API Example 1 |
| 1043 | + |
| 1044 | + # For a replica set, include the replica set name and a seedlist of the members in the URI string; e.g. |
| 1045 | + # uriString = 'mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017/?replicaSet=myRepl' |
| 1046 | + # For a sharded cluster, connect to the mongos instances; e.g. |
| 1047 | + # uriString = 'mongodb://mongos0.example.com:27017,mongos1.example.com:27017/' |
| 1048 | + |
| 1049 | + client = MongoClient(uriString) |
| 1050 | + wc_majority = WriteConcern("majority", wtimeout=1000) |
| 1051 | + |
| 1052 | + # Prereq: Create collections. CRUD operations in transactions must be on existing collections. |
| 1053 | + client.get_database( |
| 1054 | + "mydb1", write_concern=wc_majority).foo.insert_one({'abc': 0}) |
| 1055 | + client.get_database( |
| 1056 | + "mydb2", write_concern=wc_majority).bar.insert_one({'xyz': 0}) |
| 1057 | + |
| 1058 | + # Step 1: Define the callback that specifies the sequence of operations to perform inside the transactions. |
| 1059 | + def callback(session): |
| 1060 | + collection_one = session.client.mydb1.foo |
| 1061 | + collection_two = session.client.mydb2.bar |
| 1062 | + |
| 1063 | + # Important:: You must pass the session to the operations. |
| 1064 | + collection_one.insert_one({'abc': 1}, session=session) |
| 1065 | + collection_two.insert_one({'xyz': 999}, session=session) |
| 1066 | + |
| 1067 | + # Step 2: Start a client session. |
| 1068 | + with client.start_session() as session: |
| 1069 | + # Step 3: Use with_transaction to start a transaction, execute the callback, and commit (or abort on error). |
| 1070 | + session.with_transaction( |
| 1071 | + callback, read_concern=ReadConcern('local'), |
| 1072 | + write_concern=wc_majority, |
| 1073 | + read_preference=ReadPreference.PRIMARY) |
| 1074 | + |
| 1075 | + # End Transactions withTxn API Example 1 |
| 1076 | + |
1040 | 1077 | @client_context.require_transactions
|
1041 | 1078 | def test_transactions_beta(self):
|
1042 | 1079 | # Transaction beta examples
|
|
0 commit comments