|
| 1 | +// Copyright 2016 Google LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +'use strict'; |
| 16 | + |
| 17 | +// [START spanner_quickstart] |
| 18 | +const {Spanner} = require('@google-cloud/spanner'); |
| 19 | +const {status} = require('@grpc/grpc-js'); |
| 20 | + |
| 21 | +// Creates a client using the ambient project ID or environment configuration |
| 22 | +const spanner = new Spanner(); |
| 23 | + |
| 24 | +/** |
| 25 | + * Executes a query against a Cloud Spanner database. |
| 26 | + * |
| 27 | + * @param {string} projectId The project ID containing the Spanner instance (for example, 'example-project-id'). |
| 28 | + * @param {string} instanceId The ID of the Spanner instance (for example, 'example-instance'). |
| 29 | + * @param {string} databaseId The ID of the Spanner database (for example 'example-database'). |
| 30 | + */ |
| 31 | +async function quickstart(projectId, instanceId, databaseId) { |
| 32 | + try { |
| 33 | + // Gets a reference to a Cloud Spanner instance and database |
| 34 | + const instance = spanner.instance(instanceId); |
| 35 | + const database = instance.database(databaseId); |
| 36 | + |
| 37 | + const query = { |
| 38 | + sql: 'SELECT 1', |
| 39 | + }; |
| 40 | + |
| 41 | + const [rows] = await database.run(query); |
| 42 | + |
| 43 | + console.log(`Query successfully executed. ${rows.length} row(s) found.`); |
| 44 | + rows.forEach(row => { |
| 45 | + console.log(` Row details: ${JSON.stringify(row)}`); |
| 46 | + }); |
| 47 | + } catch (err) { |
| 48 | + if (err.code === status.NOT_FOUND) { |
| 49 | + console.error( |
| 50 | + `Resource not found. Please verify that instance '${instanceId}' and database '${databaseId}' exist under project '${projectId}'.` |
| 51 | + ); |
| 52 | + } else { |
| 53 | + console.error('An unexpected error occurred during execution:', err); |
| 54 | + } |
| 55 | + } |
| 56 | +} |
| 57 | +// [END spanner_quickstart] |
| 58 | + |
| 59 | +if (require.main === module) { |
| 60 | + quickstart(...process.argv.slice(2)); |
| 61 | +} |
| 62 | + |
| 63 | +module.exports = {quickstart}; |
0 commit comments