/
bigtable.ts
1439 lines (1284 loc) · 42 KB
/
bigtable.ts
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 2016 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
//
// https://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.
import {replaceProjectIdToken} from '@google-cloud/projectify';
import {PreciseDate} from '@google-cloud/precise-date';
import * as assert from 'assert';
import {beforeEach, afterEach, describe, it, before, after} from 'mocha';
import Q from 'p-queue';
import {Backup, Bigtable, Instance} from '../src';
import {AppProfile} from '../src/app-profile.js';
import {Cluster} from '../src/cluster.js';
import {Family} from '../src/family.js';
import {Row} from '../src/row.js';
import {Table} from '../src/table.js';
import {RawFilter} from '../src/filter';
import {generateId, PREFIX} from './common';
describe('Bigtable', () => {
const bigtable = new Bigtable();
const INSTANCE = bigtable.instance(generateId('instance'));
const DIFF_INSTANCE = bigtable.instance(generateId('d-inst'));
const CMEK_INSTANCE = bigtable.instance(generateId('cmek'));
const TABLE = INSTANCE.table(generateId('table'));
const APP_PROFILE_ID = generateId('appProfile');
const APP_PROFILE = INSTANCE.appProfile(APP_PROFILE_ID);
const CLUSTER_ID = generateId('cluster');
async function reapBackups(instance: Instance) {
const [backups] = await instance.getBackups();
const q = new Q({concurrency: 5});
return Promise.all(
backups.map(backup => {
q.add(async () => {
try {
await backup.delete({timeout: 50 * 1000});
} catch (e) {
console.log(`Error deleting backup: ${backup.id}`);
}
});
})
);
}
async function reapInstances() {
const [instances] = await bigtable.getInstances();
const testInstances = instances
.filter(i => i.id.match(PREFIX))
.filter(i => {
const timeCreated = i.metadata!.labels!.time_created as {} as Date;
// Only delete stale resources.
const oneHourAgo = new Date(Date.now() - 3600000);
return !timeCreated || timeCreated <= oneHourAgo;
});
const q = new Q({concurrency: 5});
// need to delete backups first due to instance deletion precondition
await Promise.all(testInstances.map(instance => reapBackups(instance)));
await Promise.all(
testInstances.map(instance => {
q.add(async () => {
try {
await instance.delete();
} catch (e) {
console.log(`Error deleting instance: ${instance.id}`);
}
});
})
);
}
before(async () => {
await reapInstances();
const [, operation] = await INSTANCE.create(
createInstanceConfig(CLUSTER_ID, 'us-central1-c', 3, Date.now())
);
await operation.promise();
await TABLE.create({
families: ['follows', 'traits'],
});
await INSTANCE.createAppProfile(APP_PROFILE_ID, {
routing: 'any',
ignoreWarnings: true,
});
});
after(async () => {
const q = new Q({concurrency: 5});
const instances = [INSTANCE, DIFF_INSTANCE, CMEK_INSTANCE];
// need to delete backups first due to instance deletion precondition
await Promise.all(instances.map(instance => reapBackups(instance)));
await Promise.all(
instances.map(instance => {
q.add(async () => {
try {
await instance.delete();
} catch (e) {
console.log(`Error deleting instance: ${instance.id}`);
}
});
})
);
});
describe('instances', () => {
it('should get a list of instances', async () => {
const [instances, failedLocations] = await bigtable.getInstances();
assert(instances.length > 0);
assert(Array.isArray(failedLocations));
});
it('should check if an instance exists', async () => {
const [exists] = await INSTANCE.exists();
assert.strictEqual(exists, true);
});
it('should check if an instance does not exist', async () => {
const instance = bigtable.instance('fake-instance');
const [exists] = await instance.exists();
assert.strictEqual(exists, false);
});
it('should get a single instance', async () => {
await INSTANCE.get();
});
it('should update an instance', async () => {
const metadata = {
displayName: 'metadata-test',
};
await INSTANCE.setMetadata(metadata);
const [metadata_] = await INSTANCE.getMetadata();
assert.strictEqual(metadata.displayName, metadata_.displayName);
});
it('should get an Iam Policy for the instance', async () => {
const policyProperties = ['version', 'bindings', 'etag'];
const [policy] = await INSTANCE.getIamPolicy();
policyProperties.forEach(property => {
assert(property in policy);
});
});
it('should test Iam permissions for the instance', async () => {
const permissions = ['bigtable.tables.get', 'bigtable.tables.readRows'];
const [grantedPermissions] = await INSTANCE.testIamPermissions(
permissions
);
assert.strictEqual(grantedPermissions.length, permissions.length);
permissions.forEach(permission => {
assert.strictEqual(grantedPermissions.includes(permission), true);
});
});
it('should set Iam Policy on the instance', async () => {
const instance = bigtable.instance(generateId('instance'));
const clusteId = generateId('cluster');
const [, operation] = await instance.create({
clusters: [
{
id: clusteId,
location: 'us-central1-c',
nodes: 3,
},
],
labels: {
time_created: Date.now(),
},
});
await operation.promise();
const [policy] = await instance.getIamPolicy();
const [updatedPolicy] = await instance.setIamPolicy(policy);
Object.keys(policy).forEach(key => assert(key in updatedPolicy));
await instance.delete();
});
});
describe('CMEK', () => {
let kmsKeyName: string;
const CMEK_CLUSTER = CMEK_INSTANCE.cluster(generateId('cluster'));
const cryptoKeyId = generateId('key');
const keyRingId = generateId('key-ring');
let keyRingsBaseUrl: string;
let cryptoKeyVersionName: string;
before(async () => {
const projectId = await bigtable.auth.getProjectId();
kmsKeyName = `projects/${projectId}/locations/us-central1/keyRings/${keyRingId}/cryptoKeys/${cryptoKeyId}`;
keyRingsBaseUrl = `https://cloudkms.googleapis.com/v1/projects/${projectId}/locations/us-central1/keyRings`;
await bigtable.auth.request({
method: 'POST',
url: keyRingsBaseUrl,
params: {keyRingId},
});
const resp = await bigtable.auth.request({
method: 'POST',
url: `${keyRingsBaseUrl}/${keyRingId}/cryptoKeys`,
params: {cryptoKeyId},
data: {purpose: 'ENCRYPT_DECRYPT'},
});
cryptoKeyVersionName = resp.data.primary.name;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [_, operation] = await CMEK_INSTANCE.create({
clusters: [
{
id: CMEK_CLUSTER.id,
location: 'us-central1-a',
nodes: 3,
key: kmsKeyName,
},
],
labels: {
time_created: Date.now(),
},
});
await operation.promise();
});
after(async () => {
await bigtable.auth.request({
method: 'POST',
url: `${keyRingsBaseUrl}/${keyRingId}/cryptoKeys/${cryptoKeyId}/cryptoKeyVersions/${cryptoKeyVersionName
.split('/')
.pop()}:destroy`,
params: {name: cryptoKeyVersionName},
});
});
it('should have created an instance', async () => {
const [metadata] = await CMEK_CLUSTER.getMetadata();
assert.deepStrictEqual(metadata.encryptionConfig, {kmsKeyName});
});
it('should create a cluster', async () => {
const cluster = CMEK_INSTANCE.cluster(generateId('cluster'));
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [_, operation] = await cluster.create({
location: 'us-central1-b',
nodes: 3,
key: kmsKeyName,
});
await operation.promise();
const [metadata] = await cluster.getMetadata();
assert.deepStrictEqual(metadata.encryptionConfig, {kmsKeyName});
});
it('should fail if key not provided', async () => {
const cluster = CMEK_INSTANCE.cluster(generateId('cluster'));
try {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [_, operation] = await cluster.create({
location: 'us-central1-b',
nodes: 3,
});
await operation.promise();
throw new Error('Cluster creation should not have succeeded');
} catch (e) {
assert(
(e as Error).message.includes(
'default keys and CMEKs are not allowed'
)
);
}
});
});
describe('appProfiles', () => {
it('should retrieve a list of app profiles', async () => {
const [appProfiles] = await INSTANCE.getAppProfiles();
assert(appProfiles[0] instanceof AppProfile);
assert(appProfiles.length > 0);
});
it('should retrieve a list of app profiles in stream mode', done => {
const appProfiles: AppProfile[] = [];
INSTANCE.getAppProfilesStream()
.on('error', done)
.on('data', appProfile => {
assert(appProfile instanceof AppProfile);
appProfiles.push(appProfile);
})
.on('end', () => {
assert(appProfiles.length > 0);
done();
});
});
it('should check if an app profile exists', async () => {
const [exists] = await APP_PROFILE.exists();
assert.strictEqual(exists, true);
});
it('should check if an app profile does not exist', async () => {
const appProfile = INSTANCE.appProfile('should-not-exist');
const [exists] = await appProfile.exists();
assert.strictEqual(exists, false);
});
it('should get an app profile', async () => {
await APP_PROFILE.get();
});
it('should delete an app profile', async () => {
const appProfile = INSTANCE.appProfile(generateId('app-profile'));
await appProfile.create({
routing: 'any',
ignoreWarnings: true,
});
await appProfile.delete({ignoreWarnings: true});
});
it('should get the app profiles metadata', async () => {
const [metadata] = await APP_PROFILE.getMetadata();
assert.strictEqual(
metadata.name,
APP_PROFILE.name.replace('{{projectId}}', bigtable.projectId)
);
});
it('should update an app profile', async () => {
const cluster = INSTANCE.cluster(CLUSTER_ID);
const options = {
routing: cluster,
allowTransactionalWrites: true,
description: 'My Updated App Profile',
};
await APP_PROFILE.setMetadata(options);
const [updatedAppProfile] = await APP_PROFILE.get();
assert.strictEqual(
updatedAppProfile.metadata!.description,
options.description
);
assert.deepStrictEqual(updatedAppProfile.metadata!.singleClusterRouting, {
clusterId: CLUSTER_ID,
allowTransactionalWrites: true,
});
});
});
describe('clusters', () => {
let CLUSTER: Cluster;
beforeEach(() => {
CLUSTER = INSTANCE.cluster(CLUSTER_ID);
});
it('should retrieve a list of clusters', async () => {
const [clusters] = await INSTANCE.getClusters();
assert(clusters[0] instanceof Cluster);
});
it('should check if a cluster exists', async () => {
const [exists] = await CLUSTER.exists();
assert.strictEqual(exists, true);
});
it('should check if a cluster does not exist', async () => {
const cluster = INSTANCE.cluster('fake-cluster');
const [exists] = await cluster.exists();
assert.strictEqual(exists, false);
});
it('should get a cluster', async () => {
await CLUSTER.get();
});
it('should update a cluster', async () => {
const metadata = {
nodes: 4,
};
const [operation] = await CLUSTER.setMetadata(metadata);
await operation.promise();
const [_metadata] = await CLUSTER.getMetadata();
assert.strictEqual(metadata.nodes, _metadata.serveNodes);
});
});
describe('tables', () => {
it('should retrieve a list of tables', async () => {
const [tables] = await INSTANCE.getTables();
assert(tables[0] instanceof Table);
});
it('should retrieve a list of tables in stream mode', done => {
const tables: Table[] = [];
INSTANCE.getTablesStream()
.on('error', done)
.on('data', table => {
assert(table instanceof Table);
tables.push(table);
})
.on('end', () => {
assert(tables.length > 0);
done();
});
});
it('should check if a table exists', async () => {
const [exists] = await TABLE.exists();
assert.strictEqual(exists, true);
});
it('should check if a table does not exist', async () => {
const table = INSTANCE.table('should-not-exist');
const [exists] = await table.exists();
assert.strictEqual(exists, false);
});
it('should get a table', async () => {
await TABLE.get();
});
it('should get an Iam Policy for the table', async () => {
const policyProperties = ['version', 'bindings', 'etag'];
const [policy] = await TABLE.getIamPolicy();
policyProperties.forEach(property => {
assert(property in policy);
});
});
it('should test Iam permissions for the table', async () => {
const permissions = ['bigtable.tables.get', 'bigtable.tables.readRows'];
const [grantedPermissions] = await TABLE.testIamPermissions(permissions);
assert.strictEqual(grantedPermissions.length, permissions.length);
permissions.forEach(permission => {
assert.strictEqual(grantedPermissions.includes(permission), true);
});
});
it('should set Iam Policy on the table', async () => {
const table = INSTANCE.table(generateId('table'));
await table.create();
const [policy] = await table.getIamPolicy();
const [updatedPolicy] = await table.setIamPolicy(policy);
Object.keys(policy).forEach(key => assert(key in updatedPolicy));
await table.delete();
});
it('should delete a table', async () => {
const table = INSTANCE.table(generateId('table'));
await table.create();
await table.delete();
});
it('should get the tables metadata', async () => {
const [metadata] = await TABLE.getMetadata();
assert.strictEqual(
metadata.name,
TABLE.name.replace('{{projectId}}', bigtable.projectId)
);
});
it('should create a table with column family data', async () => {
const name = generateId('table');
const options = {
families: ['test'],
};
const [table] = await INSTANCE.createTable(name, options);
assert(table.metadata!.columnFamilies!.test);
});
it('should create a table if autoCreate is true', async () => {
const table = INSTANCE.table(generateId('table'));
await table.get({autoCreate: true});
await table.delete();
});
});
describe('consistency tokens', () => {
it('should generate consistency token', async () => {
const [token] = await TABLE.generateConsistencyToken();
assert.strictEqual(typeof token, 'string');
});
it('should return error for checkConsistency of invalid token', done => {
TABLE.checkConsistency('dummy-token', err => {
assert.strictEqual(err!.code, 3);
done();
});
});
it('should return boolean for checkConsistency of token', async () => {
const [token] = await TABLE.generateConsistencyToken();
const [res] = await TABLE.checkConsistency(token);
assert.strictEqual(typeof res, 'boolean');
});
it('should return boolean for waitForReplication', async () => {
const [res] = await TABLE.waitForReplication();
assert.strictEqual(typeof res, 'boolean');
});
});
describe('replication states', () => {
it('should get a map of clusterId and state', async () => {
const [clusterStates] = await TABLE.getReplicationStates();
assert(clusterStates instanceof Map);
assert(clusterStates.has(CLUSTER_ID));
});
});
describe('column families', () => {
const FAMILY_ID = 'presidents';
let FAMILY: Family;
before(async () => {
FAMILY = TABLE.family(FAMILY_ID);
await FAMILY.create();
});
it('should get a list of families', async () => {
const [families] = await TABLE.getFamilies();
assert.strictEqual(families.length, 3);
assert(families[0] instanceof Family);
assert.notStrictEqual(-1, families.map(f => f.id).indexOf(FAMILY.id));
});
it('should get a family', async () => {
const family = TABLE.family(FAMILY_ID);
await family.get();
assert(family instanceof Family);
assert.strictEqual(family.name, FAMILY.name);
assert.strictEqual(family.id, FAMILY.id);
});
it('should check if a family exists', async () => {
const [exists] = await FAMILY.exists();
assert.strictEqual(exists, true);
});
it('should check if a family does not exist', async () => {
const family = TABLE.family('prezzies');
const [exists] = await family.exists();
assert.strictEqual(exists, false);
});
it('should create a family if autoCreate is true', async () => {
const family = TABLE.family('prezzies');
await family.get({autoCreate: true});
await family.delete();
});
it('should create a family with nested gc rules', async () => {
const family = TABLE.family('prezzies');
const options = {
rule: {
union: true,
versions: 10,
rule: {
versions: 2,
age: {seconds: 60 * 60 * 24 * 30},
},
},
};
await family.create(options);
const [metadata] = await family.getMetadata();
assert.deepStrictEqual(metadata.gcRule, {
union: {
rules: [
{
maxNumVersions: 10,
rule: 'maxNumVersions',
},
{
intersection: {
rules: [
{
maxAge: {
seconds: '2592000',
nanos: 0,
},
rule: 'maxAge',
},
{
maxNumVersions: 2,
rule: 'maxNumVersions',
},
],
},
rule: 'intersection',
},
],
},
rule: 'union',
});
await family.delete();
});
it('should get the column family metadata', async () => {
const [metadata] = await FAMILY.getMetadata();
assert.strictEqual(FAMILY.metadata, metadata);
});
it('should update a column family', async () => {
const rule = {
age: {
seconds: 10000,
nanos: 10000,
},
};
const [metadata] = await FAMILY.setMetadata({rule});
const maxAge = metadata.gcRule!.maxAge;
assert.strictEqual(maxAge!.seconds, rule.age.seconds.toString());
assert.strictEqual(maxAge!.nanos, rule.age.nanos);
});
it('should delete a column family', async () => {
await FAMILY.delete();
});
});
describe('rows', () => {
describe('.exists()', () => {
const row = TABLE.row('alincoln');
beforeEach(async () => {
await row.create({
entry: {
follows: {
gwashington: 1,
jadams: 1,
tjefferson: 1,
},
},
});
});
afterEach(async () => row.delete());
it('should check if a row exists', async () => {
const [exists] = await row.exists();
assert.strictEqual(exists, true);
});
it('should check if a row does not exist', async () => {
const row = TABLE.row('gwashington');
const [exists] = await row.exists();
assert.strictEqual(exists, false);
});
});
describe('inserting data', () => {
it('should insert rows', async () => {
const rows = [
{
key: 'gwashington',
data: {
follows: {
jadams: 1,
},
},
},
{
key: 'tjefferson',
data: {
follows: {
gwashington: 1,
jadams: 1,
},
},
},
{
key: 'jadams',
data: {
follows: {
gwashington: 1,
tjefferson: 1,
},
},
},
];
await TABLE.insert(rows);
});
it('should insert a large row', async () => {
await TABLE.insert({
key: 'gwashington',
data: {
follows: {
jadams: Buffer.alloc(5000000),
},
},
});
});
it('should create an individual row', async () => {
const row = TABLE.row('alincoln');
const rowData = {
follows: {
gwashington: 1,
jadams: 1,
tjefferson: 1,
},
};
await row.create({entry: rowData});
});
it('should insert individual cells', async () => {
const row = TABLE.row('gwashington');
const rowData = {
follows: {
jadams: 1,
},
};
await row.save(rowData);
});
it('should allow for user specified timestamps', async () => {
const row = TABLE.row('gwashington');
const rowData = {
follows: {
jadams: {
value: 1,
timestamp: new Date('March 22, 1986'),
},
},
};
await row.save(rowData);
});
it('should increment a column value', async () => {
const row = TABLE.row('gwashington');
const increment = 5;
const [value] = await row.increment('follows:increment', increment);
assert.strictEqual(value, increment);
});
it('should apply read/modify/write rules to a row', async () => {
const row = TABLE.row('gwashington');
const rule = {
column: 'traits:teeth',
append: '-wood',
};
await row.save({
traits: {
teeth: 'shiny',
},
});
await row.createRules(rule);
const [data] = await row.get(['traits:teeth']);
assert.strictEqual(data.traits.teeth[0].value, 'shiny-wood');
});
it('should check and mutate a row', async () => {
const row = TABLE.row('gwashington');
const filter: RawFilter = {
family: 'follows',
value: 'alincoln',
};
const mutations = [
{
method: 'delete',
data: ['follows:alincoln'],
},
];
const [matched] = await row.filter(filter, {onMatch: mutations});
assert(matched);
});
});
describe('fetching data', () => {
it('should get rows', async () => {
const [rows] = await TABLE.getRows();
assert.strictEqual(rows.length, 4);
assert(rows[0] instanceof Row);
});
it('should get rows via stream', done => {
const rows: Row[] = [];
TABLE.createReadStream()
.on('error', done)
.on('data', row => {
assert(row instanceof Row);
rows.push(row);
})
.on('end', () => {
assert.strictEqual(rows.length, 4);
done();
});
});
it('should should cancel request if stream ended early', done => {
const rows: Row[] = [];
const stream = TABLE.createReadStream()
.on('error', done)
.on('data', row => {
stream.end();
rows.push(row);
})
.on('end', () => {
assert.strictEqual(rows.length, 1);
done();
});
});
it('should fetch an individual row', async () => {
const row = TABLE.row('alincoln');
const [row_] = await row.get();
assert.strictEqual(row, row_);
});
it('should limit the number of rows', async () => {
const [rows] = await TABLE.getRows({
limit: 1,
});
assert.strictEqual(rows.length, 1);
});
it('should fetch a range of rows', async () => {
const options = {
start: 'alincoln',
end: 'jadams',
};
const [rows] = await TABLE.getRows(options);
assert.strictEqual(rows.length, 3);
});
it('should fetch a range of rows via prefix', async () => {
const options = {
prefix: 'g',
};
const [rows] = await TABLE.getRows(options);
assert.strictEqual(rows.length, 1);
assert.strictEqual(rows[0].id, 'gwashington');
});
it('should fetch individual cells of a row', async () => {
const row = TABLE.row('alincoln');
const [data] = await row.get(['follows:gwashington']);
assert.strictEqual(data.follows.gwashington[0].value, 1);
});
it('should not decode the values', async () => {
const row = TABLE.row('gwashington');
const options = {
decode: false,
};
await row.get(options);
const teeth = row.data.traits.teeth;
const value = teeth[0].value;
assert(value instanceof Buffer);
assert.strictEqual(value.toString(), 'shiny-wood');
});
it('should get sample row keys', async () => {
const [keys] = await TABLE.sampleRowKeys();
assert(keys.length > 0);
});
it('should get sample row keys via stream', done => {
const keys: string[] = [];
TABLE.sampleRowKeysStream()
.on('error', done)
.on('data', (rowKey: string) => {
keys.push(rowKey);
})
.on('end', () => {
assert(keys.length > 0);
done();
});
});
it('should end stream early', async () => {
const entries = [
{
key: 'gwashington',
data: {
follows: {
jadams: 1,
},
},
},
{
key: 'tjefferson',
data: {
follows: {
gwashington: 1,
jadams: 1,
},
},
},
{
key: 'jadams',
data: {
follows: {
gwashington: 1,
tjefferson: 1,
},
},
},
];
await TABLE.insert(entries);
const rows: Row[] = [];
await new Promise<void>((resolve, reject) => {
const stream = TABLE.createReadStream()
.on('error', reject)
.on('data', row => {
rows.push(row);
stream.end();
})
.on('end', () => {
assert.strictEqual(rows.length, 1);
resolve();
});
});
});
describe('filters', () => {
it('should get rows via column data', async () => {
const filter = {
column: 'gwashington',
};
const [rows] = await TABLE.getRows({filter});
assert.strictEqual(rows.length, 3);
const keys = rows.map(row => row.id).sort();
assert.deepStrictEqual(keys, ['alincoln', 'jadams', 'tjefferson']);
});
it('should get rows that satisfy the cell limit', async () => {
const entry = {
key: 'alincoln',
data: {
follows: {
tjefferson: 1,
},
},
};
const filter = [
{
row: 'alincoln',
},
{
column: {
name: 'tjefferson',
cellLimit: 1,
},
},
];
await TABLE.insert(entry);
const [rows] = await TABLE.getRows({filter});
const rowData = rows[0].data;
assert.strictEqual(rowData.follows.tjefferson.length, 1);
});
it('should get a range of columns', async () => {
const filter = [
{
row: 'tjefferson',
},
{
column: {
family: 'follows',
start: 'gwashington',
end: 'jadams',
},
},
];
const [rows] = await TABLE.getRows({filter});
rows.forEach(row => {
const keys = Object.keys(row.data.follows).sort();
assert.deepStrictEqual(keys, ['gwashington', 'jadams']);
});
});
it('should run a conditional filter', async () => {
const filter = {
condition: {
test: [
{
row: 'gwashington',
},
{
family: 'follows',
},
{