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

Function main

spanner/repeatable-reads.js:21–88  ·  view source on GitHub ↗
(
  instanceId = 'my-instance',
  databaseId = 'my-database',
  projectId = 'my-project-id'
)

Source from the content-addressed store, hash-verified

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

Callers 1

Calls 1

Tested by

no test coverage detected