(instanceId, databaseId, projectId)
| 84 | } |
| 85 | |
| 86 | async function readWriteTransaction(instanceId, databaseId, projectId) { |
| 87 | // [START spanner_read_write_transaction] |
| 88 | // This sample transfers 200,000 from the MarketingBudget field |
| 89 | // of the second Album to the first Album, as long as the second |
| 90 | // Album has enough money in its budget. Make sure to run the |
| 91 | // addColumn and updateData samples first (in that order). |
| 92 | |
| 93 | // Imports the Google Cloud client library |
| 94 | const {Spanner} = require('@google-cloud/spanner'); |
| 95 | |
| 96 | /** |
| 97 | * TODO(developer): Uncomment the following lines before running the sample. |
| 98 | */ |
| 99 | // const projectId = 'my-project-id'; |
| 100 | // const instanceId = 'my-instance'; |
| 101 | // const databaseId = 'my-database'; |
| 102 | |
| 103 | // Creates a client |
| 104 | const spanner = new Spanner({ |
| 105 | projectId: projectId, |
| 106 | }); |
| 107 | |
| 108 | let database; |
| 109 | const transferAmount = 200000; |
| 110 | |
| 111 | try { |
| 112 | // Gets a reference to a Cloud Spanner instance and database |
| 113 | const instance = spanner.instance(instanceId); |
| 114 | database = instance.database(databaseId); |
| 115 | |
| 116 | await database.runTransactionAsync(async transaction => { |
| 117 | let firstBudget, secondBudget; |
| 118 | const queryOne = { |
| 119 | columns: ['MarketingBudget'], |
| 120 | keys: [[2, 2]], // SingerId: 2, AlbumId: 2 |
| 121 | }; |
| 122 | |
| 123 | const queryTwo = { |
| 124 | columns: ['MarketingBudget'], |
| 125 | keys: [[1, 1]], // SingerId: 1, AlbumId: 1 |
| 126 | }; |
| 127 | |
| 128 | // Reads the second album's budget |
| 129 | const [resultsOne] = await transaction.read('Albums', queryOne); |
| 130 | const rowsOne = resultsOne.map(row => row.toJSON()); |
| 131 | secondBudget = rowsOne[0].MarketingBudget; |
| 132 | console.log(`The second album's marketing budget: ${secondBudget}`); |
| 133 | |
| 134 | // Makes sure the second album's budget is large enough |
| 135 | if (secondBudget < transferAmount) { |
| 136 | throw new Error( |
| 137 | `The second album's budget (${secondBudget}) is less than the transfer amount (${transferAmount}).` |
| 138 | ); |
| 139 | } |
| 140 | |
| 141 | // Reads the first album's budget |
| 142 | const [resultsTwo] = await transaction.read('Albums', queryTwo); |
| 143 | const rowsTwo = resultsTwo.map(row => row.toJSON()); |
no test coverage detected