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

Function readOnlyTransaction

spanner/transaction.js:17–84  ·  view source on GitHub ↗
(instanceId, databaseId, projectId)

Source from the content-addressed store, hash-verified

15'use strict';
16
17async function readOnlyTransaction(instanceId, databaseId, projectId) {
18 // [START spanner_read_only_transaction]
19 // Imports the Google Cloud client library
20 const {Spanner} = require('@google-cloud/spanner');
21
22 /**
23 * TODO(developer): Uncomment the following lines before running the sample.
24 */
25 // const projectId = 'my-project-id';
26 // const instanceId = 'my-instance';
27 // const databaseId = 'my-database';
28
29 // Creates a client
30 const spanner = new Spanner({
31 projectId: projectId,
32 });
33 let database;
34 try {
35 // Gets a reference to a Cloud Spanner instance and database
36 const instance = spanner.instance(instanceId);
37 database = instance.database(databaseId);
38
39 // Gets a transaction object that captures the database state
40 // at a specific point in time
41 const [transaction] = await database.getSnapshot();
42
43 try {
44 const queryOne = 'SELECT SingerId, AlbumId, AlbumTitle FROM Albums';
45
46 // Read #1, using SQL
47 const [qOneRows] = await transaction.run(queryOne);
48
49 qOneRows.forEach(row => {
50 const json = row.toJSON();
51 console.log(
52 `SingerId: ${json.SingerId}, AlbumId: ${json.AlbumId}, AlbumTitle: ${json.AlbumTitle}`
53 );
54 });
55
56 const queryTwo = {
57 columns: ['SingerId', 'AlbumId', 'AlbumTitle'],
58 };
59
60 // Read #2, using the `read` method. Even if changes occur
61 // in-between the reads, the transaction ensures that both
62 // return the same data.
63 const [qTwoRows] = await transaction.read('Albums', queryTwo);
64
65 qTwoRows.forEach(row => {
66 const json = row.toJSON();
67 console.log(
68 `SingerId: ${json.SingerId}, AlbumId: ${json.AlbumId}, AlbumTitle: ${json.AlbumTitle}`
69 );
70 });
71
72 console.log('Successfully executed read-only transaction.');
73 } finally {
74 // Ensure the transaction is released

Callers 1

transaction.jsFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected