MCPcopy Create free account
hub / github.com/GoogleCloudPlatform/nodejs-docs-samples / writeWithTransactionUsingDml

Function writeWithTransactionUsingDml

spanner/dml.js:371–464  ·  view source on GitHub ↗
(instanceId, databaseId, projectId)

Source from the content-addressed store, hash-verified

369}
370
371async function writeWithTransactionUsingDml(instanceId, databaseId, projectId) {
372 // [START spanner_dml_getting_started_update]
373 // This sample transfers 200,000 from the MarketingBudget field
374 // of the second Album to the first Album, as long as the second
375 // Album has enough money in its budget. Make sure to run the
376 // addColumn and updateData samples first (in that order).
377
378 // Imports the Google Cloud client library
379 const {Spanner} = require('@google-cloud/spanner');
380
381 /**
382 * TODO(developer): Uncomment the following lines before running the sample.
383 */
384 // const projectId = 'my-project-id';
385 // const instanceId = 'my-instance';
386 // const databaseId = 'my-database';
387
388 // Creates a client
389 const spanner = new Spanner({
390 projectId: projectId,
391 });
392
393 // Gets a reference to a Cloud Spanner instance and database
394 const instance = spanner.instance(instanceId);
395 const database = instance.database(databaseId);
396
397 const transferAmount = 200000;
398
399 try {
400 await database.runTransactionAsync(async transaction => {
401 let firstBudget, secondBudget;
402 const queryOne = `SELECT MarketingBudget FROM Albums
403 WHERE SingerId = 2 AND AlbumId = 2`;
404
405 const queryTwo = `SELECT MarketingBudget FROM Albums
406 WHERE SingerId = 1 AND AlbumId = 1`;
407
408 // Reads the second album's budget
409 const [resultsOne] = await transaction.run(queryOne);
410 const rowsOne = resultsOne.map(row => row.toJSON());
411 secondBudget = rowsOne[0].MarketingBudget;
412 console.log(`The second album's marketing budget: ${secondBudget}`);
413
414 // Makes sure the second album's budget is large enough
415 if (secondBudget < transferAmount) {
416 throw new Error(
417 `The second album's budget (${secondBudget}) is less than the transfer amount (${transferAmount}).`
418 );
419 }
420
421 // Reads the first album's budget
422 const [resultsTwo] = await transaction.run(queryTwo);
423 const rowsTwo = resultsTwo.map(row => row.toJSON());
424 firstBudget = rowsTwo[0].MarketingBudget;
425 console.log(`The first album's marketing budget: ${firstBudget}`);
426
427 // Transfers the budgets between the albums
428 console.log(firstBudget, secondBudget);

Callers 1

dml.jsFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected