| 113 | } |
| 114 | |
| 115 | async function deleteData(instanceId, databaseId, projectId) { |
| 116 | // [START spanner_delete_data] |
| 117 | // Imports the Google Cloud client library |
| 118 | const {Spanner} = require('@google-cloud/spanner'); |
| 119 | |
| 120 | /** |
| 121 | * TODO(developer): Uncomment the following lines before running the sample. |
| 122 | */ |
| 123 | // const projectId = 'my-project-id'; |
| 124 | // const instanceId = 'my-instance'; |
| 125 | // const databaseId = 'my-database'; |
| 126 | |
| 127 | // Creates a client |
| 128 | const spanner = new Spanner({ |
| 129 | projectId: projectId, |
| 130 | }); |
| 131 | |
| 132 | // Gets a reference to a Cloud Spanner instance and database |
| 133 | const instance = spanner.instance(instanceId); |
| 134 | const database = instance.database(databaseId); |
| 135 | |
| 136 | // Instantiate Spanner table object |
| 137 | const albumsTable = database.table('Albums'); |
| 138 | |
| 139 | // Deletes individual rows from the Albums table. |
| 140 | try { |
| 141 | const keys = [ |
| 142 | ['2', '1'], |
| 143 | ['2', '3'], |
| 144 | ]; |
| 145 | await albumsTable.deleteRows(keys); |
| 146 | console.log('Deleted individual rows in Albums.'); |
| 147 | } catch (err) { |
| 148 | console.error('ERROR:', err); |
| 149 | } |
| 150 | |
| 151 | // Delete a range of rows where the column key is >=3 and <5 |
| 152 | database.runTransaction(async (err, transaction) => { |
| 153 | if (err) { |
| 154 | console.error(err); |
| 155 | return; |
| 156 | } |
| 157 | try { |
| 158 | const [rowCount] = await transaction.runUpdate({ |
| 159 | sql: 'DELETE FROM Singers WHERE SingerId >= 3 AND SingerId < 5', |
| 160 | }); |
| 161 | console.log(`${rowCount} records deleted from Singers.`); |
| 162 | } catch (err) { |
| 163 | console.error('ERROR:', err); |
| 164 | } |
| 165 | |
| 166 | // Deletes remaining rows from the Singers table and the Albums table, |
| 167 | // because Albums table is defined with ON DELETE CASCADE. |
| 168 | try { |
| 169 | // The WHERE clause is required for DELETE statements to prevent |
| 170 | // accidentally deleting all rows in a table. |
| 171 | // https://cloud.google.com/spanner/docs/dml-syntax#where_clause |
| 172 | const [rowCount] = await transaction.runUpdate({ |