-
Notifications
You must be signed in to change notification settings - Fork 101
/
crud.js
395 lines (345 loc) · 12.1 KB
/
crud.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
'use strict';
// sample-metadata:
// title: CRUD
async function updateData(instanceId, databaseId, projectId) {
// [START spanner_update_data]
// Imports the Google Cloud client library
const {Spanner} = require('@google-cloud/spanner');
/**
* TODO(developer): Uncomment the following lines before running the sample.
*/
// const projectId = 'my-project-id';
// const instanceId = 'my-instance';
// const databaseId = 'my-database';
// Creates a client
const spanner = new Spanner({
projectId: projectId,
});
// Gets a reference to a Cloud Spanner instance and database
const instance = spanner.instance(instanceId);
const database = instance.database(databaseId);
// Update a row in the Albums table
// Note: Cloud Spanner interprets Node.js numbers as FLOAT64s, so they
// must be converted to strings before being inserted as INT64s
const albumsTable = database.table('Albums');
try {
await albumsTable.update([
{SingerId: '1', AlbumId: '1', MarketingBudget: '100000'},
{SingerId: '2', AlbumId: '2', MarketingBudget: '500000'},
]);
console.log('Updated data.');
} catch (err) {
console.error('ERROR:', err);
} finally {
// Close the database when finished.
database.close();
}
// [END spanner_update_data]
}
async function insertData(instanceId, databaseId, projectId) {
// [START spanner_insert_data]
// Imports the Google Cloud client library
const {Spanner} = require('@google-cloud/spanner');
/**
* TODO(developer): Uncomment the following lines before running the sample.
*/
// const projectId = 'my-project-id';
// const instanceId = 'my-instance';
// const databaseId = 'my-database';
// Creates a client
const spanner = new Spanner({
projectId: projectId,
});
// Gets a reference to a Cloud Spanner instance and database
const instance = spanner.instance(instanceId);
const database = instance.database(databaseId);
// Instantiate Spanner table objects
const singersTable = database.table('Singers');
const albumsTable = database.table('Albums');
// Inserts rows into the Singers table
// Note: Cloud Spanner interprets Node.js numbers as FLOAT64s, so
// they must be converted to strings before being inserted as INT64s
try {
await singersTable.insert([
{SingerId: '1', FirstName: 'Marc', LastName: 'Richards'},
{SingerId: '2', FirstName: 'Catalina', LastName: 'Smith'},
{SingerId: '3', FirstName: 'Alice', LastName: 'Trentor'},
{SingerId: '4', FirstName: 'Lea', LastName: 'Martin'},
{SingerId: '5', FirstName: 'David', LastName: 'Lomond'},
]);
await albumsTable.insert([
{SingerId: '1', AlbumId: '1', AlbumTitle: 'Total Junk'},
{SingerId: '1', AlbumId: '2', AlbumTitle: 'Go, Go, Go'},
{SingerId: '2', AlbumId: '1', AlbumTitle: 'Green'},
{SingerId: '2', AlbumId: '2', AlbumTitle: 'Forever Hold your Peace'},
{SingerId: '2', AlbumId: '3', AlbumTitle: 'Terrified'},
]);
console.log('Inserted data.');
} catch (err) {
console.error('ERROR:', err);
} finally {
await database.close();
}
// [END spanner_insert_data]
}
async function deleteData(instanceId, databaseId, projectId) {
// [START spanner_delete_data]
// Imports the Google Cloud client library
const {Spanner} = require('@google-cloud/spanner');
/**
* TODO(developer): Uncomment the following lines before running the sample.
*/
// const projectId = 'my-project-id';
// const instanceId = 'my-instance';
// const databaseId = 'my-database';
// Creates a client
const spanner = new Spanner({
projectId: projectId,
});
// Gets a reference to a Cloud Spanner instance and database
const instance = spanner.instance(instanceId);
const database = instance.database(databaseId);
// Instantiate Spanner table object
const albumsTable = database.table('Albums');
// Deletes individual rows from the Albums table.
try {
const keys = [
[2, 1],
[2, 3],
];
await albumsTable.deleteRows(keys);
console.log('Deleted individual rows in Albums.');
} catch (err) {
console.error('ERROR:', err);
}
// Delete a range of rows where the column key is >=3 and <5
database.runTransaction(async (err, transaction) => {
if (err) {
console.error(err);
return;
}
try {
const [rowCount] = await transaction.runUpdate({
sql: 'DELETE FROM Singers WHERE SingerId >= 3 AND SingerId < 5',
});
console.log(`${rowCount} records deleted from Singers.`);
} catch (err) {
console.error('ERROR:', err);
}
// Deletes remaining rows from the Singers table and the Albums table,
// because Albums table is defined with ON DELETE CASCADE.
try {
// The WHERE clause is required for DELETE statements to prevent
// accidentally deleting all rows in a table.
// https://cloud.google.com/spanner/docs/dml-syntax#where_clause
const [rowCount] = await transaction.runUpdate({
sql: 'DELETE FROM Singers WHERE true',
});
console.log(`${rowCount} records deleted from Singers.`);
await transaction.commit();
} catch (err) {
console.error('ERROR:', err);
} finally {
// Close the database when finished.
await database.close();
}
});
// [END spanner_delete_data]
}
async function queryData(instanceId, databaseId, projectId) {
// [START spanner_query_data]
// Imports the Google Cloud client library
const {Spanner} = require('@google-cloud/spanner');
/**
* TODO(developer): Uncomment the following lines before running the sample.
*/
// const projectId = 'my-project-id';
// const instanceId = 'my-instance';
// const databaseId = 'my-database';
// Creates a client
const spanner = new Spanner({
projectId: projectId,
});
// Gets a reference to a Cloud Spanner instance and database
const instance = spanner.instance(instanceId);
const database = instance.database(databaseId);
const query = {
sql: 'SELECT SingerId, AlbumId, AlbumTitle FROM Albums',
};
// Queries rows from the Albums table
try {
const [rows] = await database.run(query);
rows.forEach(row => {
const json = row.toJSON();
console.log(
`SingerId: ${json.SingerId}, AlbumId: ${json.AlbumId}, AlbumTitle: ${json.AlbumTitle}`
);
});
} catch (err) {
console.error('ERROR:', err);
} finally {
// Close the database when finished.
await database.close();
}
// [END spanner_query_data]
}
async function readData(instanceId, databaseId, projectId) {
// [START spanner_read_data]
// Imports the Google Cloud client library
const {Spanner} = require('@google-cloud/spanner');
/**
* TODO(developer): Uncomment the following lines before running the sample.
*/
// const projectId = 'my-project-id';
// const instanceId = 'my-instance';
// const databaseId = 'my-database';
// Creates a client
const spanner = new Spanner({
projectId: projectId,
});
// Gets a reference to a Cloud Spanner instance and database
const instance = spanner.instance(instanceId);
const database = instance.database(databaseId);
// Reads rows from the Albums table
const albumsTable = database.table('Albums');
const query = {
columns: ['SingerId', 'AlbumId', 'AlbumTitle'],
keySet: {
all: true,
},
};
try {
const [rows] = await albumsTable.read(query);
rows.forEach(row => {
const json = row.toJSON();
console.log(
`SingerId: ${json.SingerId}, AlbumId: ${json.AlbumId}, AlbumTitle: ${json.AlbumTitle}`
);
});
} catch (err) {
console.error('ERROR:', err);
} finally {
// Close the database when finished.
await database.close();
}
// [END spanner_read_data]
}
async function readStaleData(instanceId, databaseId, projectId) {
// [START spanner_read_stale_data]
// Imports the Google Cloud client library
const {Spanner} = require('@google-cloud/spanner');
/**
* TODO(developer): Uncomment the following lines before running the sample.
*/
// const projectId = 'my-project-id';
// const instanceId = 'my-instance';
// const databaseId = 'my-database';
// Creates a client
const spanner = new Spanner({
projectId: projectId,
});
// Gets a reference to a Cloud Spanner instance and database
const instance = spanner.instance(instanceId);
const database = instance.database(databaseId);
// Reads rows from the Albums table
const albumsTable = database.table('Albums');
const query = {
columns: ['SingerId', 'AlbumId', 'AlbumTitle', 'MarketingBudget'],
keySet: {
all: true,
},
};
const options = {
// Guarantees that all writes committed more than 15000 milliseconds ago are visible
exactStaleness: 15000,
};
try {
const [rows] = await albumsTable.read(query, options);
rows.forEach(row => {
const json = row.toJSON();
const id = json.SingerId;
const album = json.AlbumId;
const title = json.AlbumTitle;
const budget = json.MarketingBudget ? json.MarketingBudget : '';
console.log(
`SingerId: ${id}, AlbumId: ${album}, AlbumTitle: ${title}, MarketingBudget: ${budget}`
);
});
} catch (err) {
console.error('ERROR:', err);
} finally {
// Close the database when finished.
await database.close();
}
// [END spanner_read_stale_data]
}
const {getCommitStats} = require('./get-commit-stats');
require('yargs')
.demand(1)
.command(
'update <instanceName> <databaseName> <projectId>',
'Modifies existing rows of data in an example Cloud Spanner table.',
{},
opts => updateData(opts.instanceName, opts.databaseName, opts.projectId)
)
.command(
'query <instanceName> <databaseName> <projectId>',
'Executes a read-only SQL query against an example Cloud Spanner table.',
{},
opts => queryData(opts.instanceName, opts.databaseName, opts.projectId)
)
.command(
'insert <instanceName> <databaseName> <projectId>',
'Inserts new rows of data into an example Cloud Spanner table.',
{},
opts => insertData(opts.instanceName, opts.databaseName, opts.projectId)
)
.command(
'delete <instanceName> <databaseName> <projectId>',
'Deletes rows from an example Cloud Spanner table.',
{},
opts => deleteData(opts.instanceName, opts.databaseName, opts.projectId)
)
.command(
'read <instanceName> <databaseName> <projectId>',
'Reads data in an example Cloud Spanner table.',
{},
opts => readData(opts.instanceName, opts.databaseName, opts.projectId)
)
.command(
'read-stale <instanceName> <databaseName> <projectId>',
'Reads stale data in an example Cloud Spanner table.',
{},
opts => readStaleData(opts.instanceName, opts.databaseName, opts.projectId)
)
.command(
'getCommitStats <instanceName> <databaseName> <projectId>',
'Updates rows in example Cloud Spanner table and reads CommitStats.',
{},
opts => getCommitStats(opts.instanceName, opts.databaseName, opts.projectId)
)
.example('node $0 update "my-instance" "my-database" "my-project-id"')
.example('node $0 query "my-instance" "my-database" "my-project-id"')
.example('node $0 insert "my-instance" "my-database" "my-project-id"')
.example('node $0 delete "my-instance" "my-database" "my-project-id"')
.example('node $0 read "my-instance" "my-database" "my-project-id"')
.example('node $0 read-stale "my-instance" "my-database" "my-project-id"')
.example('node $0 getCommitStats "my-instance" "my-database" "my-project-id"')
.wrap(120)
.recommendCommands()
.epilogue('For more information, see https://cloud.google.com/spanner/docs')
.strict()
.help().argv;