| 15 | 'use strict'; |
| 16 | |
| 17 | async function createAndExecuteQueryPartitions( |
| 18 | instanceId, |
| 19 | databaseId, |
| 20 | projectId |
| 21 | ) { |
| 22 | // [START spanner_batch_client] |
| 23 | // Imports the Google Cloud client library |
| 24 | const {Spanner} = require('@google-cloud/spanner'); |
| 25 | |
| 26 | /** |
| 27 | * TODO(developer): Uncomment the following lines before running the sample. |
| 28 | */ |
| 29 | // const projectId = 'my-project-id'; |
| 30 | // const instanceId = 'my-instance'; |
| 31 | // const databaseId = 'my-database'; |
| 32 | |
| 33 | // Creates a client |
| 34 | const spanner = new Spanner({ |
| 35 | projectId: projectId, |
| 36 | }); |
| 37 | |
| 38 | // Gets a reference to a Cloud Spanner instance and database |
| 39 | const instance = spanner.instance(instanceId); |
| 40 | const database = instance.database(databaseId); |
| 41 | |
| 42 | let transaction; |
| 43 | |
| 44 | try { |
| 45 | [transaction] = await database.createBatchTransaction(); |
| 46 | |
| 47 | const query = { |
| 48 | sql: 'SELECT * FROM Singers', |
| 49 | // DataBoost option is an optional parameter which can also be used for partition read |
| 50 | // and query to execute the request via spanner independent compute resources. |
| 51 | dataBoostEnabled: true, |
| 52 | }; |
| 53 | |
| 54 | // A Partition object is serializable and can be used from a different process. |
| 55 | const [partitions] = await transaction.createQueryPartitions(query); |
| 56 | console.log(`Successfully created ${partitions.length} query partitions.`); |
| 57 | |
| 58 | let rowCount = 0; |
| 59 | const promises = partitions.map(partition => |
| 60 | transaction.execute(partition).then(results => { |
| 61 | const rows = results[0].map(row => row.toJSON()); |
| 62 | rowCount += rows.length; |
| 63 | }) |
| 64 | ); |
| 65 | await Promise.all(promises); |
| 66 | console.log(`Successfully received ${rowCount} from executed partitions.`); |
| 67 | } catch (err) { |
| 68 | console.error('Error executing query partitions:', err); |
| 69 | } finally { |
| 70 | if (transaction) { |
| 71 | transaction.close(); |
| 72 | } |
| 73 | await database.close(); |
| 74 | } |