-
Notifications
You must be signed in to change notification settings - Fork 93
/
spanner.test.js
1382 lines (1268 loc) · 44.4 KB
/
spanner.test.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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2024 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';
const {Spanner} = require('@google-cloud/spanner');
const pLimit = require('p-limit');
const {describe, it, before, after, afterEach} = require('mocha');
const {KeyManagementServiceClient} = require('@google-cloud/kms');
const {assert} = require('chai');
const cp = require('child_process');
const execSync = cmd => cp.execSync(cmd, {encoding: 'utf-8'});
const instanceCmd = 'node instance.js';
const schemaCmd = 'node schema.js';
const backupsCmd = 'node backups.js';
const crudCmd = 'node crud.js';
const datatypesCmd = 'node datatypes.js';
const timestampCmd = 'node timestamp.js';
const createTableWithForeignKeyDeleteCascadeCommand =
'node table-create-with-foreign-key-delete-cascade.js';
const alterTableWithForeignKeyDeleteCascadeCommand =
'node table-alter-with-foreign-key-delete-cascade.js';
const dropForeignKeyConstraintDeleteCascaseCommand =
'node table-drop-foreign-key-constraint-delete-cascade.js';
const CURRENT_TIME = Math.round(Date.now() / 1000).toString();
const PROJECT_ID = process.env.GCLOUD_PROJECT;
const PREFIX = 'test-instance';
const SAMPLE_INSTANCE_ID = `${PREFIX}-my-sample-instance-${CURRENT_TIME}`;
const INSTANCE_ID =
process.env.SPANNERTEST_INSTANCE || `${PREFIX}-${CURRENT_TIME}`;
const SAMPLE_INSTANCE_CONFIG_ID = `custom-my-sample-instance-config-${CURRENT_TIME}`;
const INSTANCE_ALREADY_EXISTS = !!process.env.SPANNERTEST_INSTANCE;
const BASE_INSTANCE_CONFIG_ID = 'regional-us-central1';
const DATABASE_ID = `test-database-${CURRENT_TIME}`;
const ENCRYPTED_DATABASE_ID = `test-database-${CURRENT_TIME}-enc`;
const DEFAULT_LEADER_DATABASE_ID = `test-database-${CURRENT_TIME}-dl`;
const VERSION_RETENTION_DATABASE_ID = `test-database-${CURRENT_TIME}-v`;
const SEQUENCE_DATABASE_ID = `test-seq-database-${CURRENT_TIME}-r`;
const PG_DATABASE_ID = `test-pg-database-${CURRENT_TIME}`;
const RESTORE_DATABASE_ID = `test-database-${CURRENT_TIME}-r`;
const ENCRYPTED_RESTORE_DATABASE_ID = `test-database-${CURRENT_TIME}-r-enc`;
const BACKUP_ID = `test-backup-${CURRENT_TIME}`;
const COPY_BACKUP_ID = `test-copy-backup-${CURRENT_TIME}`;
const ENCRYPTED_BACKUP_ID = `test-backup-${CURRENT_TIME}-enc`;
const CANCELLED_BACKUP_ID = `test-backup-${CURRENT_TIME}-c`;
const LOCATION_ID = 'regional-us-central1';
const PG_LOCATION_ID = 'regional-us-west2';
const KEY_LOCATION_ID = 'us-central1';
const KEY_RING_ID = 'test-key-ring-node';
const KEY_ID = 'test-key';
const DEFAULT_LEADER = 'us-central1';
const DEFAULT_LEADER_2 = 'us-east1';
const spanner = new Spanner({
projectId: PROJECT_ID,
});
const LABEL = 'node-sample-tests';
const GAX_OPTIONS = {
retry: {
retryCodes: [4, 8, 14],
backoffSettings: {
initialRetryDelayMillis: 1000,
retryDelayMultiplier: 1.3,
maxRetryDelayMillis: 32000,
initialRpcTimeoutMillis: 60000,
rpcTimeoutMultiplier: 1,
maxRpcTimeoutMillis: 60000,
totalTimeoutMillis: 600000,
},
},
};
const delay = async test => {
const retries = test.currentRetry();
// No retry on the first failure.
if (retries === 0) return;
// See: https://cloud.google.com/storage/docs/exponential-backoff
const ms = Math.pow(2, retries) + Math.random() * 1000;
return new Promise(done => {
console.info(`retrying "${test.title}" in ${ms}ms`);
setTimeout(done, ms);
});
};
async function deleteStaleInstances() {
let [instances] = await spanner.getInstances({
filter: `(labels.${LABEL}:true) OR (labels.cloud_spanner_samples:true)`,
});
const old = new Date();
old.setHours(old.getHours() - 4);
instances = instances.filter(instance => {
return (
instance.metadata.labels['created'] &&
new Date(parseInt(instance.metadata.labels['created']) * 1000) < old
);
});
const limit = pLimit(5);
await Promise.all(
instances.map(instance =>
limit(() => setTimeout(deleteInstance, delay, instance))
)
);
}
async function deleteInstance(instance) {
const [backups] = await instance.getBackups();
await Promise.all(backups.map(backup => backup.delete(GAX_OPTIONS)));
return instance.delete(GAX_OPTIONS);
}
async function getCryptoKey() {
const NOT_FOUND = 5;
// Instantiates a client.
const client = new KeyManagementServiceClient();
// Build the parent key ring name.
const keyRingName = client.keyRingPath(
PROJECT_ID,
KEY_LOCATION_ID,
KEY_RING_ID
);
// Get key ring.
try {
await client.getKeyRing({name: keyRingName});
} catch (err) {
// Create key ring if it doesn't exist.
if (err.code === NOT_FOUND) {
// Build the parent location name.
const locationName = client.locationPath(PROJECT_ID, KEY_LOCATION_ID);
await client.createKeyRing({
parent: locationName,
keyRingId: KEY_RING_ID,
});
} else {
throw err;
}
}
// Get key.
try {
// Build the key name
const keyName = client.cryptoKeyPath(
PROJECT_ID,
KEY_LOCATION_ID,
KEY_RING_ID,
KEY_ID
);
const [key] = await client.getCryptoKey({
name: keyName,
});
return key;
} catch (err) {
// Create key if it doesn't exist.
if (err.code === NOT_FOUND) {
const [key] = await client.createCryptoKey({
parent: keyRingName,
cryptoKeyId: KEY_ID,
cryptoKey: {
purpose: 'ENCRYPT_DECRYPT',
versionTemplate: {
algorithm: 'GOOGLE_SYMMETRIC_ENCRYPTION',
},
},
});
return key;
} else {
throw err;
}
}
}
describe('Autogenerated Admin Clients', () => {
const instance = spanner.instance(INSTANCE_ID);
before(async () => {
await deleteStaleInstances();
if (!INSTANCE_ALREADY_EXISTS) {
const [, operation] = await instance.create({
config: LOCATION_ID,
nodes: 1,
labels: {
[LABEL]: 'true',
created: CURRENT_TIME,
},
gaxOptions: GAX_OPTIONS,
});
return operation.promise();
} else {
console.log(
`Not creating temp instance, using + ${instance.formattedName_}...`
);
}
});
after(async () => {
const instance = spanner.instance(INSTANCE_ID);
if (!INSTANCE_ALREADY_EXISTS) {
// Make sure all backups are deleted before an instance can be deleted.
await Promise.all([
instance.backup(BACKUP_ID).delete(GAX_OPTIONS),
instance.backup(ENCRYPTED_BACKUP_ID).delete(GAX_OPTIONS),
instance.backup(COPY_BACKUP_ID).delete(GAX_OPTIONS),
instance.backup(CANCELLED_BACKUP_ID).delete(GAX_OPTIONS),
]);
await instance.delete(GAX_OPTIONS);
} else {
await Promise.all([
instance.database(DATABASE_ID).delete(),
instance.database(PG_DATABASE_ID).delete(),
instance.database(RESTORE_DATABASE_ID).delete(),
instance.database(ENCRYPTED_RESTORE_DATABASE_ID).delete(),
instance.backup(BACKUP_ID).delete(GAX_OPTIONS),
instance.backup(COPY_BACKUP_ID).delete(GAX_OPTIONS),
instance.backup(ENCRYPTED_BACKUP_ID).delete(GAX_OPTIONS),
instance.backup(CANCELLED_BACKUP_ID).delete(GAX_OPTIONS),
]);
}
await spanner.instance(SAMPLE_INSTANCE_ID).delete(GAX_OPTIONS);
});
describe('instance', () => {
afterEach(async () => {
const sample_instance = spanner.instance(SAMPLE_INSTANCE_ID);
await sample_instance.delete();
});
// create_instance
it('should create an example instance', async () => {
const output = execSync(
`${instanceCmd} createInstance "${SAMPLE_INSTANCE_ID}" ${PROJECT_ID}`
);
assert.match(
output,
new RegExp(
`Waiting for operation on ${SAMPLE_INSTANCE_ID} to complete...`
)
);
assert.match(
output,
new RegExp(`Created instance ${SAMPLE_INSTANCE_ID}.`)
);
});
// create_instance_with_processing_units
it('should create an example instance with processing units', async () => {
const output = execSync(
`${instanceCmd} createInstanceWithProcessingUnits "${SAMPLE_INSTANCE_ID}" ${PROJECT_ID}`
);
assert.match(
output,
new RegExp(
`Waiting for operation on ${SAMPLE_INSTANCE_ID} to complete...`
)
);
assert.match(
output,
new RegExp(`Created instance ${SAMPLE_INSTANCE_ID}.`)
);
assert.match(
output,
new RegExp(`Instance ${SAMPLE_INSTANCE_ID} has 500 processing units.`)
);
});
// create_instance_with_autoscaling_config
it('should create an example instance with autoscaling config', async () => {
const output = execSync(
`node instance-with-autoscaling-config.js "${SAMPLE_INSTANCE_ID}" ${PROJECT_ID}`
);
assert.match(
output,
new RegExp(
`Waiting for operation on ${SAMPLE_INSTANCE_ID} to complete...`
)
);
assert.match(
output,
new RegExp(`Created instance ${SAMPLE_INSTANCE_ID}.`)
);
assert.match(
output,
new RegExp(
`Autoscaling configurations of ${SAMPLE_INSTANCE_ID} are: ` +
'\n' +
'Min nodes: 1 ' +
'nodes.' +
'\n' +
'Max nodes: 2' +
' nodes.' +
'\n' +
'High priority cpu utilization percent: 65.' +
'\n' +
'Storage utilization percent: 95.'
)
);
});
});
// check that base instance was created
it('should have created an instance', async () => {
const [exists] = await instance.exists();
assert.strictEqual(
exists,
true,
'The main instance was not created successfully!'
);
});
// create_database
it('should create an example database', async () => {
const output = execSync(
`${schemaCmd} createDatabase "${INSTANCE_ID}" "${DATABASE_ID}" "${PROJECT_ID}"`
);
assert.match(
output,
new RegExp(`Waiting for creation of ${DATABASE_ID} to complete...`)
);
assert.match(
output,
new RegExp(`Created database ${DATABASE_ID} on instance ${INSTANCE_ID}.`)
);
});
// update_database
it('should set database metadata', async () => {
const output = execSync(
`node database-update.js ${INSTANCE_ID} ${DATABASE_ID} ${PROJECT_ID}`
);
assert.match(
output,
new RegExp(
`Waiting for update operation for ${DATABASE_ID} to complete...`
)
);
assert.match(output, new RegExp(`Updated database ${DATABASE_ID}.`));
// cleanup
const [operation] = await instance
.database(DATABASE_ID)
.setMetadata({enableDropProtection: false});
await operation.promise();
});
describe('encrypted database', () => {
after(async () => {
const instance = spanner.instance(INSTANCE_ID);
const encrypted_database = instance.database(ENCRYPTED_DATABASE_ID);
await encrypted_database.delete();
});
// create_database_with_encryption_key
it('should create a database with an encryption key', async () => {
const key = await getCryptoKey();
const output = execSync(
`${schemaCmd} createDatabaseWithEncryptionKey "${INSTANCE_ID}" "${ENCRYPTED_DATABASE_ID}" "${PROJECT_ID}" "${key.name}"`
);
assert.match(
output,
new RegExp(
`Waiting for operation on ${ENCRYPTED_DATABASE_ID} to complete...`
)
);
assert.match(
output,
new RegExp(
`Created database ${ENCRYPTED_DATABASE_ID} on instance ${INSTANCE_ID}.`
)
);
assert.match(
output,
new RegExp(`Database encrypted with key ${key.name}.`)
);
});
});
describe('postgreSQL', () => {
before(async () => {
const instance = spanner.instance(SAMPLE_INSTANCE_ID);
const [, operation] = await instance.create({
config: PG_LOCATION_ID,
nodes: 1,
displayName: 'PostgreSQL Test',
labels: {
['cloud_spanner_samples']: 'true',
created: Math.round(Date.now() / 1000).toString(), // current time
},
});
await operation.promise();
});
after(async () => {
const instance = spanner.instance(SAMPLE_INSTANCE_ID);
await instance.delete();
});
// create_pg_database
it('should create an example PostgreSQL database', async () => {
const output = execSync(
`node pg-database-create.js ${SAMPLE_INSTANCE_ID} ${PG_DATABASE_ID} ${PROJECT_ID}`
);
assert.match(
output,
new RegExp(`Waiting for operation on ${PG_DATABASE_ID} to complete...`)
);
assert.match(
output,
new RegExp(
`Created database ${PG_DATABASE_ID} on instance ${SAMPLE_INSTANCE_ID} with dialect POSTGRESQL.`
)
);
});
// pg_interleaving
it('should create an interleaved table hierarchy using PostgreSQL dialect', async () => {
const output = execSync(
`node pg-interleaving.js ${SAMPLE_INSTANCE_ID} ${PG_DATABASE_ID} ${PROJECT_ID}`
);
assert.match(
output,
new RegExp(`Waiting for operation on ${PG_DATABASE_ID} to complete...`)
);
assert.match(
output,
new RegExp(
`Created an interleaved table hierarchy in database ${PG_DATABASE_ID} using PostgreSQL dialect.`
)
);
});
// pg_add_column
it('should add a column to a table in the Spanner PostgreSQL database.', async () => {
const output = execSync(
`node pg-add-column.js ${SAMPLE_INSTANCE_ID} ${PG_DATABASE_ID} ${PROJECT_ID}`
);
assert.match(
output,
new RegExp(
`Added MarketingBudget column to Albums table in database ${PG_DATABASE_ID}`
)
);
});
//pg_create_index
it('should create an index in the Spanner PostgreSQL database.', async () => {
const output = execSync(
`node pg-index-create-storing.js ${SAMPLE_INSTANCE_ID} ${PG_DATABASE_ID} ${PROJECT_ID}`
);
assert.match(output, new RegExp('Added the AlbumsByAlbumTitle index.'));
});
// pg_numeric_data_type
it('should create a table, insert and query pg numeric data', async () => {
const output = execSync(
`node pg-numeric-data-type.js ${SAMPLE_INSTANCE_ID} ${PG_DATABASE_ID} ${PROJECT_ID}`
);
assert.match(
output,
new RegExp(`Waiting for operation on ${PG_DATABASE_ID} to complete...`)
);
assert.match(
output,
new RegExp(`Added table venues to database ${PG_DATABASE_ID}.`)
);
assert.match(output, new RegExp('Inserted data.'));
assert.match(output, new RegExp('VenueId: 4, Revenue: 97372.3863'));
assert.match(output, new RegExp('VenueId: 19, Revenue: 7629'));
assert.match(output, new RegExp('VenueId: 398, Revenue: 0.000000123'));
});
// pg_jsonb_add_column
it('should add a jsonb column to a table', async () => {
const output = execSync(
`node pg-jsonb-add-column.js ${SAMPLE_INSTANCE_ID} ${PG_DATABASE_ID} ${PROJECT_ID}`
);
assert.match(
output,
new RegExp(`Waiting for operation on ${PG_DATABASE_ID} to complete...`)
);
assert.match(
output,
new RegExp(
`Added jsonb column to table venues to database ${PG_DATABASE_ID}.`
)
);
});
// pg_create_sequence
it('should create a sequence', async () => {
const output = execSync(
`node pg-sequence-create.js ${SAMPLE_INSTANCE_ID} ${PG_DATABASE_ID} ${PROJECT_ID}`
);
assert.match(
output,
new RegExp('Created Seq sequence and Customers table')
);
assert.match(
output,
new RegExp('Number of customer records inserted is: 3')
);
});
// pg_alter_sequence
it('should alter a sequence', async () => {
const output = execSync(
`node pg-sequence-alter.js ${SAMPLE_INSTANCE_ID} ${PG_DATABASE_ID} ${PROJECT_ID}`
);
assert.match(
output,
new RegExp(
'Altered Seq sequence to skip an inclusive range between 1000 and 5000000.'
)
);
assert.match(
output,
new RegExp('Number of customer records inserted is: 3')
);
});
// pg_drop_sequence
it('should drop a sequence', async () => {
const output = execSync(
`node pg-sequence-drop.js ${SAMPLE_INSTANCE_ID} ${PG_DATABASE_ID} ${PROJECT_ID}`
);
assert.match(
output,
new RegExp(
'Altered Customers table to drop DEFAULT from CustomerId column and dropped the Seq sequence.'
)
);
});
});
// insert_data
it('should insert rows into an example table', async () => {
const output = execSync(
`${crudCmd} insert ${INSTANCE_ID} ${DATABASE_ID} ${PROJECT_ID}`
);
assert.match(output, /Inserted data\./);
});
// add_column
it('should add a column to a table', async () => {
const output = execSync(
`${schemaCmd} addColumn ${INSTANCE_ID} ${DATABASE_ID} ${PROJECT_ID}`
);
assert.match(output, /Waiting for operation to complete\.\.\./);
assert.match(output, /Added the MarketingBudget column\./);
});
// update_data
it('should update existing rows in an example table', async () => {
const output = execSync(
`${crudCmd} update ${INSTANCE_ID} ${DATABASE_ID} ${PROJECT_ID}`
);
assert.match(output, /Updated data\./);
});
// query_data_with_new_column
it('should query an example table with an additional column and return matching rows', async () => {
const output = execSync(
`${schemaCmd} queryNewColumn ${INSTANCE_ID} ${DATABASE_ID} ${PROJECT_ID}`
);
assert.match(output, /SingerId: 1, AlbumId: 1, MarketingBudget: 100000/);
assert.match(output, /SingerId: 2, AlbumId: 2, MarketingBudget: 500000/);
});
// create_index
it('should create an index in an example table', async () => {
const output = execSync(
`node index-create ${INSTANCE_ID} ${DATABASE_ID} ${PROJECT_ID}`
);
assert.match(output, /Waiting for operation to complete\.\.\./);
assert.match(output, /Added the AlbumsByAlbumTitle index\./);
});
// create_storing_index
it('should create a storing index in an example table', async function () {
this.retries(5);
// Delay the start of the test, if this is a retry.
await delay(this.test);
const output = execSync(
`node index-create-storing ${INSTANCE_ID} ${DATABASE_ID} ${PROJECT_ID}`
);
assert.match(output, /Waiting for operation to complete\.\.\./);
assert.match(output, /Added the AlbumsByAlbumTitle2 index\./);
});
// add_timestamp_column
it('should add a timestamp column to a table', async () => {
const output = execSync(
`${timestampCmd} addTimestampColumn ${INSTANCE_ID} ${DATABASE_ID} ${PROJECT_ID}`
);
assert.match(output, /Waiting for operation to complete\.\.\./);
assert.match(
output,
/Added LastUpdateTime as a commit timestamp column in Albums table\./
);
});
// update_data_with_timestamp_column
it('should update existing rows in an example table with commit timestamp column', async () => {
const output = execSync(
`${timestampCmd} updateWithTimestamp ${INSTANCE_ID} ${DATABASE_ID} ${PROJECT_ID}`
);
assert.match(output, /Updated data\./);
});
// query_data_with_timestamp_column
it('should query an example table with an additional timestamp column and return matching rows', async () => {
const output = execSync(
`${timestampCmd} queryWithTimestamp ${INSTANCE_ID} ${DATABASE_ID} ${PROJECT_ID}`
);
assert.match(
output,
/SingerId: 1, AlbumId: 1, MarketingBudget: 1000000, LastUpdateTime:/
);
assert.match(
output,
/SingerId: 2, AlbumId: 2, MarketingBudget: 750000, LastUpdateTime:/
);
});
// create_table_with_timestamp_column
it('should create an example table with a timestamp column', async () => {
const output = execSync(
`${timestampCmd} createTableWithTimestamp "${INSTANCE_ID}" "${DATABASE_ID}" ${PROJECT_ID}`
);
assert.match(
output,
new RegExp(`Waiting for operation on ${DATABASE_ID} to complete...`)
);
assert.match(
output,
new RegExp(`Created table Performances in database ${DATABASE_ID}.`)
);
});
// insert_data_with_timestamp
it('should insert rows into an example table with timestamp column', async () => {
const output = execSync(
`${timestampCmd} insertWithTimestamp ${INSTANCE_ID} ${DATABASE_ID} ${PROJECT_ID}`
);
assert.match(output, /Inserted data\./);
});
// query_new_table_with_timestamp
it('should query an example table with a non-null timestamp column and return matching rows', async () => {
const output = execSync(
`${timestampCmd} queryTableWithTimestamp ${INSTANCE_ID} ${DATABASE_ID} ${PROJECT_ID}`
);
assert.match(output, /SingerId: 1, VenueId: 4, EventDate:/);
assert.match(output, /Revenue: 15000, LastUpdateTime:/);
});
// create_table_with_datatypes
it('should create Venues example table with supported datatype columns', async () => {
const output = execSync(
`${datatypesCmd} createVenuesTable "${INSTANCE_ID}" "${DATABASE_ID}" ${PROJECT_ID}`
);
assert.match(
output,
new RegExp(`Waiting for operation on ${DATABASE_ID} to complete...`)
);
assert.match(
output,
new RegExp(`Created table Venues in database ${DATABASE_ID}.`)
);
});
// insert_datatypes_data
it('should insert multiple records into Venues example table', async () => {
const output = execSync(
`${datatypesCmd} insertData ${INSTANCE_ID} ${DATABASE_ID} ${PROJECT_ID}`
);
assert.match(output, /Inserted data./);
});
// query_with_array_parameter
it('should use an ARRAY query parameter to query record from the Venues example table', async () => {
const output = execSync(
`${datatypesCmd} queryWithArray ${INSTANCE_ID} ${DATABASE_ID} ${PROJECT_ID}`
);
assert.match(
output,
/VenueId: 19, VenueName: Venue 19, AvailableDate: 2020-11-01/
);
assert.match(
output,
/VenueId: 42, VenueName: Venue 42, AvailableDate: 2020-10-01/
);
});
// query_with_bool_parameter
it('should use a BOOL query parameter to query record from the Venues example table', async () => {
const output = execSync(
`${datatypesCmd} queryWithBool ${INSTANCE_ID} ${DATABASE_ID} ${PROJECT_ID}`
);
assert.match(
output,
/VenueId: 19, VenueName: Venue 19, OutdoorVenue: true/
);
});
// query_with_bytes_parameter
it('should use a BYTES query parameter to query record from the Venues example table', async () => {
const output = execSync(
`${datatypesCmd} queryWithBytes ${INSTANCE_ID} ${DATABASE_ID} ${PROJECT_ID}`
);
assert.match(output, /VenueId: 4, VenueName: Venue 4/);
});
// query_with_date_parameter
it('should use a DATE query parameter to query record from the Venues example table', async () => {
const output = execSync(
`${datatypesCmd} queryWithDate ${INSTANCE_ID} ${DATABASE_ID} ${PROJECT_ID}`
);
assert.match(
output,
/VenueId: 4, VenueName: Venue 4, LastContactDate: 2018-09-02/
);
assert.match(
output,
/VenueId: 42, VenueName: Venue 42, LastContactDate: 2018-10-01/
);
});
// query_with_float_parameter
it('should use a FLOAT64 query parameter to query record from the Venues example table', async () => {
const output = execSync(
`${datatypesCmd} queryWithFloat ${INSTANCE_ID} ${DATABASE_ID} ${PROJECT_ID}`
);
assert.match(
output,
/VenueId: 4, VenueName: Venue 4, PopularityScore: 0.8/
);
assert.match(
output,
/VenueId: 19, VenueName: Venue 19, PopularityScore: 0.9/
);
});
// query_with_int_parameter
it('should use a INT64 query parameter to query record from the Venues example table', async () => {
const output = execSync(
`${datatypesCmd} queryWithInt ${INSTANCE_ID} ${DATABASE_ID} ${PROJECT_ID}`
);
assert.match(output, /VenueId: 19, VenueName: Venue 19, Capacity: 6300/);
assert.match(output, /VenueId: 42, VenueName: Venue 42, Capacity: 3000/);
});
// query_with_string_parameter
it('should use a STRING query parameter to query record from the Venues example table', async () => {
const output = execSync(
`${datatypesCmd} queryWithString ${INSTANCE_ID} ${DATABASE_ID} ${PROJECT_ID}`
);
assert.match(output, /VenueId: 42, VenueName: Venue 42/);
});
// query_with_timestamp_parameter
it('should use a TIMESTAMP query parameter to query record from the Venues example table', async () => {
const output = execSync(
`${datatypesCmd} queryWithTimestamp ${INSTANCE_ID} ${DATABASE_ID} ${PROJECT_ID}`
);
assert.match(output, /VenueId: 4, VenueName: Venue 4, LastUpdateTime:/);
assert.match(output, /VenueId: 19, VenueName: Venue 19, LastUpdateTime:/);
assert.match(output, /VenueId: 42, VenueName: Venue 42, LastUpdateTime:/);
});
// add_numeric_column
it('should add a Revenue column to Venues example table', async () => {
const output = execSync(
`${datatypesCmd} addNumericColumn "${INSTANCE_ID}" "${DATABASE_ID}" ${PROJECT_ID}`
);
assert.include(
output,
`Waiting for operation on ${DATABASE_ID} to complete...`
);
assert.include(
output,
`Added Revenue column to Venues table in database ${DATABASE_ID}.`
);
});
// update_data_with_numeric
it('should update rows in Venues example table to add data in Revenue column', async () => {
const output = execSync(
`${datatypesCmd} updateWithNumericData ${INSTANCE_ID} ${DATABASE_ID} ${PROJECT_ID}`
);
assert.match(output, /Updated data./);
});
// query_with_numeric_parameter
it('should use a NUMERIC query parameter to query records from the Venues example table', async () => {
const output = execSync(
`${datatypesCmd} queryWithNumericParameter ${INSTANCE_ID} ${DATABASE_ID} ${PROJECT_ID}`
);
assert.match(output, /VenueId: 4, Revenue: 35000/);
});
// add_json_column
it('should add a VenueDetails column to Venues example table', async () => {
const output = execSync(
`${datatypesCmd} addJsonColumn "${INSTANCE_ID}" "${DATABASE_ID}" ${PROJECT_ID}`
);
assert.include(
output,
`Waiting for operation on ${DATABASE_ID} to complete...`
);
assert.include(
output,
`Added VenueDetails column to Venues table in database ${DATABASE_ID}.`
);
});
// update_data_with_json
it('should update rows in Venues example table to add data in VenueDetails column', async () => {
const output = execSync(
`${datatypesCmd} updateWithJsonData ${INSTANCE_ID} ${DATABASE_ID} ${PROJECT_ID}`
);
assert.match(output, /Updated data./);
});
// query_with_json_parameter
it('should use a JSON query parameter to query records from the Venues example table', async () => {
const output = execSync(
`${datatypesCmd} queryWithJsonParameter ${INSTANCE_ID} ${DATABASE_ID} ${PROJECT_ID}`
);
assert.match(output, /VenueId: 19, Details: {"open":true,"rating":9}/);
});
// add_and_drop_new_database_role
it('should add and drop new database roles', async () => {
const output = execSync(
`node add-and-drop-new-database-role.js ${INSTANCE_ID} ${DATABASE_ID} ${PROJECT_ID}`
);
assert.match(output, new RegExp('Waiting for operation to complete...'));
assert.match(
output,
new RegExp('Created roles child and parent and granted privileges')
);
assert.match(
output,
new RegExp('Revoked privileges and dropped role child')
);
});
// get_database_roles
it('should list database roles', async () => {
const output = execSync(
`node get-database-roles.js ${INSTANCE_ID} ${DATABASE_ID} ${PROJECT_ID}`
);
assert.match(
output,
new RegExp(
`Role: projects/${PROJECT_ID}/instances/${INSTANCE_ID}/databases/${DATABASE_ID}/databaseRoles/public`
)
);
});
// create_backup
it('should create a backup of the database', async () => {
const instance = spanner.instance(INSTANCE_ID);
const database = instance.database(DATABASE_ID);
const query = {
sql: 'SELECT CURRENT_TIMESTAMP() as Timestamp',
};
const [rows] = await database.run(query);
const versionTime = rows[0].toJSON().Timestamp.toISOString();
const output = execSync(
`${backupsCmd} createBackup ${INSTANCE_ID} ${DATABASE_ID} ${BACKUP_ID} ${PROJECT_ID} ${versionTime}`
);
assert.match(output, new RegExp(`Backup (.+)${BACKUP_ID} of size`));
});
// create_backup_with_encryption_key
it('should create an encrypted backup of the database', async () => {
const key = await getCryptoKey();
const output = execSync(
`${backupsCmd} createBackupWithEncryptionKey ${INSTANCE_ID} ${DATABASE_ID} ${ENCRYPTED_BACKUP_ID} ${PROJECT_ID} ${key.name}`
);
assert.match(
output,
new RegExp(`Backup (.+)${ENCRYPTED_BACKUP_ID} of size`)
);
assert.include(output, `using encryption key ${key.name}`);
});
// copy_backup
it('should create a copy of a backup', async () => {
const sourceBackupPath = `projects/${PROJECT_ID}/instances/${INSTANCE_ID}/backups/${BACKUP_ID}`;
const output = execSync(
`node backups-copy.js ${INSTANCE_ID} ${COPY_BACKUP_ID} ${sourceBackupPath} ${PROJECT_ID}`
);
assert.match(
output,
new RegExp(`(.*)Backup copy(.*)${COPY_BACKUP_ID} of size(.*)`)
);
});
// cancel_backup
it('should cancel a backup of the database', async () => {
const output = execSync(
`${backupsCmd} cancelBackup ${INSTANCE_ID} ${DATABASE_ID} ${CANCELLED_BACKUP_ID} ${PROJECT_ID}`
);
assert.match(output, /Backup cancelled./);
});
// get_backups
it('should list backups in the instance', async () => {
const output = execSync(
`${backupsCmd} getBackups ${INSTANCE_ID} ${DATABASE_ID} ${BACKUP_ID} ${PROJECT_ID}`
);
assert.include(output, 'All backups:');
assert.include(output, 'Backups matching backup name:');
assert.include(output, 'Backups expiring within 30 days:');
assert.include(output, 'Backups matching database name:');
assert.include(output, 'Backups filtered by size:');
assert.include(output, 'Ready backups filtered by create time:');
assert.include(output, 'Get backups paginated:');
const count = (output.match(new RegExp(`${BACKUP_ID}`, 'g')) || []).length;
assert.equal(count, 14);
});
// list_backup_operations
it('should list backup operations in the instance', async () => {
const output = execSync(
`${backupsCmd} getBackupOperations ${INSTANCE_ID} ${DATABASE_ID} ${BACKUP_ID} ${PROJECT_ID}`
);
assert.match(output, /Create Backup Operations:/);
assert.match(
output,
new RegExp(
`Backup (.+)${BACKUP_ID} on database (.+)${DATABASE_ID} is 100% complete.`
)
);
assert.match(output, /Copy Backup Operations:/);
assert.match(
output,
new RegExp(
`Backup (.+)${COPY_BACKUP_ID} copied from source backup (.+)${BACKUP_ID} is 100% complete`
)
);
});
// update_backup_expire_time
it('should update the expire time of a backup', async () => {
const output = execSync(
`${backupsCmd} updateBackup ${INSTANCE_ID} ${BACKUP_ID} ${PROJECT_ID}`
);
assert.match(output, /Expire time updated./);
});
// restore_backup
it('should restore database from a backup', async function () {
// Restoring a backup can be a slow operation so the test may timeout and
// we'll have to retry.
this.retries(5);
// Delay the start of the test, if this is a retry.
await delay(this.test);
const output = execSync(
`${backupsCmd} restoreBackup ${INSTANCE_ID} ${RESTORE_DATABASE_ID} ${BACKUP_ID} ${PROJECT_ID}`
);
assert.match(output, /Database restored from backup./);
assert.match(
output,
new RegExp(
`Database (.+) was restored to ${RESTORE_DATABASE_ID} from backup ` +
`(.+)${BACKUP_ID} with version time (.+)`
)
);
});
// restore_backup_with_encryption_key
it('should restore database from a backup using an encryption key', async function () {
// Restoring a backup can be a slow operation so the test may timeout and
// we'll have to retry.
this.retries(5);