| 15 | 'use strict'; |
| 16 | |
| 17 | async function databaseWithQueryOptions(instanceId, databaseId, projectId) { |
| 18 | // [START spanner_create_client_with_query_options] |
| 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( |
| 38 | databaseId, |
| 39 | {}, |
| 40 | { |
| 41 | optimizerVersion: '1', |
| 42 | // The list of available statistics packages can be found by querying the |
| 43 | // "INFORMATION_SCHEMA.SPANNER_STATISTICS" table. |
| 44 | optimizerStatisticsPackage: 'latest', |
| 45 | } |
| 46 | ); |
| 47 | |
| 48 | const query = { |
| 49 | sql: `SELECT AlbumId, AlbumTitle, MarketingBudget |
| 50 | FROM Albums |
| 51 | ORDER BY AlbumTitle`, |
| 52 | }; |
| 53 | |
| 54 | // Queries rows from the Albums table |
| 55 | const [rows] = await database.run(query); |
| 56 | |
| 57 | rows.forEach(row => { |
| 58 | const json = row.toJSON(); |
| 59 | const marketingBudget = json.MarketingBudget |
| 60 | ? json.MarketingBudget |
| 61 | : null; // This value is nullable |
| 62 | console.log( |
| 63 | `AlbumId: ${json.AlbumId}, AlbumTitle: ${json.AlbumTitle}, MarketingBudget: ${marketingBudget}` |
| 64 | ); |
| 65 | }); |
| 66 | } catch (err) { |
| 67 | console.error('ERROR:', err); |
| 68 | } finally { |
| 69 | // Close the database when finished. |
| 70 | await database.close(); |
| 71 | } |
| 72 | // [END spanner_create_client_with_query_options] |
| 73 | } |
| 74 | |