-
Notifications
You must be signed in to change notification settings - Fork 213
/
Copy pathdataset.ts
623 lines (581 loc) · 18.9 KB
/
dataset.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
/*!
* Copyright 2014 Google Inc. All Rights Reserved.
*
* 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';
import {ServiceObject} from '@google-cloud/common';
import {paginator} from '@google-cloud/paginator';
import {promisifyAll} from '@google-cloud/promisify';
import * as extend from 'extend';
import * as is from 'is';
import {Table} from './table';
import * as request from 'request';
/**
* Interact with your BigQuery dataset. Create a Dataset instance with
* {@link BigQuery#createDataset} or {@link BigQuery#dataset}.
*
* @class
* @param {BigQuery} bigQuery {@link BigQuery} instance.
* @param {string} id The ID of the Dataset.
* @param {object} [options] Dataset options.
* @param {string} [options.location] The geographic location of the dataset.
* Defaults to US.
*
* @example
* const BigQuery = require('@google-cloud/bigquery');
* const bigquery = new BigQuery();
* const dataset = bigquery.dataset('institutions');
*/
class Dataset extends ServiceObject {
constructor(bigQuery, id, options) {
const methods = {
/**
* Create a dataset.
*
* @method Dataset#create
* @param {function} [callback] The callback function.
* @param {?error} callback.err An error returned while making this
* request.
* @param {Dataset} callback.dataset The created dataset.
* @param {object} callback.apiResponse The full API response.
* @returns {Promise}
*
* @example
* const BigQuery = require('@google-cloud/bigquery');
* const bigquery = new BigQuery();
* const dataset = bigquery.dataset('institutions');
* dataset.create((err, dataset, apiResponse) => {
* if (!err) {
* // The dataset was created successfully.
* }
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* dataset.create().then((data) => {
* const dataset = data[0];
* const apiResponse = data[1];
* });
*/
create: true,
/**
* Check if the dataset exists.
*
* @method Dataset#exists
* @param {function} [callback] The callback function.
* @param {?error} callback.err An error returned while making this
* request.
* @param {boolean} callback.exists Whether the dataset exists or not.
* @returns {Promise}
*
* @example
* const BigQuery = require('@google-cloud/bigquery');
* const bigquery = new BigQuery();
* const dataset = bigquery.dataset('institutions');
* dataset.exists((err, exists) => {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* dataset.exists().then((data) => {
* const exists = data[0];
* });
*/
exists: true,
/**
* Get a dataset if it exists.
*
* You may optionally use this to "get or create" an object by providing an
* object with `autoCreate` set to `true`. Any extra configuration that is
* normally required for the `create` method must be contained within this
* object as well.
*
* @method Dataset#get
* @param {options} [options] Configuration object.
* @param {boolean} [options.autoCreate=false] Automatically create the
* object if it does not exist.
* @param {function} [callback] The callback function.
* @param {?error} callback.err An error returned while making this
* request.
* @param {Dataset} callback.dataset The dataset.
* @returns {Promise}
*
* @example
* const BigQuery = require('@google-cloud/bigquery');
* const bigquery = new BigQuery();
* const dataset = bigquery.dataset('institutions');
* dataset.get((err, dataset, apiResponse) => {
* if (!err) {
* // `dataset.metadata` has been populated.
* }
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* dataset.get().then((data) => {
* const dataset = data[0];
* const apiResponse = data[1];
* });
*/
get: true,
/**
* Get the metadata for the Dataset.
*
* @see [Datasets: get API Documentation]{@link https://cloud.google.com/bigquery/docs/reference/v2/datasets/get}
*
* @method Dataset#getMetadata
* @param {function} [callback] The callback function.
* @param {?error} callback.err An error returned while making this
* request.
* @param {object} callback.metadata The dataset's metadata.
* @param {object} callback.apiResponse The full API response.
* @returns {Promise}
*
* @example
* const BigQuery = require('@google-cloud/bigquery');
* const bigquery = new BigQuery();
* const dataset = bigquery.dataset('institutions');
* dataset.getMetadata((err, metadata, apiResponse) => {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* dataset.getMetadata().then((data) => {
* const metadata = data[0];
* const apiResponse = data[1];
* });
*/
getMetadata: true,
/**
* Sets the metadata of the Dataset object.
*
* @see [Datasets: patch API Documentation]{@link https://cloud.google.com/bigquery/docs/reference/v2/datasets/patch}
*
* @method Dataset#setMetadata
* @param {object} metadata Metadata to save on the Dataset.
* @param {function} [callback] The callback function.
* @param {?error} callback.err An error returned while making this
* request.
* @param {object} callback.apiResponse The full API response.
* @returns {Promise}
*
* @example
* const BigQuery = require('@google-cloud/bigquery');
* const bigquery = new BigQuery();
* const dataset = bigquery.dataset('institutions');
*
* const metadata = {
* description: 'Info for every institution in the 2013 IPEDS universe'
* };
*
* dataset.setMetadata(metadata, (err, apiResponse) => {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* dataset.setMetadata(metadata).then((data) => {
* const apiResponse = data[0];
* });
*/
setMetadata: true,
};
super({
parent: bigQuery,
baseUrl: '/datasets',
id: id,
methods: methods,
requestModule: request,
createMethod: (id, options, callback) => {
if (is.fn(options)) {
callback = options;
options = {};
}
options = extend({}, options, {location: this.location});
return bigQuery.createDataset(id, options, callback);
},
});
if (options && options.location) {
this.location = options.location;
}
this.bigQuery = bigQuery;
// Catch all for read-modify-write cycle
// https://cloud.google.com/bigquery/docs/api-performance#read-patch-write
this.interceptors.push({
request: function(reqOpts) {
if (reqOpts.method === 'PATCH' && reqOpts.json.etag) {
reqOpts.headers = reqOpts.headers || {};
reqOpts.headers['If-Match'] = reqOpts.json.etag;
}
return reqOpts;
},
});
/**
* List all or some of the {module:bigquery/table} objects in your project as a
* readable object stream.
*
* @param {object} [options] Configuration object. See
* {@link Dataset#getTables} for a complete list of options.
* @return {stream}
*
* @example
* const BigQuery = require('@google-cloud/bigquery');
* const bigquery = new BigQuery();
* const dataset = bigquery.dataset('institutions');
*
* dataset.getTablesStream()
* .on('error', console.error)
* .on('data', (table) => {})
* .on('end', () => {
* // All tables have been retrieved
* });
*
* //-
* // If you anticipate many results, you can end a stream early to prevent
* // unnecessary processing and API requests.
* //-
* dataset.getTablesStream()
* .on('data', function(table) {
* this.end();
* });
*/
this.getTablesStream = paginator.streamify('getTables');
}
/**
* Run a query as a job. No results are immediately returned. Instead, your
* callback will be executed with a {@link Job} object that you must
* ping for the results. See the Job documentation for explanations of how to
* check on the status of the job.
*
* See {@link BigQuery#createQueryJob} for full documentation of this method.
*
* @param {object} options See {@link BigQuery#createQueryJob} for full documentation of this method.
* @param {function} [callback] See {@link BigQuery#createQueryJob} for full documentation of this method.
* @returns {Promise} See {@link BigQuery#createQueryJob} for full documentation of this method.
*/
createQueryJob(options, callback) {
if (is.string(options)) {
options = {
query: options,
};
}
options = extend(true, {}, options, {
defaultDataset: {
datasetId: this.id,
},
location: this.location,
});
return this.bigQuery.createQueryJob(options, callback);
};
/**
* Run a query scoped to your dataset as a readable object stream.
*
* See {@link BigQuery#createQueryStream} for full documentation of this
* method.
*
* @param {object} options See {@link BigQuery#createQueryStream} for full
* documentation of this method.
* @returns {stream}
*/
createQueryStream(options) {
if (is.string(options)) {
options = {
query: options,
};
}
options = extend(true, {}, options, {
defaultDataset: {
datasetId: this.id,
},
location: this.location,
});
return this.bigQuery.createQueryStream(options);
};
/**
* Create a table given a tableId or configuration object.
*
* @see [Tables: insert API Documentation]{@link https://cloud.google.com/bigquery/docs/reference/v2/tables/insert}
*
* @param {string} id Table id.
* @param {object} [options] See a
* [Table resource](https://cloud.google.com/bigquery/docs/reference/v2/tables#resource).
* @param {string|object} [options.schema] A comma-separated list of name:type
* pairs. Valid types are "string", "integer", "float", "boolean", and
* "timestamp". If the type is omitted, it is assumed to be "string".
* Example: "name:string, age:integer". Schemas can also be specified as a
* JSON array of fields, which allows for nested and repeated fields. See
* a [Table resource](http://goo.gl/sl8Dmg) for more detailed information.
* @param {function} [callback] The callback function.
* @param {?error} callback.err An error returned while making this request
* @param {Table} callback.table The newly created table.
* @param {object} callback.apiResponse The full API response.
* @returns {Promise}
*
* @example
* const BigQuery = require('@google-cloud/bigquery');
* const bigquery = new BigQuery();
* const dataset = bigquery.dataset('institutions');
*
* const tableId = 'institution_data';
*
* const options = {
* // From the data.gov CSV dataset (http://goo.gl/kSE7z6):
* schema: 'UNITID,INSTNM,ADDR,CITY,STABBR,ZIP,FIPS,OBEREG,CHFNM,...'
* };
*
* dataset.createTable(tableId, options, (err, table, apiResponse) => {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* dataset.createTable(tableId, options).then((data) => {
* const table = data[0];
* const apiResponse = data[1];
* });
*/
createTable(id, options, callback) {
if (is.fn(options)) {
callback = options;
options = {};
}
const body = Table.formatMetadata_(options);
body.tableReference = {
datasetId: this.id,
projectId: this.bigQuery.projectId,
tableId: id,
};
this.request(
{
method: 'POST',
uri: '/tables',
json: body,
},
(err, resp) => {
if (err) {
callback(err, null, resp);
return;
}
const table = this.table(resp.tableReference.tableId, {
location: resp.location,
});
table.metadata = resp;
callback(null, table, resp);
}
);
};
/**
* Delete the dataset.
*
* @see [Datasets: delete API Documentation]{@link https://cloud.google.com/bigquery/docs/reference/v2/datasets/delete}
*
* @param {object} [options] The configuration object.
* @param {boolean} [options.force=false] Force delete dataset and all tables.
* @param {function} [callback] The callback function.
* @param {?error} callback.err An error returned while making this request
* @param {object} callback.apiResponse The full API response.
* @returns {Promise}
*
* @example
* const BigQuery = require('@google-cloud/bigquery');
* const bigquery = new BigQuery();
* const dataset = bigquery.dataset('institutions');
*
* //-
* // Delete the dataset, only if it does not have any tables.
* //-
* dataset.delete((err, apiResponse) => {});
*
* //-
* // Delete the dataset and any tables it contains.
* //-
* dataset.delete({ force: true }, (err, apiResponse) => {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* dataset.delete().then((data) => {
* const apiResponse = data[0];
* });
*/
delete(options, callback?) {
if (!callback) {
callback = options;
options = {};
}
const query = {
deleteContents: !!options.force,
};
this.request(
{
method: 'DELETE',
uri: '',
qs: query,
},
callback
);
};
/**
* Get a list of tables.
*
* @see [Tables: list API Documentation]{@link https://cloud.google.com/bigquery/docs/reference/v2/tables/list}
*
* @param {object} [options] Configuration object.
* @param {boolean} [options.autoPaginate=true] Have pagination handled automatically.
* @param {number} [options.maxApiCalls] Maximum number of API calls to make.
* @param {number} [options.maxResults] Maximum number of results to return.
* @param {string} [options.pageToken] Token returned from a previous call, to
* request the next page of results.
* @param {function} [callback] The callback function.
* @param {?error} callback.err An error returned while making this request
* @param {Table[]} callback.tables The list of tables from
* your Dataset.
* @returns {Promise}
*
* @example
* const BigQuery = require('@google-cloud/bigquery');
* const bigquery = new BigQuery();
* const dataset = bigquery.dataset('institutions');
*
* dataset.getTables((err, tables) => {
* // tables is an array of `Table` objects.
* });
*
* //-
* // To control how many API requests are made and page through the results
* // manually, set `autoPaginate` to `false`.
* //-
* function manualPaginationCallback(err, tables, nextQuery, apiResponse) {
* if (nextQuery) {
* // More results exist.
* dataset.getTables(nextQuery, manualPaginationCallback);
* }
* }
*
* dataset.getTables({
* autoPaginate: false
* }, manualPaginationCallback);
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* dataset.getTables().then((data) => {
* const tables = data[0];
* });
*/
getTables(options, callback) {
if (is.fn(options)) {
callback = options;
options = {};
}
options = options || {};
this.request(
{
uri: '/tables',
qs: options,
},
(err, resp) => {
if (err) {
callback(err, null, null, resp);
return;
}
let nextQuery = null;
if (resp.nextPageToken) {
nextQuery = extend({}, options, {
pageToken: resp.nextPageToken,
});
}
const tables = (resp.tables || []).map(tableObject => {
const table = this.table(tableObject.tableReference.tableId, {
location: tableObject.location,
});
table.metadata = tableObject;
return table;
});
callback(null, tables, nextQuery, resp);
}
);
};
/**
* Run a query scoped to your dataset.
*
* See {@link BigQuery#query} for full documentation of this method.
*
* @param {object} options See {@link BigQuery#query} for full documentation of this method.
* @param {function} [callback] See {@link BigQuery#query} for full documentation of this method.
* @returns {Promise} See {@link BigQuery#query} for full documentation of this method.
*/
query(options, callback) {
if (is.string(options)) {
options = {
query: options,
};
}
options = extend(true, {}, options, {
defaultDataset: {
datasetId: this.id,
},
location: this.location,
});
return this.bigQuery.query(options, callback);
};
/**
* Create a Table object.
*
* @param {string} id The ID of the table.
* @param {object} [options] Table options.
* @param {string} [options.location] The geographic location of the table, by
* default this value is inherited from the dataset. This can be used to
* configure the location of all jobs created through a table instance. It
* cannot be used to set the actual location of the table. This value will
* be superseded by any API responses containing location data for the
* table.
* @return {Table}
*
* @example
* const BigQuery = require('@google-cloud/bigquery');
* const bigquery = new BigQuery();
* const dataset = bigquery.dataset('institutions');
*
* const institutions = dataset.table('institution_data');
*/
table(id, options) {
options = extend(
{
location: this.location,
},
options
);
return new Table(this, id, options);
};
}
/*! Developer Documentation
*
* These methods can be auto-paginated.
*/
paginator.extend(Dataset, ['getTables']);
/*! Developer Documentation
*
* All async methods (except for streams) will return a Promise in the event
* that a callback is omitted.
*/
promisifyAll(Dataset, {
exclude: ['table'],
});
/**
* Reference to the {@link Dataset} class.
* @name module:@google-cloud/bigquery.Dataset
* @see Dataset
*/
export {Dataset};