( instanceId = 'my-instance', databaseId = 'my-database', projectId = 'my-project-id' )
| 19 | 'use strict'; |
| 20 | |
| 21 | async function main( |
| 22 | instanceId = 'my-instance', |
| 23 | databaseId = 'my-database', |
| 24 | projectId = 'my-project-id' |
| 25 | ) { |
| 26 | // [START spanner_read_lock_mode] |
| 27 | // Imports the Google Cloud Spanner client library |
| 28 | const {Spanner, protos} = require('@google-cloud/spanner'); |
| 29 | // The read lock mode specified at the client-level will be applied |
| 30 | // to all RW transactions. |
| 31 | const defaultTransactionOptions = { |
| 32 | readLockMode: |
| 33 | protos.google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode |
| 34 | .OPTIMISTIC, |
| 35 | }; |
| 36 | |
| 37 | // Instantiates a client with defaultTransactionOptions |
| 38 | const spanner = new Spanner({ |
| 39 | projectId: projectId, |
| 40 | defaultTransactionOptions, |
| 41 | }); |
| 42 | |
| 43 | async function runTransactionWithReadLockMode() { |
| 44 | // Gets a reference to a Cloud Spanner instance and database |
| 45 | const instance = spanner.instance(instanceId); |
| 46 | const database = instance.database(databaseId); |
| 47 | // The read lock mode specified at the request-level takes precedence over |
| 48 | // the read lock mode configured at the client-level. |
| 49 | const readLockModeOptionsForTransaction = { |
| 50 | readLockMode: |
| 51 | protos.google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode |
| 52 | .PESSIMISTIC, |
| 53 | }; |
| 54 | |
| 55 | try { |
| 56 | // Use runTransactionAsync to safely handle the transaction lifecycle |
| 57 | await database.runTransactionAsync( |
| 58 | readLockModeOptionsForTransaction, |
| 59 | async transaction => { |
| 60 | const query = |
| 61 | 'SELECT AlbumTitle FROM Albums WHERE SingerId = 2 AND AlbumId = 1'; |
| 62 | |
| 63 | const [rows] = await transaction.run(query); |
| 64 | |
| 65 | // Gets first album's title cleanly using native .toJSON() |
| 66 | const albumTitle = rows[0].toJSON().AlbumTitle; |
| 67 | console.log(`previous album title ${albumTitle}`); |
| 68 | |
| 69 | const update = |
| 70 | "UPDATE Albums SET AlbumTitle = 'New Album Title' WHERE SingerId = 2 AND AlbumId = 1"; |
| 71 | const [rowCount] = await transaction.runUpdate(update); |
| 72 | console.log( |
| 73 | `Successfully updated ${rowCount} record in Albums table.` |
| 74 | ); |
| 75 | |
| 76 | await transaction.commit(); |
| 77 | console.log( |
| 78 | 'Successfully executed read-write transaction with readLockMode option.' |
no test coverage detected