-
Notifications
You must be signed in to change notification settings - Fork 52
DOCSP-32718: add CodeWhisperer comments to transactions code snippets #769
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
ccho-mongodb
merged 8 commits into
mongodb:master
from
ccho-mongodb:DOCSP-32718-transactions
Sep 5, 2023
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
f81576e
DOCSP-32718: add CodeWhisperer comments to transactions code snippets
160a2d7
build
026c6d4
fix highlighting
90c3d6c
build again
ab8d6fa
remove extra lines
e6a25c7
PRR fixes
f3ea0c0
reword
9643564
update highlighted lines
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 | ||||
---|---|---|---|---|---|---|
@@ -1,12 +1,14 @@ | ||||||
/* Performs multiple write operations in a transaction */ | ||||||
|
||||||
const { MongoError, MongoClient } = require('mongodb'); | ||||||
|
||||||
// drop collections | ||||||
// Drop the "customers", "inventory", and "orders" collections from the "testdb" database | ||||||
async function cleanUp(client) { | ||||||
await Promise.all( ['customers', 'inventory', 'orders'].map(async c => { | ||||||
try { | ||||||
const coll = client.db('testdb').collection(c); | ||||||
await coll.drop(); | ||||||
} catch(e) {} | ||||||
} catch(e) {} // Ignore any exceptions | ||||||
})); | ||||||
} | ||||||
|
||||||
|
@@ -15,17 +17,21 @@ async function setup(client) { | |||||
const customerColl = client.db('testdb').collection('customers'); | ||||||
const inventoryColl = client.db('testdb').collection('inventory'); | ||||||
|
||||||
// Insert order data for customer "98765" in the customers collection | ||||||
await customerColl.insertOne({ _id: 98765, orders: [] }); | ||||||
|
||||||
// Insert inventory data for "sunblock" and "beach towel" | ||||||
await inventoryColl.insertMany([ | ||||||
{ name: 'sunblock', sku: 5432, qty: 85 }, | ||||||
{ name: 'beach towel', sku: 7865, qty: 41 }, | ||||||
]); | ||||||
} catch (e) { | ||||||
// Print the exception if one was thrown | ||||||
console.log('Unable to insert test data: ' + e); | ||||||
} | ||||||
} | ||||||
|
||||||
// Print all documents in the "customers", "inventory", and "orders" collections | ||||||
async function queryData() { | ||||||
const uri = process.env.MONGODB_URI; | ||||||
const client = new MongoClient(uri); | ||||||
|
@@ -36,23 +42,29 @@ async function queryData() { | |||||
}, client)); | ||||||
|
||||||
} finally { | ||||||
// Close the database connection | ||||||
client.close(); | ||||||
} | ||||||
} | ||||||
|
||||||
// start placeOrder | ||||||
async function placeOrder(client, cart, payment) { | ||||||
// Specify readConcern, writeConcern, and readPreference transaction options | ||||||
const transactionOptions = { | ||||||
readConcern: { level: 'snapshot' }, | ||||||
writeConcern: { w: 'majority' }, | ||||||
readPreference: 'primary' | ||||||
}; | ||||||
|
||||||
// Start the session | ||||||
const session = client.startSession(); | ||||||
try { | ||||||
// Start the transaction in the session, specifying the transaction options | ||||||
session.startTransaction(transactionOptions); | ||||||
|
||||||
const ordersCollection = client.db('testdb').collection('orders'); | ||||||
// Within the session, insert an order that contains information about the | ||||||
// customer, items purchased, and the total payment. | ||||||
const orderResult = await ordersCollection.insertOne( | ||||||
{ | ||||||
customer: payment.customer, | ||||||
|
@@ -63,21 +75,26 @@ async function placeOrder(client, cart, payment) { | |||||
); | ||||||
|
||||||
const inventoryCollection = client.db('testdb').collection('inventory'); | ||||||
|
||||||
// Within the session, for each item purchased, decrement the purchased quantity in the "inventory" collection. | ||||||
// Cancel the transaction when you have insufficient inventory or if the item SKU does not exist. | ||||||
for (let i=0; i<cart.length; i++) { | ||||||
const item = cart[i]; | ||||||
|
||||||
// Cancel the transaction when you have insufficient inventory | ||||||
// Retrieve the inventory information for the item | ||||||
const checkInventory = await inventoryCollection.findOne( | ||||||
{ | ||||||
sku: item.sku, | ||||||
qty: { $gte: item.qty } | ||||||
}, | ||||||
{ session } | ||||||
) | ||||||
// Throw an exception if the item lacks sufficient quantity or SKU does not exist. | ||||||
if (checkInventory === null) { | ||||||
throw new Error('Insufficient quantity or SKU not found.'); | ||||||
} | ||||||
|
||||||
// Decrement the inventory of the item by the amount specified in the order. | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
await inventoryCollection.updateOne( | ||||||
{ sku: item.sku }, | ||||||
{ $inc: { 'qty': -item.qty }}, | ||||||
|
@@ -86,15 +103,23 @@ async function placeOrder(client, cart, payment) { | |||||
} | ||||||
|
||||||
const customerCollection = client.db('testdb').collection('customers'); | ||||||
|
||||||
// Within the session, add the order details to the "orders" array of the customer document. | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
await customerCollection.updateOne( | ||||||
{ _id: payment.customer }, | ||||||
{ $push: { orders: orderResult.insertedId }}, | ||||||
{ session } | ||||||
); | ||||||
|
||||||
// Commit the transaction to apply all updates performed within it | ||||||
await session.commitTransaction(); | ||||||
console.log('Transaction successfully committed.'); | ||||||
|
||||||
} catch (error) { | ||||||
/* | ||||||
Handle any exceptions thrown during the transaction and end the | ||||||
transaction. Roll back all the updates performed in the transaction. | ||||||
*/ | ||||||
if (error instanceof MongoError && error.hasErrorLabel('UnknownTransactionCommitResult')) { | ||||||
// add your logic to retry or handle the error | ||||||
} | ||||||
|
@@ -105,28 +130,41 @@ async function placeOrder(client, cart, payment) { | |||||
} | ||||||
await session.abortTransaction(); | ||||||
} finally { | ||||||
// End the session so that no further calls can be made on it | ||||||
await session.endSession(); | ||||||
} | ||||||
} | ||||||
// end placeOrder | ||||||
|
||||||
|
||||||
// Run the full transaction example | ||||||
async function run() { | ||||||
const uri = process.env.MONGODB_URI; | ||||||
const client = new MongoClient(uri); | ||||||
|
||||||
// Call a method that removes data from prior runs of this example | ||||||
await cleanUp(client); | ||||||
|
||||||
// Call a method that creates sample inventory data for this example | ||||||
await setup(client); | ||||||
|
||||||
// Create sample data for a customer's shopping cart that includes "sunblock" and "beach towel" items | ||||||
const cart = [ | ||||||
{ name: 'sunblock', sku: 5432, qty: 1, price: 5.19 }, | ||||||
{ name: 'beach towel', sku: 7865, qty: 2, price: 15.99 } | ||||||
]; | ||||||
|
||||||
// Create sample data for a customer's payment, calculated from the contents of their cart | ||||||
const payment = { customer: 98765, total: 37.17 }; | ||||||
|
||||||
try { | ||||||
// Call the method that updates the customer and inventory in a transaction | ||||||
await placeOrder(client, cart, payment); | ||||||
} finally { | ||||||
// Call a method that removes data from prior runs of this example | ||||||
await cleanUp(client); | ||||||
|
||||||
// Close the database connection | ||||||
await client.close(); | ||||||
} | ||||||
} | ||||||
|
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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.