-
Notifications
You must be signed in to change notification settings - Fork 213
/
Copy pathbigquery.ts
3041 lines (2569 loc) · 83.8 KB
/
bigquery.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 2019 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.
import {
DecorateRequestOptions,
Service,
ServiceConfig,
ServiceOptions,
util,
} from '@google-cloud/common';
import * as pfy from '@google-cloud/promisify';
import arrify = require('arrify');
import * as assert from 'assert';
import {describe, it, after, afterEach, before, beforeEach} from 'mocha';
import * as Big from 'big.js';
import * as extend from 'extend';
import * as proxyquire from 'proxyquire';
import * as sinon from 'sinon';
import * as uuid from 'uuid';
import {
BigQueryInt,
BigQueryDate,
IntegerTypeCastValue,
IntegerTypeCastOptions,
Dataset,
Job,
PROTOCOL_REGEX,
Table,
JobOptions,
TableField,
} from '../src';
import {SinonStub} from 'sinon';
import {PreciseDate} from '@google-cloud/precise-date';
const fakeUuid = extend(true, {}, uuid);
class FakeApiError {
calledWith_: Array<{}>;
constructor(...args: Array<{}>) {
this.calledWith_ = args;
}
}
interface InputObject {
year?: number;
month?: number;
day?: number;
hours?: number;
minutes?: number;
seconds?: number;
fractional?: number;
}
interface CalledWithService extends Service {
calledWith_: Array<{
baseUrl: string;
scopes: string[];
packageJson: {};
}>;
}
let promisified = false;
const fakePfy = Object.assign({}, pfy, {
promisifyAll: (c: Function, options: pfy.PromisifyAllOptions) => {
if (c.name !== 'BigQuery') {
return;
}
promisified = true;
assert.deepStrictEqual(options.exclude, [
'dataset',
'date',
'datetime',
'geography',
'int',
'job',
'time',
'timestamp',
]);
},
});
const fakeUtil = Object.assign({}, util, {
ApiError: FakeApiError,
});
const originalFakeUtil = extend(true, {}, fakeUtil);
class FakeDataset {
calledWith_: Array<{}>;
constructor(...args: Array<{}>) {
this.calledWith_ = args;
}
}
class FakeTable extends Table {
constructor(a: Dataset, b: string) {
super(a, b);
}
}
class FakeJob {
calledWith_: Array<{}>;
constructor(...args: Array<{}>) {
this.calledWith_ = args;
}
}
let extended = false;
const fakePaginator = {
paginator: {
extend: (c: Function, methods: string[]) => {
if (c.name !== 'BigQuery') {
return;
}
methods = arrify(methods);
assert.strictEqual(c.name, 'BigQuery');
assert.deepStrictEqual(methods, ['getDatasets', 'getJobs']);
extended = true;
},
streamify: (methodName: string) => {
return methodName;
},
},
};
class FakeService extends Service {
calledWith_: IArguments;
constructor(config: ServiceConfig, options: ServiceOptions) {
super(config, options);
// eslint-disable-next-line prefer-rest-params
this.calledWith_ = arguments;
}
}
const sandbox = sinon.createSandbox();
afterEach(() => sandbox.restore());
describe('BigQuery', () => {
const JOB_ID = 'JOB_ID';
const PROJECT_ID = 'test-project';
const ANOTHER_PROJECT_ID = 'another-test-project';
const LOCATION = 'asia-northeast1';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let BigQueryCached: any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let BigQuery: any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let bq: any;
const BIGQUERY_EMULATOR_HOST = process.env.BIGQUERY_EMULATOR_HOST;
before(() => {
delete process.env.BIGQUERY_EMULATOR_HOST;
BigQuery = proxyquire('../src/bigquery', {
uuid: fakeUuid,
'./dataset': {
Dataset: FakeDataset,
},
'./job': {
Job: FakeJob,
},
'./table': {
Table: FakeTable,
},
'@google-cloud/common': {
Service: FakeService,
util: fakeUtil,
},
'@google-cloud/paginator': fakePaginator,
'@google-cloud/promisify': fakePfy,
}).BigQuery;
BigQueryCached = Object.assign({}, BigQuery);
});
beforeEach(() => {
Object.assign(fakeUtil, originalFakeUtil);
BigQuery = Object.assign(BigQuery, BigQueryCached);
bq = new BigQuery({projectId: PROJECT_ID});
});
after(() => {
if (BIGQUERY_EMULATOR_HOST) {
process.env.BIGQUERY_EMULATOR_HOST = BIGQUERY_EMULATOR_HOST;
}
});
describe('instantiation', () => {
it('should extend the correct methods', () => {
assert(extended); // See `fakePaginator.extend`
});
it('should streamify the correct methods', () => {
assert.strictEqual(bq.getDatasetsStream, 'getDatasets');
assert.strictEqual(bq.getJobsStream, 'getJobs');
assert.strictEqual(bq.createQueryStream, 'queryAsStream_');
});
it('should promisify all the things', () => {
assert(promisified);
});
it('should inherit from Service', () => {
assert(bq instanceof Service);
const calledWith = (bq as CalledWithService).calledWith_[0];
const baseUrl = 'https://bigquery.googleapis.com/bigquery/v2';
assert.strictEqual(calledWith.baseUrl, baseUrl);
assert.deepStrictEqual(calledWith.scopes, [
'https://www.googleapis.com/auth/bigquery',
]);
assert.deepStrictEqual(
calledWith.packageJson,
// eslint-disable-next-line @typescript-eslint/no-var-requires
require('../../package.json')
);
});
it('should allow overriding the apiEndpoint', () => {
const apiEndpoint = 'https://not.real.local';
bq = new BigQuery({
apiEndpoint,
});
const calledWith = bq.calledWith_[0];
assert.strictEqual(calledWith.baseUrl, `${apiEndpoint}/bigquery/v2`);
assert.strictEqual(calledWith.apiEndpoint, `${apiEndpoint}`);
});
it('should prepend apiEndpoint with default protocol', () => {
const protocollessApiEndpoint = 'some.fake.endpoint';
bq = new BigQuery({
apiEndpoint: protocollessApiEndpoint,
});
const calledWith = bq.calledWith_[0];
assert.strictEqual(
calledWith.baseUrl,
`https://${protocollessApiEndpoint}/bigquery/v2`
);
assert.strictEqual(
calledWith.apiEndpoint,
`https://${protocollessApiEndpoint}`
);
});
it('should strip trailing slash from apiEndpoint', () => {
const apiEndpoint = 'https://some.fake.endpoint/';
bq = new BigQuery({
apiEndpoint: apiEndpoint,
});
const calledWith = bq.calledWith_[0];
assert.strictEqual(calledWith.baseUrl, `${apiEndpoint}bigquery/v2`);
assert.strictEqual(calledWith.apiEndpoint, 'https://some.fake.endpoint');
});
it('should allow overriding TPC universe', () => {
const universeDomain = 'fake-tpc-env.example.com/';
bq = new BigQuery({
universeDomain: universeDomain,
});
const calledWith = bq.calledWith_[0];
assert.strictEqual(
calledWith.baseUrl,
'https://bigquery.fake-tpc-env.example.com/bigquery/v2'
);
assert.strictEqual(
calledWith.apiEndpoint,
'https://bigquery.fake-tpc-env.example.com'
);
});
it('should capture any user specified location', () => {
const bq = new BigQuery({
projectId: PROJECT_ID,
location: LOCATION,
});
assert.strictEqual(bq.location, LOCATION);
});
it('should pass scopes from options', () => {
const bq = new BigQuery({
scopes: ['https://www.googleapis.com/auth/drive.readonly'],
});
const expectedScopes = [
'https://www.googleapis.com/auth/bigquery',
'https://www.googleapis.com/auth/drive.readonly',
];
const calledWith = bq.calledWith_[0];
assert.deepStrictEqual(calledWith.scopes, expectedScopes);
});
it('should pass autoRetry from options', () => {
const retry = false;
const bq = new BigQuery({
autoRetry: retry,
});
const calledWith = bq.calledWith_[0];
assert.deepStrictEqual(calledWith.autoRetry, retry);
});
it('should pass maxRetries from options', () => {
const retryVal = 1;
const bq = new BigQuery({
maxRetries: retryVal,
});
const calledWith = bq.calledWith_[0];
assert.deepStrictEqual(calledWith.maxRetries, retryVal);
});
it('should not modify options argument', () => {
const options = {
projectId: PROJECT_ID,
};
const expectedCalledWith = Object.assign({}, options, {
apiEndpoint: 'https://bigquery.googleapis.com',
});
const bigquery = new BigQuery(options);
const calledWith = bigquery.calledWith_[1];
assert.notStrictEqual(calledWith, options);
assert.notDeepStrictEqual(calledWith, options);
assert.deepStrictEqual(calledWith, expectedCalledWith);
});
describe('BIGQUERY_EMULATOR_HOST', () => {
const EMULATOR_HOST = 'https://internal.benchmark.com/path';
before(() => {
process.env.BIGQUERY_EMULATOR_HOST = EMULATOR_HOST;
});
after(() => {
delete process.env.BIGQUERY_EMULATOR_HOST;
});
it('should set baseUrl to env var STORAGE_EMULATOR_HOST', () => {
bq = new BigQuery({
projectId: PROJECT_ID,
});
const calledWith = bq.calledWith_[0];
assert.strictEqual(calledWith.baseUrl, EMULATOR_HOST);
assert.strictEqual(
calledWith.apiEndpoint,
'https://internal.benchmark.com/path'
);
});
it('should be overriden by apiEndpoint', () => {
bq = new BigQuery({
projectId: PROJECT_ID,
apiEndpoint: 'https://some.api.com',
});
const calledWith = bq.calledWith_[0];
assert.strictEqual(calledWith.baseUrl, EMULATOR_HOST);
assert.strictEqual(calledWith.apiEndpoint, 'https://some.api.com');
});
it('should prepend default protocol and strip trailing slash', () => {
const EMULATOR_HOST = 'internal.benchmark.com/path/';
process.env.BIGQUERY_EMULATOR_HOST = EMULATOR_HOST;
bq = new BigQuery({
projectId: PROJECT_ID,
});
const calledWith = bq.calledWith_[0];
assert.strictEqual(calledWith.baseUrl, EMULATOR_HOST);
assert.strictEqual(
calledWith.apiEndpoint,
'https://internal.benchmark.com/path'
);
});
});
describe('prettyPrint request interceptor', () => {
let requestInterceptor: Function;
beforeEach(() => {
requestInterceptor = bq.interceptors.pop().request;
});
it('should disable prettyPrint', () => {
assert.deepStrictEqual(requestInterceptor({}), {
qs: {prettyPrint: false},
});
});
it('should clone json', () => {
const reqOpts = {qs: {a: 'b'}};
const expectedReqOpts = {qs: {a: 'b', prettyPrint: false}};
assert.deepStrictEqual(requestInterceptor(reqOpts), expectedReqOpts);
assert.notDeepStrictEqual(reqOpts, expectedReqOpts);
});
});
});
describe('mergeSchemaWithRows_', () => {
const SCHEMA_OBJECT = {
fields: [
{name: 'id', type: 'INTEGER'},
{name: 'name', type: 'STRING'},
{name: 'dob', type: 'TIMESTAMP'},
{name: 'has_claws', type: 'BOOLEAN'},
{name: 'has_fangs', type: 'BOOL'},
{name: 'hair_count', type: 'FLOAT'},
{name: 'teeth_count', type: 'FLOAT64'},
{name: 'numeric_col', type: 'NUMERIC'},
{name: 'bignumeric_col', type: 'BIGNUMERIC'},
],
} as {fields: TableField[]};
beforeEach(() => {
sandbox.stub(BigQuery, 'date').callsFake(input => {
return {
type: 'fakeDate',
input,
};
});
sandbox.stub(BigQuery, 'datetime').callsFake(input => {
return {
type: 'fakeDatetime',
input,
};
});
sandbox.stub(BigQuery, 'time').callsFake(input => {
return {
type: 'fakeTime',
input,
};
});
sandbox.stub(BigQuery, 'timestamp').callsFake(input => {
return {
type: 'fakeTimestamp',
input,
};
});
sandbox.stub(BigQuery, 'geography').callsFake(input => {
return {
type: 'fakeGeography',
input,
};
});
});
it('should merge the schema and flatten the rows', () => {
const now = new Date();
const buffer = Buffer.from('test');
const rows = [
{
raw: {
f: [
{v: '3'},
{v: 'Milo'},
{v: now.valueOf() * 1000},
{v: 'false'},
{v: 'true'},
{v: '5.222330009847'},
{v: '30.2232138'},
{v: '3.14'},
{v: '9.9876543210123456789'},
{
v: [
{
v: '10',
},
],
},
{
v: [
{
v: '2',
},
],
},
{v: null},
{v: buffer.toString('base64')},
{
v: [
{
v: {
f: [
{
v: {
f: [
{
v: 'nested_value',
},
],
},
},
],
},
},
],
},
{v: 'date-input'},
{v: 'datetime-input'},
{v: 'time-input'},
{v: 'geography-input'},
],
},
expected: {
id: 3,
name: 'Milo',
dob: {
input: now.valueOf() * 1000,
type: 'fakeTimestamp',
},
has_claws: false,
has_fangs: true,
hair_count: 5.222330009847,
teeth_count: 30.2232138,
numeric_col: new Big(3.14),
bignumeric_col: new Big('9.9876543210123456789'),
arr: [10],
arr2: [2],
nullable: null,
buffer,
objects: [
{
nested_object: {
nested_property: 'nested_value',
},
},
],
date: {
input: 'date-input',
type: 'fakeDate',
},
datetime: {
input: 'datetime-input',
type: 'fakeDatetime',
},
time: {
input: 'time-input',
type: 'fakeTime',
},
geography: {
input: 'geography-input',
type: 'fakeGeography',
},
},
},
];
const schemaObject = extend(true, SCHEMA_OBJECT, {});
schemaObject.fields.push({
name: 'arr',
type: 'INTEGER',
mode: 'REPEATED',
});
schemaObject.fields.push({
name: 'arr2',
type: 'INT64',
mode: 'REPEATED',
});
schemaObject.fields.push({
name: 'nullable',
type: 'STRING',
mode: 'NULLABLE',
});
schemaObject.fields.push({
name: 'buffer',
type: 'BYTES',
});
schemaObject.fields.push({
name: 'objects',
type: 'RECORD',
mode: 'REPEATED',
fields: [
{
name: 'nested_object',
type: 'RECORD',
fields: [
{
name: 'nested_property',
type: 'STRING',
},
],
},
],
});
schemaObject.fields.push({
name: 'date',
type: 'DATE',
});
schemaObject.fields.push({
name: 'datetime',
type: 'DATETIME',
});
schemaObject.fields.push({
name: 'time',
type: 'TIME',
});
schemaObject.fields.push({
name: 'geography',
type: 'GEOGRAPHY',
});
const rawRows = rows.map(x => x.raw);
const mergedRows = BigQuery.mergeSchemaWithRows_(schemaObject, rawRows, {
wrapIntegers: false,
});
mergedRows.forEach((mergedRow: {}, index: number) => {
assert.deepStrictEqual(mergedRow, rows[index].expected);
});
});
it('should wrap integers with option', () => {
const wrapIntegersBoolean = true;
const wrapIntegersObject = {};
const fakeInt = new BigQueryInt(100);
const SCHEMA_OBJECT = {
fields: [{name: 'fave_number', type: 'INTEGER'}],
} as {fields: TableField[]};
const rows = {
raw: {
f: [{v: 100}],
},
expectedBool: {
fave_number: fakeInt,
},
expectedObj: {
fave_number: fakeInt.valueOf(),
},
};
sandbox.stub(BigQuery, 'int').returns(fakeInt);
let mergedRows = BigQuery.mergeSchemaWithRows_(SCHEMA_OBJECT, rows.raw, {
wrapIntegers: wrapIntegersBoolean,
});
mergedRows.forEach((mergedRow: {}) => {
assert.deepStrictEqual(mergedRow, rows.expectedBool);
});
mergedRows = BigQuery.mergeSchemaWithRows_(SCHEMA_OBJECT, rows.raw, {
wrapIntegers: wrapIntegersObject,
});
mergedRows.forEach((mergedRow: {}) => {
assert.deepStrictEqual(mergedRow, rows.expectedObj);
});
});
it('should parse json with option', () => {
const jsonValue = {name: 'John Doe'};
const SCHEMA_OBJECT = {
fields: [{name: 'json_field', type: 'JSON'}],
} as {fields: TableField[]};
const rows = {
raw: {
f: [{v: JSON.stringify(jsonValue)}],
},
expectedParsed: {
json_field: jsonValue,
},
expectedRaw: {
json_field: JSON.stringify(jsonValue),
},
};
let mergedRows = BigQuery.mergeSchemaWithRows_(SCHEMA_OBJECT, rows.raw, {
parseJSON: false,
});
mergedRows.forEach((mergedRow: {}) => {
assert.deepStrictEqual(mergedRow, rows.expectedRaw);
});
mergedRows = BigQuery.mergeSchemaWithRows_(SCHEMA_OBJECT, rows.raw, {
parseJSON: true,
});
mergedRows.forEach((mergedRow: {}) => {
assert.deepStrictEqual(mergedRow, rows.expectedParsed);
});
});
});
describe('date', () => {
const INPUT_STRING = '2017-1-1';
const INPUT_OBJ = {
year: 2017,
month: 1,
day: 1,
};
// tslint:disable-next-line ban
it.skip('should expose static and instance constructors', () => {
const staticD = BigQuery.date();
assert(staticD instanceof BigQueryDate);
assert(staticD instanceof bq.date);
const instanceD = bq.date();
assert(instanceD instanceof BigQueryDate);
assert(instanceD instanceof bq.date);
});
it('should have the correct constructor name', () => {
const date = bq.date(INPUT_STRING);
assert.strictEqual(date.constructor.name, 'BigQueryDate');
});
it('should accept a string', () => {
const date = bq.date(INPUT_STRING);
assert.strictEqual(date.value, INPUT_STRING);
});
it('should accept an object', () => {
const date = bq.date(INPUT_OBJ);
assert.strictEqual(date.value, INPUT_STRING);
});
});
describe('datetime', () => {
const INPUT_STRING = '2017-1-1T14:2:38.883388Z';
const INPUT_OBJ = {
year: 2017,
month: 1,
day: 1,
hours: 14,
minutes: 2,
seconds: 38,
fractional: 883388,
};
const EXPECTED_VALUE = '2017-1-1 14:2:38.883388';
// tslint:disable-next-line ban
it.skip('should expose static and instance constructors', () => {
const staticDt = BigQuery.datetime(INPUT_OBJ);
assert(staticDt instanceof BigQuery.datetime);
assert(staticDt instanceof bq.datetime);
const instanceDt = bq.datetime(INPUT_OBJ);
assert(instanceDt instanceof BigQuery.datetime);
assert(instanceDt instanceof bq.datetime);
});
it('should have the correct constructor name', () => {
const datetime = bq.datetime(INPUT_STRING);
assert.strictEqual(datetime.constructor.name, 'BigQueryDatetime');
});
it('should accept an object', () => {
const datetime = bq.datetime(INPUT_OBJ);
assert.strictEqual(datetime.value, EXPECTED_VALUE);
});
it('should not include time if hours not provided', () => {
const datetime = bq.datetime({
year: 2016,
month: 1,
day: 1,
});
assert.strictEqual(datetime.value, '2016-1-1');
});
it('should accept a string', () => {
const datetime = bq.datetime(INPUT_STRING);
assert.strictEqual(datetime.value, EXPECTED_VALUE);
});
});
describe('time', () => {
const INPUT_STRING = '14:2:38.883388';
const INPUT_OBJ = {
hours: 14,
minutes: 2,
seconds: 38,
fractional: 883388,
};
// tslint:disable-next-line ban
it.skip('should expose static and instance constructors', () => {
const staticT = BigQuery.time();
assert(staticT instanceof BigQuery.time);
assert(staticT instanceof bq.time);
const instanceT = bq.time();
assert(instanceT instanceof BigQuery.time);
assert(instanceT instanceof bq.time);
});
it('should have the correct constructor name', () => {
const time = bq.time(INPUT_STRING);
assert.strictEqual(time.constructor.name, 'BigQueryTime');
});
it('should accept a string', () => {
const time = bq.time(INPUT_STRING);
assert.strictEqual(time.value, INPUT_STRING);
});
it('should accept an object', () => {
const time = bq.time(INPUT_OBJ);
assert.strictEqual(time.value, INPUT_STRING);
});
it('should default minutes and seconds to 0', () => {
const time = bq.time({
hours: 14,
});
assert.strictEqual(time.value, '14:0:0');
});
it('should not include fractional digits if not provided', () => {
const input = Object.assign({}, INPUT_OBJ) as InputObject;
delete input.fractional;
const time = bq.time(input);
assert.strictEqual(time.value, '14:2:38');
});
});
describe('timestamp', () => {
const INPUT_STRING = '2016-12-06T12:00:00.000Z';
const INPUT_STRING_MICROS = '2016-12-06T12:00:00.123456Z';
const INPUT_STRING_NEGATIVE = '1969-12-25T00:00:00.000Z';
const INPUT_DATE = new Date(INPUT_STRING);
const INPUT_PRECISE_DATE = new PreciseDate(INPUT_STRING_MICROS);
const INPUT_PRECISE_NEGATIVE_DATE = new PreciseDate(INPUT_STRING_NEGATIVE);
const EXPECTED_VALUE = INPUT_DATE.toJSON();
const EXPECTED_VALUE_MICROS = INPUT_PRECISE_DATE.toISOString();
// tslint:disable-next-line ban
it.skip('should expose static and instance constructors', () => {
const staticT = BigQuery.timestamp(INPUT_DATE);
assert(staticT instanceof BigQuery.timestamp);
assert(staticT instanceof bq.timestamp);
const instanceT = bq.timestamp(INPUT_DATE);
assert(instanceT instanceof BigQuery.timestamp);
assert(instanceT instanceof bq.timestamp);
});
it('should have the correct constructor name', () => {
const timestamp = bq.timestamp(INPUT_STRING);
assert.strictEqual(timestamp.constructor.name, 'BigQueryTimestamp');
});
it('should accept a NaN', () => {
const timestamp = bq.timestamp(NaN);
assert.strictEqual(timestamp.value, null);
});
it('should accept a string', () => {
const timestamp = bq.timestamp(INPUT_STRING);
assert.strictEqual(timestamp.value, EXPECTED_VALUE);
});
it('should accept a number in microseconds', () => {
let ms = INPUT_PRECISE_DATE.valueOf(); // milliseconds
let us = ms * 1000 + INPUT_PRECISE_DATE.getMicroseconds(); // microseconds
let timestamp = bq.timestamp(us);
assert.strictEqual(timestamp.value, EXPECTED_VALUE_MICROS);
let usStr = `${us}`;
timestamp = bq.timestamp(usStr);
assert.strictEqual(timestamp.value, EXPECTED_VALUE_MICROS);
ms = INPUT_PRECISE_NEGATIVE_DATE.valueOf();
us = ms * 1000;
timestamp = bq.timestamp(us);
assert.strictEqual(timestamp.value, INPUT_STRING_NEGATIVE);
usStr = `${us}`;
timestamp = bq.timestamp(usStr);
assert.strictEqual(timestamp.value, INPUT_STRING_NEGATIVE);
});
it('should accept a string with microseconds', () => {
const timestamp = bq.timestamp(INPUT_STRING_MICROS);
assert.strictEqual(timestamp.value, EXPECTED_VALUE_MICROS);
});
it('should accept a Date object', () => {
const timestamp = bq.timestamp(INPUT_DATE);
assert.strictEqual(timestamp.value, EXPECTED_VALUE);
});
it('should accept a PreciseDate object', () => {
const timestamp = bq.timestamp(INPUT_PRECISE_DATE);
assert.strictEqual(timestamp.value, EXPECTED_VALUE_MICROS);
});
});
describe('geography', () => {
const INPUT_STRING = 'POINT(1 2)';
it('should have the correct constructor name', () => {
const geography = BigQuery.geography(INPUT_STRING);
assert.strictEqual(geography.constructor.name, 'Geography');
});
it('should accept a string', () => {
const geography = BigQuery.geography(INPUT_STRING);
assert.strictEqual(geography.value, INPUT_STRING);
});
it('should call through to the static method', () => {
const fakeGeography = {value: 'foo'};
sandbox
.stub(BigQuery, 'geography')
.withArgs(INPUT_STRING)
.returns(fakeGeography);
const geography = bq.geography(INPUT_STRING);
assert.strictEqual(geography, fakeGeography);
});
});
describe('int', () => {
const INPUT_STRING = '100';
it('should call through to the static method', () => {
const fakeInt = new BigQueryInt(INPUT_STRING);
sandbox.stub(BigQuery, 'int').withArgs(INPUT_STRING).returns(fakeInt);
const int = bq.int(INPUT_STRING);
assert.strictEqual(int, fakeInt);
});
it('should have the correct constructor name', () => {
const int = BigQuery.int(INPUT_STRING);
assert.strictEqual(int.constructor.name, 'BigQueryInt');
});
});
describe('BigQueryInt', () => {
it('should store the stringified value', () => {
const INPUT_NUM = 100;
const int = new BigQueryInt(INPUT_NUM);
assert.strictEqual(int.value, INPUT_NUM.toString());
});
describe('valueOf', () => {
let valueObject: IntegerTypeCastValue;
beforeEach(() => {
valueObject = {
integerValue: 8,
};
});
describe('integerTypeCastFunction is not provided', () => {
const expectedError = (opts: {
integerValue: string | number;
schemaFieldName?: string;
}) => {
return new Error(
'We attempted to return all of the numeric values, but ' +
(opts.schemaFieldName ? opts.schemaFieldName + ' ' : '') +
'value ' +
opts.integerValue +
" is out of bounds of 'Number.MAX_SAFE_INTEGER'.\n" +
"To prevent this error, please consider passing 'options.wrapIntegers' as\n" +
'{\n' +
' integerTypeCastFunction: provide <your_custom_function>\n' +
' fields: optionally specify field name(s) to be custom casted\n' +
'}\n'
);
};