-
Notifications
You must be signed in to change notification settings - Fork 213
/
Copy pathbigquery.ts
2183 lines (2034 loc) · 67.9 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 * as common from '@google-cloud/common';
import {paginator, ResourceStream} from '@google-cloud/paginator';
import {promisifyAll} from '@google-cloud/promisify';
import arrify = require('arrify');
import {Big} from 'big.js';
import * as extend from 'extend';
import * as is from 'is';
import * as uuid from 'uuid';
import {Dataset, DatasetOptions} from './dataset';
import {Job, JobOptions, QueryResultsOptions} from './job';
import {
Table,
TableField,
TableSchema,
TableRow,
TableRowField,
JobCallback,
JobResponse,
RowMetadata,
} from './table';
import {GoogleErrorBody} from '@google-cloud/common/build/src/util';
import bigquery from './types';
export interface RequestCallback<T> {
(err: Error | null, response?: T | null): void;
}
export interface ResourceCallback<T, R> {
(err: Error | null, resource?: T | null, response?: R | null): void;
}
export type PagedResponse<T, Q, R> = [T[]] | [T[], Q | null, R];
export interface PagedCallback<T, Q, R> {
(
err: Error | null,
resource?: T[] | null,
nextQuery?: Q | null,
response?: R | null
): void;
}
export type JobRequest<J> = J & {
jobId?: string;
jobPrefix?: string;
location?: string;
};
export type PagedRequest<P> = P & {
autoPaginate?: boolean;
maxApiCalls?: number;
};
export type QueryRowsResponse = PagedResponse<
RowMetadata,
Query,
bigquery.IGetQueryResultsResponse
>;
export type QueryRowsCallback = PagedCallback<
RowMetadata,
Query,
bigquery.IGetQueryResultsResponse
>;
export type SimpleQueryRowsResponse = [RowMetadata[], bigquery.IJob];
export type SimpleQueryRowsCallback = ResourceCallback<
RowMetadata[],
bigquery.IJob
>;
export type Query = JobRequest<bigquery.IJobConfigurationQuery> & {
destination?: Table;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
params?: any[] | {[param: string]: any};
dryRun?: boolean;
labels?: {[label: string]: string};
types?: string[] | string[][] | {[type: string]: string | string[]};
job?: Job;
maxResults?: number;
jobTimeoutMs?: number;
pageToken?: string;
wrapIntegers?: boolean | IntegerTypeCastOptions;
};
export type QueryOptions = QueryResultsOptions;
export type QueryStreamOptions = {
wrapIntegers?: boolean | IntegerTypeCastOptions;
};
export type DatasetResource = bigquery.IDataset;
export type ValueType = bigquery.IQueryParameterType;
export type GetDatasetsOptions = PagedRequest<bigquery.datasets.IListParams>;
export type DatasetsResponse = PagedResponse<
Dataset,
GetDatasetsOptions,
bigquery.IDatasetList
>;
export type DatasetsCallback = PagedCallback<
Dataset,
GetDatasetsOptions,
bigquery.IDatasetList
>;
export type DatasetResponse = [Dataset, bigquery.IDataset];
export type DatasetCallback = ResourceCallback<Dataset, bigquery.IDataset>;
export type GetJobsOptions = PagedRequest<bigquery.jobs.IListParams>;
export type GetJobsResponse = PagedResponse<
Job,
GetJobsOptions,
bigquery.IJobList
>;
export type GetJobsCallback = PagedCallback<
Job,
GetJobsOptions,
bigquery.IJobList
>;
export interface BigQueryTimeOptions {
hours?: number | string;
minutes?: number | string;
seconds?: number | string;
fractional?: number | string;
}
export interface BigQueryDateOptions {
year?: number | string;
month?: number | string;
day?: number | string;
}
export interface BigQueryDatetimeOptions {
year?: string | number;
month?: string | number;
day?: string | number;
hours?: string | number;
minutes?: string | number;
seconds?: string | number;
fractional?: string | number;
}
export type ProvidedTypeArray = Array<ProvidedTypeStruct | string | []>;
export interface ProvidedTypeStruct {
[key: string]: string | ProvidedTypeArray | ProvidedTypeStruct;
}
export type QueryParameter = bigquery.IQueryParameter;
export interface BigQueryOptions extends common.GoogleAuthOptions {
autoRetry?: boolean;
maxRetries?: number;
location?: string;
userAgent?: string;
/**
* The API endpoint of the service used to make requests.
* Defaults to `bigquery.googleapis.com`.
*/
apiEndpoint?: string;
}
export interface IntegerTypeCastOptions {
integerTypeCastFunction: Function;
fields?: string | string[];
}
export type IntegerTypeCastValue = {
integerValue: string | number;
schemaFieldName?: string;
};
export const PROTOCOL_REGEX = /^(\w*):\/\//;
/**
* @typedef {object} BigQueryOptions
* @property {string} [projectId] The project ID from the Google Developer's
* Console, e.g. 'grape-spaceship-123'. We will also check the environment
* variable `GCLOUD_PROJECT` for your project ID. If your app is running in
* an environment which supports {@link
* https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application
* Application Default Credentials}, your project ID will be detected
* automatically.
* @property {string} [keyFilename] Full path to the a .json, .pem, or .p12 key
* downloaded from the Google Developers Console. If you provide a path to a
* JSON file, the `projectId` option above is not necessary. NOTE: .pem and
* .p12 require you to specify the `email` option as well.
* @property {string} [token] An OAUTH access token. If provided, we will not
* manage fetching, re-using, and re-minting access tokens.
* @property {string} [email] Account email address. Required when using a .pem
* or .p12 keyFilename.
* @property {object} [credentials] Credentials object.
* @property {string} [credentials.client_email]
* @property {string} [credentials.private_key]
* @property {boolean} [autoRetry=true] Automatically retry requests if the
* response is related to rate limits or certain intermittent server errors.
* We will exponentially backoff subsequent requests by default.
* @property {number} [maxRetries=3] Maximum number of automatic retries
* attempted before returning the error.
* @property {Constructor} [promise] Custom promise module to use instead of
* native Promises.
* @property {string} [location] The geographic location of all datasets and
* jobs referenced and created through the client.
* @property {string} [userAgent] The value to be prepended to the User-Agent
* header in API requests.
* @property {string[]} [scopes] Additional OAuth scopes to use in requests. For
* example, to access an external data source, you may need the
* `https://www.googleapis.com/auth/drive.readonly` scope.
* @property {string=} apiEndpoint The API endpoint of the service used to make requests. Defaults to `bigquery.googleapis.com`.
*/
/**
* In the following examples from this page and the other modules (`Dataset`,
* `Table`, etc.), we are going to be using a dataset from
* [data.gov](http://goo.gl/f2SXcb) of higher education institutions.
*
* We will create a table with the correct schema, import the public CSV file
* into that table, and query it for data.
*
* @class
*
* @see [What is BigQuery?]{@link https://cloud.google.com/bigquery/what-is-bigquery}
*
* @param {BigQueryOptions} options Constructor options.
*
* @example <caption>Install the client library with <a href="https://www.npmjs.com/">npm</a>:</caption>
* npm install @google-cloud/bigquery
*
* @example <caption>Import the client library</caption>
* const {BigQuery} = require('@google-cloud/bigquery');
*
* @example <caption>Create a client that uses <a href="https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application">Application Default Credentials (ADC)</a>:</caption>
* const bigquery = new BigQuery();
*
* @example <caption>Create a client with <a href="https://cloud.google.com/docs/authentication/production#obtaining_and_providing_service_account_credentials_manually">explicit credentials</a>:</caption>
* const bigquery = new BigQuery({
* projectId: 'your-project-id',
* keyFilename: '/path/to/keyfile.json'
* });
*
* @example <caption>include:samples/quickstart.js</caption>
* region_tag:bigquery_quickstart
* Full quickstart example:
*/
export class BigQuery extends common.Service {
location?: string;
createQueryStream: (options?: Query | string) => ResourceStream<RowMetadata>;
getDatasetsStream: (options?: GetDatasetsOptions) => ResourceStream<Dataset>;
getJobsStream: (options?: GetJobsOptions) => ResourceStream<Job>;
constructor(options: BigQueryOptions = {}) {
let apiEndpoint = 'https://bigquery.googleapis.com';
const EMULATOR_HOST = process.env.BIGQUERY_EMULATOR_HOST;
if (typeof EMULATOR_HOST === 'string') {
apiEndpoint = BigQuery.sanitizeEndpoint(EMULATOR_HOST);
}
if (options.apiEndpoint) {
apiEndpoint = BigQuery.sanitizeEndpoint(options.apiEndpoint);
}
options = Object.assign({}, options, {
apiEndpoint,
});
const baseUrl = EMULATOR_HOST || `${options.apiEndpoint}/bigquery/v2`;
const config = {
apiEndpoint: options.apiEndpoint!,
baseUrl,
scopes: ['https://www.googleapis.com/auth/bigquery'],
packageJson: require('../../package.json'),
};
if (options.scopes) {
config.scopes = config.scopes.concat(options.scopes);
}
super(config, options);
/**
* @name BigQuery#location
* @type {string}
*/
this.location = options.location;
/**
* Run a query scoped to your project as a readable object stream.
*
* @param {object} query Configuration object. See {@link Query} for a complete
* list of options.
* @returns {stream}
*
* @example
* const {BigQuery} = require('@google-cloud/bigquery');
* const bigquery = new BigQuery();
*
* const query = 'SELECT url FROM `publicdata.samples.github_nested` LIMIT
* 100';
*
* bigquery.createQueryStream(query)
* .on('error', console.error)
* .on('data', function(row) {
* // row is a result from your query.
* })
* .on('end', function() {
* // All rows retrieved.
* });
*
* //-
* // If you anticipate many results, you can end a stream early to prevent
* // unnecessary processing and API requests.
* //-
* bigquery.createQueryStream(query)
* .on('data', function(row) {
* this.end();
* });
*/
this.createQueryStream = paginator.streamify<RowMetadata>('queryAsStream_');
/**
* List all or some of the {@link Dataset} objects in your project as
* a readable object stream.
*
* @param {object} [options] Configuration object. See
* {@link BigQuery#getDatasets} for a complete list of options.
* @returns {stream}
*
* @example
* const {BigQuery} = require('@google-cloud/bigquery');
* const bigquery = new BigQuery();
*
* bigquery.getDatasetsStream()
* .on('error', console.error)
* .on('data', function(dataset) {
* // dataset is a Dataset object.
* })
* .on('end', function() {
* // All datasets retrieved.
* });
*
* //-
* // If you anticipate many results, you can end a stream early to prevent
* // unnecessary processing and API requests.
* //-
* bigquery.getDatasetsStream()
* .on('data', function(dataset) {
* this.end();
* });
*/
this.getDatasetsStream = paginator.streamify<Dataset>('getDatasets');
/**
* List all or some of the {@link Job} objects in your project as a
* readable object stream.
*
* @param {object} [options] Configuration object. See
* {@link BigQuery#getJobs} for a complete list of options.
* @returns {stream}
*
* @example
* const {BigQuery} = require('@google-cloud/bigquery');
* const bigquery = new BigQuery();
*
* bigquery.getJobsStream()
* .on('error', console.error)
* .on('data', function(job) {
* // job is a Job object.
* })
* .on('end', function() {
* // All jobs retrieved.
* });
*
* //-
* // If you anticipate many results, you can end a stream early to prevent
* // unnecessary processing and API requests.
* //-
* bigquery.getJobsStream()
* .on('data', function(job) {
* this.end();
* });
*/
this.getJobsStream = paginator.streamify<Job>('getJobs');
// Disable `prettyPrint` for better performance.
// https://github.com/googleapis/nodejs-bigquery/issues/858
this.interceptors.push({
request: (reqOpts: common.DecorateRequestOptions) => {
return extend(true, {}, reqOpts, {qs: {prettyPrint: false}});
},
});
}
private static sanitizeEndpoint(url: string) {
if (!PROTOCOL_REGEX.test(url)) {
url = `https://${url}`;
}
return url.replace(/\/+$/, ''); // Remove trailing slashes
}
/**
* Merge a rowset returned from the API with a table schema.
*
* @private
*
* @param {object} schema
* @param {array} rows
* @param {boolean|IntegerTypeCastOptions} wrapIntegers Wrap values of
* 'INT64' type in {@link BigQueryInt} objects.
* If a `boolean`, this will wrap values in {@link BigQueryInt} objects.
* If an `object`, this will return a value returned by
* `wrapIntegers.integerTypeCastFunction`.
* Please see {@link IntegerTypeCastOptions} for options descriptions.
* @param {array} selectedFields List of fields to return.
* If unspecified, all fields are returned.
* @returns {array} Fields using their matching names from the table's schema.
*/
static mergeSchemaWithRows_(
schema: TableSchema | TableField,
rows: TableRow[],
wrapIntegers: boolean | IntegerTypeCastOptions,
selectedFields?: string[]
) {
if (selectedFields && selectedFields!.length > 0) {
const selectedFieldsArray = selectedFields!.map(c => {
return c.split('.');
});
const currentFields = selectedFieldsArray.map(c => c.shift());
//filter schema fields based on selected fields.
schema.fields = schema.fields?.filter(
field =>
currentFields
.map(c => c!.toLowerCase())
.indexOf(field.name!.toLowerCase()) >= 0
);
selectedFields = selectedFieldsArray
.filter(c => c.length > 0)
.map(c => c.join('.'));
}
return arrify(rows)
.map(mergeSchema)
.map(flattenRows);
function mergeSchema(row: TableRow) {
return row.f!.map((field: TableRowField, index: number) => {
const schemaField = schema.fields![index];
let value = field.v;
if (schemaField.mode === 'REPEATED') {
value = (value as TableRowField[]).map(val => {
return convert(schemaField, val.v, wrapIntegers, selectedFields);
});
} else {
value = convert(schemaField, value, wrapIntegers, selectedFields);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const fieldObject: any = {};
fieldObject[schemaField.name!] = value;
return fieldObject;
});
}
function convert(
schemaField: TableField,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
value: any,
wrapIntegers: boolean | IntegerTypeCastOptions,
selectedFields?: string[]
) {
if (is.null(value)) {
return value;
}
switch (schemaField.type) {
case 'BOOLEAN':
case 'BOOL': {
value = value.toLowerCase() === 'true';
break;
}
case 'BYTES': {
value = Buffer.from(value, 'base64');
break;
}
case 'FLOAT':
case 'FLOAT64': {
value = Number(value);
break;
}
case 'INTEGER':
case 'INT64': {
value = wrapIntegers
? typeof wrapIntegers === 'object'
? BigQuery.int(
{integerValue: value, schemaFieldName: schemaField.name},
wrapIntegers
).valueOf()
: BigQuery.int(value)
: Number(value);
break;
}
case 'NUMERIC': {
value = new Big(value);
break;
}
case 'BIGNUMERIC': {
value = new Big(value);
break;
}
case 'RECORD': {
value = BigQuery.mergeSchemaWithRows_(
schemaField,
value,
wrapIntegers,
selectedFields
).pop();
break;
}
case 'DATE': {
value = BigQuery.date(value);
break;
}
case 'DATETIME': {
value = BigQuery.datetime(value);
break;
}
case 'TIME': {
value = BigQuery.time(value);
break;
}
case 'TIMESTAMP': {
value = BigQuery.timestamp(new Date(value * 1000));
break;
}
case 'GEOGRAPHY': {
value = BigQuery.geography(value);
break;
}
default:
break;
}
return value;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function flattenRows(rows: any[]) {
return rows.reduce((acc, row) => {
const key = Object.keys(row)[0];
acc[key] = row[key];
return acc;
}, {});
}
}
/**
* The `DATE` type represents a logical calendar date, independent of time
* zone. It does not represent a specific 24-hour time period. Rather, a given
* DATE value represents a different 24-hour period when interpreted in
* different time zones, and may represent a shorter or longer day during
* Daylight Savings Time transitions.
*
* @param {object|string} value The date. If a string, this should be in the
* format the API describes: `YYYY-[M]M-[D]D`.
* Otherwise, provide an object.
* @param {string|number} value.year Four digits.
* @param {string|number} value.month One or two digits.
* @param {string|number} value.day One or two digits.
*
* @example
* const {BigQuery} = require('@google-cloud/bigquery');
* const bigquery = new BigQuery();
* const date = bigquery.date('2017-01-01');
*
* //-
* // Alternatively, provide an object.
* //-
* const date2 = bigquery.date({
* year: 2017,
* month: 1,
* day: 1
* });
*/
static date(value: BigQueryDateOptions | string) {
return new BigQueryDate(value);
}
/**
* @param {object|string} value The date. If a string, this should be in the
* format the API describes: `YYYY-[M]M-[D]D`.
* Otherwise, provide an object.
* @param {string|number} value.year Four digits.
* @param {string|number} value.month One or two digits.
* @param {string|number} value.day One or two digits.
*
* @example
* const {BigQuery} = require('@google-cloud/bigquery');
* const date = BigQuery.date('2017-01-01');
*
* //-
* // Alternatively, provide an object.
* //-
* const date2 = BigQuery.date({
* year: 2017,
* month: 1,
* day: 1
* });
*/
date(value: BigQueryDateOptions | string) {
return BigQuery.date(value);
}
/**
* A `DATETIME` data type represents a point in time. Unlike a `TIMESTAMP`,
* this does not refer to an absolute instance in time. Instead, it is the
* civil time, or the time that a user would see on a watch or calendar.
*
* @method BigQuery.datetime
* @param {object|string} value The time. If a string, this should be in the
* format the API describes: `YYYY-[M]M-[D]D[ [H]H:[M]M:[S]S[.DDDDDD]]`.
* Otherwise, provide an object.
* @param {string|number} value.year Four digits.
* @param {string|number} value.month One or two digits.
* @param {string|number} value.day One or two digits.
* @param {string|number} [value.hours] One or two digits (`00` - `23`).
* @param {string|number} [value.minutes] One or two digits (`00` - `59`).
* @param {string|number} [value.seconds] One or two digits (`00` - `59`).
* @param {string|number} [value.fractional] Up to six digits for microsecond
* precision.
*
* @example
* const {BigQuery} = require('@google-cloud/bigquery');
* const datetime = BigQuery.datetime('2017-01-01 13:00:00');
*
* //-
* // Alternatively, provide an object.
* //-
* const datetime = BigQuery.datetime({
* year: 2017,
* month: 1,
* day: 1,
* hours: 14,
* minutes: 0,
* seconds: 0
* });
*/
/**
* A `DATETIME` data type represents a point in time. Unlike a `TIMESTAMP`,
* this does not refer to an absolute instance in time. Instead, it is the
* civil time, or the time that a user would see on a watch or calendar.
*
* @method BigQuery#datetime
* @param {object|string} value The time. If a string, this should be in the
* format the API describes: `YYYY-[M]M-[D]D[ [H]H:[M]M:[S]S[.DDDDDD]]`.
* Otherwise, provide an object.
* @param {string|number} value.year Four digits.
* @param {string|number} value.month One or two digits.
* @param {string|number} value.day One or two digits.
* @param {string|number} [value.hours] One or two digits (`00` - `23`).
* @param {string|number} [value.minutes] One or two digits (`00` - `59`).
* @param {string|number} [value.seconds] One or two digits (`00` - `59`).
* @param {string|number} [value.fractional] Up to six digits for microsecond
* precision.
*
* @example
* const {BigQuery} = require('@google-cloud/bigquery');
* const bigquery = new BigQuery();
* const datetime = bigquery.datetime('2017-01-01 13:00:00');
*
* //-
* // Alternatively, provide an object.
* //-
* const datetime = bigquery.datetime({
* year: 2017,
* month: 1,
* day: 1,
* hours: 14,
* minutes: 0,
* seconds: 0
* });
*/
static datetime(value: BigQueryDatetimeOptions | string) {
return new BigQueryDatetime(value);
}
datetime(value: BigQueryDatetimeOptions | string) {
return BigQuery.datetime(value);
}
/**
* A `TIME` data type represents a time, independent of a specific date.
*
* @method BigQuery.time
* @param {object|string} value The time. If a string, this should be in the
* format the API describes: `[H]H:[M]M:[S]S[.DDDDDD]`. Otherwise, provide
* an object.
* @param {string|number} [value.hours] One or two digits (`00` - `23`).
* @param {string|number} [value.minutes] One or two digits (`00` - `59`).
* @param {string|number} [value.seconds] One or two digits (`00` - `59`).
* @param {string|number} [value.fractional] Up to six digits for microsecond
* precision.
*
* @example
* const {BigQuery} = require('@google-cloud/bigquery');
* const time = BigQuery.time('14:00:00'); // 2:00 PM
*
* //-
* // Alternatively, provide an object.
* //-
* const time = BigQuery.time({
* hours: 14,
* minutes: 0,
* seconds: 0
* });
*/
/**
* A `TIME` data type represents a time, independent of a specific date.
*
* @method BigQuery#time
* @param {object|string} value The time. If a string, this should be in the
* format the API describes: `[H]H:[M]M:[S]S[.DDDDDD]`. Otherwise, provide
* an object.
* @param {string|number} [value.hours] One or two digits (`00` - `23`).
* @param {string|number} [value.minutes] One or two digits (`00` - `59`).
* @param {string|number} [value.seconds] One or two digits (`00` - `59`).
* @param {string|number} [value.fractional] Up to six digits for microsecond
* precision.
*
* @example
* const {BigQuery} = require('@google-cloud/bigquery');
* const bigquery = new BigQuery();
* const time = bigquery.time('14:00:00'); // 2:00 PM
*
* //-
* // Alternatively, provide an object.
* //-
* const time = bigquery.time({
* hours: 14,
* minutes: 0,
* seconds: 0
* });
*/
static time(value: BigQueryTimeOptions | string) {
return new BigQueryTime(value);
}
time(value: BigQueryTimeOptions | string) {
return BigQuery.time(value);
}
/**
* A timestamp represents an absolute point in time, independent of any time
* zone or convention such as Daylight Savings Time.
*
* @method BigQuery.timestamp
* @param {Date|string} value The time.
*
* @example
* const {BigQuery} = require('@google-cloud/bigquery');
* const timestamp = BigQuery.timestamp(new Date());
*/
/**
* A timestamp represents an absolute point in time, independent of any time
* zone or convention such as Daylight Savings Time.
*
* @method BigQuery#timestamp
* @param {Date|string} value The time.
*
* @example
* const {BigQuery} = require('@google-cloud/bigquery');
* const bigquery = new BigQuery();
* const timestamp = bigquery.timestamp(new Date());
*/
static timestamp(value: Date | string) {
return new BigQueryTimestamp(value);
}
timestamp(value: Date | string) {
return BigQuery.timestamp(value);
}
/**
* A BigQueryInt wraps 'INT64' values. Can be used to maintain precision.
*
* @method BigQuery#int
* @param {string|number|IntegerTypeCastValue} value The INT64 value to convert.
* @param {IntegerTypeCastOptions} typeCastOptions Configuration to convert
* value. Must provide an `integerTypeCastFunction` to handle conversion.
*
* @example
* const {BigQuery} = require('@google-cloud/bigquery');
* const bigquery = new BigQuery();
*
* const largeIntegerValue = Number.MAX_SAFE_INTEGER + 1;
*
* const options = {
* integerTypeCastFunction: value => value.split(),
* };
*
* const bqInteger = bigquery.int(largeIntegerValue, options);
*
* const customValue = bqInteger.valueOf();
* // customValue is the value returned from your `integerTypeCastFunction`.
*/
static int(
value: string | number | IntegerTypeCastValue,
typeCastOptions?: IntegerTypeCastOptions
) {
return new BigQueryInt(value, typeCastOptions);
}
int(
value: string | number | IntegerTypeCastValue,
typeCastOptions?: IntegerTypeCastOptions
) {
return BigQuery.int(value, typeCastOptions);
}
/**
* A geography value represents a surface area on the Earth
* in Well-known Text (WKT) format.
*
* @method BigQuery.geography
* @param {string} value The geospatial data.
*
* @example
* const {BigQuery} = require('@google-cloud/bigquery');
* const geography = BigQuery.geography('POINT(1, 2)');
*/
/**
* A geography value represents a surface area on the Earth
* in Well-known Text (WKT) format.
*
* @method BigQuery#geography
* @param {string} value The geospatial data.
*
* @example
* const {BigQuery} = require('@google-cloud/bigquery');
* const bigquery = new BigQuery();
* const geography = bigquery.geography('POINT(1, 2)');
*/
static geography(value: string) {
return new Geography(value);
}
geography(value: string) {
return BigQuery.geography(value);
}
/**
* Convert an INT64 value to Number.
*
* @private
* @param {object} value The INT64 value to convert.
*/
static decodeIntegerValue_(value: IntegerTypeCastValue) {
const num = Number(value.integerValue);
if (!Number.isSafeInteger(num)) {
throw new Error(
'We attempted to return all of the numeric values, but ' +
(value.schemaFieldName ? value.schemaFieldName + ' ' : '') +
'value ' +
value.integerValue +
" is out of bounds of 'Number.MAX_SAFE_INTEGER'.\n" +
"To prevent this error, please consider passing 'options.wrapNumbers' as\n" +
'{\n' +
' integerTypeCastFunction: provide <your_custom_function>\n' +
' fields: optionally specify field name(s) to be custom casted\n' +
'}\n'
);
}
return num;
}
/**
* Return a value's provided type.
*
* @private
*
* @throws {error} If the type provided is invalid.
*
* @see [Data Type]{@link https://cloud.google.com/bigquery/data-types}
*
* @param {*} providedType The type.
* @returns {string} The valid type provided.
*/
static getTypeDescriptorFromProvidedType_(
providedType: string | ProvidedTypeStruct | ProvidedTypeArray
): ValueType {
// The list of types can be found in src/types.d.ts
const VALID_TYPES = [
'DATE',
'DATETIME',
'TIME',
'TIMESTAMP',
'BYTES',
'NUMERIC',
'BIGNUMERIC',
'BOOL',
'INT64',
'FLOAT64',
'STRING',
'GEOGRAPHY',
'ARRAY',
'STRUCT',
];
if (is.array(providedType)) {
providedType = providedType as Array<ProvidedTypeStruct | string | []>;
return {
type: 'ARRAY',
arrayType: BigQuery.getTypeDescriptorFromProvidedType_(providedType[0]),
};
} else if (is.object(providedType)) {
return {
type: 'STRUCT',
structTypes: Object.keys(providedType).map(prop => {
return {
name: prop,
type: BigQuery.getTypeDescriptorFromProvidedType_(
(providedType as ProvidedTypeStruct)[prop]
),
};
}),
};
}
providedType = (providedType as string).toUpperCase();
if (!VALID_TYPES.includes(providedType)) {
throw new Error(`Invalid type provided: "${providedType}"`);
}
return {type: providedType.toUpperCase()};
}
/**
* Detect a value's type.
*
* @private
*
* @throws {error} If the type could not be detected.
*
* @see [Data Type]{@link https://cloud.google.com/bigquery/data-types}
*
* @param {*} value The value.
* @returns {string} The type detected from the value.
*/
static getTypeDescriptorFromValue_(value: unknown): ValueType {
let typeName;
if (value === null) {
throw new Error(
"Parameter types must be provided for null values via the 'types' field in query options."
);
}
if (value instanceof BigQueryDate) {
typeName = 'DATE';
} else if (value instanceof BigQueryDatetime) {
typeName = 'DATETIME';
} else if (value instanceof BigQueryTime) {
typeName = 'TIME';
} else if (value instanceof BigQueryTimestamp) {
typeName = 'TIMESTAMP';
} else if (value instanceof Buffer) {
typeName = 'BYTES';
} else if (value instanceof Big) {
if (value.c.length - value.e >= 10) {
typeName = 'BIGNUMERIC';
} else {
typeName = 'NUMERIC';
}
} else if (value instanceof BigQueryInt) {
typeName = 'INT64';
} else if (value instanceof Geography) {
typeName = 'GEOGRAPHY';
} else if (Array.isArray(value)) {
if (value.length === 0) {
throw new Error(