UNPKG

25.8 kBJavaScriptView Raw
1"use strict";
2/*!
3 * Copyright 2014 Google Inc. All Rights Reserved.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17Object.defineProperty(exports, "__esModule", { value: true });
18exports.Dataset = void 0;
19const common_1 = require("@google-cloud/common");
20const paginator_1 = require("@google-cloud/paginator");
21const promisify_1 = require("@google-cloud/promisify");
22const extend = require("extend");
23const table_1 = require("./table");
24const model_1 = require("./model");
25const routine_1 = require("./routine");
26/**
27 * Interact with your BigQuery dataset. Create a Dataset instance with
28 * {@link BigQuery#createDataset} or {@link BigQuery#dataset}.
29 *
30 * @class
31 * @param {BigQuery} bigQuery {@link BigQuery} instance.
32 * @param {string} id The ID of the Dataset.
33 * @param {object} [options] Dataset options.
34 * @param {string} [options.location] The geographic location of the dataset.
35 * Defaults to US.
36 *
37 * @example
38 * ```
39 * const {BigQuery} = require('@google-cloud/bigquery');
40 * const bigquery = new BigQuery();
41 * const dataset = bigquery.dataset('institutions');
42 * ```
43 */
44class Dataset extends common_1.ServiceObject {
45 constructor(bigQuery, id, options) {
46 const methods = {
47 /**
48 * @callback CreateDatasetCallback
49 * @param {?Error} err Request error, if any.
50 * @param {Dataset} dataset The newly created dataset.
51 * @param {object} apiResponse The full API response.
52 */
53 /**
54 * @typedef {array} CreateDatasetResponse
55 * @property {Dataset} 0 The newly created dataset.
56 * @property {object} 1 The full API response body.
57 */
58 /**
59 * Create a dataset.
60 *
61 * @method Dataset#create
62 * @param {CreateDatasetCallback} [callback] The callback function.
63 * @param {?error} callback.err An error returned while making this
64 * request.
65 * @param {Dataset} callback.dataset The newly created dataset.
66 * @param {object} callback.apiResponse The full API response.
67 * @returns {Promise<CreateDatasetResponse>}
68 *
69 * @example
70 * ```
71 * const {BigQuery} = require('@google-cloud/bigquery');
72 * const bigquery = new BigQuery();
73 * const dataset = bigquery.dataset('institutions');
74 * dataset.create((err, dataset, apiResponse) => {
75 * if (!err) {
76 * // The dataset was created successfully.
77 * }
78 * });
79 *
80 * //-
81 * // If the callback is omitted, we'll return a Promise.
82 * //-
83 * dataset.create().then((data) => {
84 * const dataset = data[0];
85 * const apiResponse = data[1];
86 * });
87 * ```
88 */
89 create: true,
90 /**
91 * @callback DatasetExistsCallback
92 * @param {?Error} err Request error, if any.
93 * @param {boolean} exists Indicates if the dataset exists.
94 */
95 /**
96 * @typedef {array} DatasetExistsResponse
97 * @property {boolean} 0 Indicates if the dataset exists.
98 */
99 /**
100 * Check if the dataset exists.
101 *
102 * @method Dataset#exists
103 * @param {DatasetExistsCallback} [callback] The callback function.
104 * @param {?error} callback.err An error returned while making this
105 * request.
106 * @param {boolean} callback.exists Whether the dataset exists or not.
107 * @returns {Promise<DatasetExistsResponse>}
108 *
109 * @example
110 * ```
111 * const {BigQuery} = require('@google-cloud/bigquery');
112 * const bigquery = new BigQuery();
113 * const dataset = bigquery.dataset('institutions');
114 * dataset.exists((err, exists) => {});
115 *
116 * //-
117 * // If the callback is omitted, we'll return a Promise.
118 * //-
119 * dataset.exists().then((data) => {
120 * const exists = data[0];
121 * });
122 * ```
123 */
124 exists: true,
125 /**
126 * @callback GetDatasetCallback
127 * @param {?Error} err Request error, if any.
128 * @param {Dataset} dataset The dataset.
129 * @param {object} apiResponse The full API response body.
130 */
131 /**
132 * @typedef {array} GetDatasetResponse
133 * @property {Dataset} 0 The dataset.
134 * @property {object} 1 The full API response body.
135 */
136 /**
137 * Get a dataset if it exists.
138 *
139 * You may optionally use this to "get or create" an object by providing
140 * an object with `autoCreate` set to `true`. Any extra configuration that
141 * is normally required for the `create` method must be contained within
142 * this object as well.
143 *
144 * @method Dataset#get
145 * @param {options} [options] Configuration object.
146 * @param {boolean} [options.autoCreate=false] Automatically create the
147 * object if it does not exist.
148 * @param {GetDatasetCallback} [callback] The callback function.
149 * @param {?error} callback.err An error returned while making this
150 * request.
151 * @param {Dataset} callback.dataset The dataset.
152 * @param {object} callback.apiResponse The full API response.
153 * @returns {Promise<GetDatasetResponse>}
154 *
155 * @example
156 * ```
157 * const {BigQuery} = require('@google-cloud/bigquery');
158 * const bigquery = new BigQuery();
159 * const dataset = bigquery.dataset('institutions');
160 * dataset.get((err, dataset, apiResponse) => {
161 * if (!err) {
162 * // `dataset.metadata` has been populated.
163 * }
164 * });
165 *
166 * //-
167 * // If the callback is omitted, we'll return a Promise.
168 * //-
169 * dataset.get().then((data) => {
170 * const dataset = data[0];
171 * const apiResponse = data[1];
172 * });
173 * ```
174 */
175 get: true,
176 /**
177 * @callback GetDatasetMetadataCallback
178 * @param {?Error} err Request error, if any.
179 * @param {object} metadata The dataset metadata.
180 * @param {object} apiResponse The full API response.
181 */
182 /**
183 * @typedef {array} GetDatasetMetadataResponse
184 * @property {object} 0 The dataset metadata.
185 * @property {object} 1 The full API response.
186 */
187 /**
188 * Get the metadata for the Dataset.
189 *
190 * See {@link https://cloud.google.com/bigquery/docs/reference/v2/datasets/get| Datasets: get API Documentation}
191 *
192 * @method Dataset#getMetadata
193 * @param {GetDatasetMetadataCallback} [callback] The callback function.
194 * @param {?error} callback.err An error returned while making this
195 * request.
196 * @param {object} callback.metadata The dataset's metadata.
197 * @param {object} callback.apiResponse The full API response.
198 * @returns {Promise<GetDatasetMetadataResponse>}
199 *
200 * @example
201 * ```
202 * const {BigQuery} = require('@google-cloud/bigquery');
203 * const bigquery = new BigQuery();
204 * const dataset = bigquery.dataset('institutions');
205 * dataset.getMetadata((err, metadata, apiResponse) => {});
206 *
207 * //-
208 * // If the callback is omitted, we'll return a Promise.
209 * //-
210 * dataset.getMetadata().then((data) => {
211 * const metadata = data[0];
212 * const apiResponse = data[1];
213 * });
214 * ```
215 */
216 getMetadata: true,
217 /**
218 * @callback SetDatasetMetadataCallback
219 * @param {?Error} err Request error, if any.
220 * @param {object} apiResponse The full API response.
221 */
222 /**
223 * @typedef {array} SetDatasetMetadataResponse
224 * @property {object} 0 The full API response.
225 */
226 /**
227 * Sets the metadata of the Dataset object.
228 *
229 * See {@link https://cloud.google.com/bigquery/docs/reference/v2/datasets/patch| Datasets: patch API Documentation}
230 *
231 * @method Dataset#setMetadata
232 * @param {object} metadata Metadata to save on the Dataset.
233 * @param {SetDatasetMetadataCallback} [callback] The callback function.
234 * @param {?error} callback.err An error returned while making this
235 * request.
236 * @param {object} callback.apiResponse The full API response.
237 * @returns {Promise<SetDatasetMetadataResponse>}
238 *
239 * @example
240 * ```
241 * const {BigQuery} = require('@google-cloud/bigquery');
242 * const bigquery = new BigQuery();
243 * const dataset = bigquery.dataset('institutions');
244 *
245 * const metadata = {
246 * description: 'Info for every institution in the 2013 IPEDS universe'
247 * };
248 *
249 * dataset.setMetadata(metadata, (err, apiResponse) => {});
250 *
251 * //-
252 * // If the callback is omitted, we'll return a Promise.
253 * //-
254 * dataset.setMetadata(metadata).then((data) => {
255 * const apiResponse = data[0];
256 * });
257 * ```
258 */
259 setMetadata: true,
260 };
261 super({
262 parent: bigQuery,
263 baseUrl: '/datasets',
264 id,
265 methods,
266 createMethod: (id, optionsOrCallback, cb) => {
267 let options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
268 const callback = typeof optionsOrCallback === 'function'
269 ? optionsOrCallback
270 : cb;
271 options = extend({}, options, { location: this.location });
272 return bigQuery.createDataset(id, options, callback);
273 },
274 });
275 if (options && options.location) {
276 this.location = options.location;
277 }
278 if (options === null || options === void 0 ? void 0 : options.projectId) {
279 this.projectId = options.projectId;
280 }
281 this.bigQuery = bigQuery;
282 // Catch all for read-modify-write cycle
283 // https://cloud.google.com/bigquery/docs/api-performance#read-patch-write
284 this.interceptors.push({
285 request: (reqOpts) => {
286 if (reqOpts.method === 'PATCH' && reqOpts.json.etag) {
287 reqOpts.headers = reqOpts.headers || {};
288 reqOpts.headers['If-Match'] = reqOpts.json.etag;
289 }
290 if (this.projectId) {
291 // Override projectId if provided
292 reqOpts.uri = reqOpts.uri.replace(`/projects/${this.bigQuery.projectId}/`, `/projects/${this.projectId}/`);
293 }
294 return reqOpts;
295 },
296 });
297 /**
298 * List all or some of the {@link Model} objects in your project
299 * as a readable object stream.
300 *
301 * @method Dataset#getModelsStream
302 * @param {object} [options] Configuration object. See
303 * {@link Dataset#getModels} for a complete list of options.
304 * @return {stream}
305 *
306 * @example
307 * ```
308 * const {BigQuery} = require('@google-cloud/bigquery');
309 * const bigquery = new BigQuery();
310 * const dataset = bigquery.dataset('institutions');
311 *
312 * dataset.getModelsStream()
313 * .on('error', console.error)
314 * .on('data', (model) => {})
315 * .on('end', () => {
316 * // All models have been retrieved
317 * });
318 *
319 * ```
320 * @example If you anticipate many results, you can end a stream early to prevent unnecessary processing and API requests.
321 * ```
322 * dataset.getModelsStream()
323 * .on('data', function(model) {
324 * this.end();
325 * });
326 * ```
327 */
328 this.getModelsStream = paginator_1.paginator.streamify('getModels');
329 /**
330 * List all or some of the {@link Routine} objects in your project as a
331 * readable object stream.
332 *
333 * @method Dataset#getRoutinesStream
334 * @param {GetRoutinesOptions} [options] Configuration object.
335 * @returns {stream}
336 *
337 * @example
338 * ```
339 * const {BigQuery} = require('@google-cloud/bigquery');
340 * const bigquery = new BigQuery();
341 * const dataset = bigquery.dataset('institutions');
342 *
343 * dataset.getRoutinesStream()
344 * .on('error', console.error)
345 * .on('data', (routine) => {})
346 * .on('end', () => {
347 * // All routines have been retrieved
348 * });
349 *
350 * ```
351 * @example If you anticipate many results, you can end a stream early to prevent unnecessary processing and API requests.
352 * ```
353 * dataset.getRoutinesStream()
354 * .on('data', function(routine) {
355 * this.end();
356 * });
357 * ```
358 */
359 this.getRoutinesStream = paginator_1.paginator.streamify('getRoutines');
360 /**
361 * List all or some of the {@link Table} objects in your project
362 * as a readable object stream.
363 *
364 * @method Dataset#getTablesStream
365 * @param {object} [options] Configuration object. See
366 * {@link Dataset#getTables} for a complete list of options.
367 * @return {stream}
368 *
369 * @example
370 * ```
371 * const {BigQuery} = require('@google-cloud/bigquery');
372 * const bigquery = new BigQuery();
373 * const dataset = bigquery.dataset('institutions');
374 *
375 * dataset.getTablesStream()
376 * .on('error', console.error)
377 * .on('data', (table) => {})
378 * .on('end', () => {
379 * // All tables have been retrieved
380 * });
381 *
382 * //-
383 * // If you anticipate many results, you can end a stream early to prevent
384 * // unnecessary processing and API requests.
385 * //-
386 * dataset.getTablesStream()
387 * .on('data', function(table) {
388 * this.end();
389 * });
390 * ```
391 */
392 this.getTablesStream = paginator_1.paginator.streamify('getTables');
393 }
394 getModelsStream(options) {
395 // placeholder body, overwritten in constructor
396 return new paginator_1.ResourceStream({}, () => { });
397 }
398 getRoutinesStream(options) {
399 // placeholder body, overwritten in constructor
400 return new paginator_1.ResourceStream({}, () => { });
401 }
402 getTablesStream(options) {
403 // placeholder body, overwritten in constructor
404 return new paginator_1.ResourceStream({}, () => { });
405 }
406 createQueryJob(options, callback) {
407 if (typeof options === 'string') {
408 options = {
409 query: options,
410 };
411 }
412 options = extend(true, {}, options, {
413 defaultDataset: {
414 datasetId: this.id,
415 },
416 location: this.location,
417 });
418 return this.bigQuery.createQueryJob(options, callback);
419 }
420 /**
421 * Run a query scoped to your dataset as a readable object stream.
422 *
423 * See {@link BigQuery#createQueryStream} for full documentation of this
424 * method.
425 *
426 * @param {object} options See {@link BigQuery#createQueryStream} for full
427 * documentation of this method.
428 * @returns {stream}
429 */
430 createQueryStream(options) {
431 if (typeof options === 'string') {
432 options = {
433 query: options,
434 };
435 }
436 options = extend(true, {}, options, {
437 defaultDataset: {
438 datasetId: this.id,
439 },
440 location: this.location,
441 });
442 return this.bigQuery.createQueryStream(options);
443 }
444 createRoutine(id, config, callback) {
445 const json = Object.assign({}, config, {
446 routineReference: {
447 routineId: id,
448 datasetId: this.id,
449 projectId: this.bigQuery.projectId,
450 },
451 });
452 this.request({
453 method: 'POST',
454 uri: '/routines',
455 json,
456 }, (err, resp) => {
457 if (err) {
458 callback(err, null, resp);
459 return;
460 }
461 const routine = this.routine(resp.routineReference.routineId);
462 routine.metadata = resp;
463 callback(null, routine, resp);
464 });
465 }
466 createTable(id, optionsOrCallback, cb) {
467 const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
468 const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb;
469 const body = table_1.Table.formatMetadata_(options);
470 // eslint-disable-next-line @typescript-eslint/no-explicit-any
471 body.tableReference = {
472 datasetId: this.id,
473 projectId: this.bigQuery.projectId,
474 tableId: id,
475 };
476 this.request({
477 method: 'POST',
478 uri: '/tables',
479 json: body,
480 }, (err, resp) => {
481 if (err) {
482 callback(err, null, resp);
483 return;
484 }
485 const table = this.table(resp.tableReference.tableId, {
486 location: resp.location,
487 });
488 table.metadata = resp;
489 callback(null, table, resp);
490 });
491 }
492 delete(optionsOrCallback, callback) {
493 const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
494 callback =
495 typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
496 const query = {
497 deleteContents: !!options.force,
498 };
499 this.request({
500 method: 'DELETE',
501 uri: '',
502 qs: query,
503 }, callback);
504 }
505 getModels(optsOrCb, cb) {
506 const options = typeof optsOrCb === 'object' ? optsOrCb : {};
507 const callback = typeof optsOrCb === 'function' ? optsOrCb : cb;
508 this.request({
509 uri: '/models',
510 qs: options,
511 }, (err, resp) => {
512 if (err) {
513 callback(err, null, null, resp);
514 return;
515 }
516 let nextQuery = null;
517 if (resp.nextPageToken) {
518 nextQuery = Object.assign({}, options, {
519 pageToken: resp.nextPageToken,
520 });
521 }
522 const models = (resp.models || []).map(modelObject => {
523 const model = this.model(modelObject.modelReference.modelId);
524 model.metadata = modelObject;
525 return model;
526 });
527 callback(null, models, nextQuery, resp);
528 });
529 }
530 getRoutines(optsOrCb, cb) {
531 const options = typeof optsOrCb === 'object' ? optsOrCb : {};
532 const callback = typeof optsOrCb === 'function' ? optsOrCb : cb;
533 this.request({
534 uri: '/routines',
535 qs: options,
536 }, (err, resp) => {
537 if (err) {
538 callback(err, null, null, resp);
539 return;
540 }
541 let nextQuery = null;
542 if (resp.nextPageToken) {
543 nextQuery = Object.assign({}, options, {
544 pageToken: resp.nextPageToken,
545 });
546 }
547 const routines = (resp.routines || []).map(metadata => {
548 const routine = this.routine(metadata.routineReference.routineId);
549 routine.metadata = metadata;
550 return routine;
551 });
552 callback(null, routines, nextQuery, resp);
553 });
554 }
555 getTables(optionsOrCallback, cb) {
556 const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
557 const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb;
558 this.request({
559 uri: '/tables',
560 qs: options,
561 }, (err, resp) => {
562 if (err) {
563 callback(err, null, null, resp);
564 return;
565 }
566 let nextQuery = null;
567 if (resp.nextPageToken) {
568 nextQuery = Object.assign({}, options, {
569 pageToken: resp.nextPageToken,
570 });
571 }
572 // eslint-disable-next-line @typescript-eslint/no-explicit-any
573 const tables = (resp.tables || []).map((tableObject) => {
574 const table = this.table(tableObject.tableReference.tableId, {
575 location: tableObject.location,
576 });
577 table.metadata = tableObject;
578 return table;
579 });
580 callback(null, tables, nextQuery, resp);
581 });
582 }
583 /**
584 * Create a {@link Model} object.
585 *
586 * @throws {TypeError} if model ID is missing.
587 *
588 * @param {string} id The ID of the model.
589 * @return {Model}
590 *
591 * @example
592 * ```
593 * const {BigQuery} = require('@google-cloud/bigquery');
594 * const bigquery = new BigQuery();
595 * const dataset = bigquery.dataset('institutions');
596 *
597 * const model = dataset.model('my-model');
598 * ```
599 */
600 model(id) {
601 if (typeof id !== 'string') {
602 throw new TypeError('A model ID is required.');
603 }
604 return new model_1.Model(this, id);
605 }
606 query(options, callback) {
607 if (typeof options === 'string') {
608 options = {
609 query: options,
610 };
611 }
612 options = extend(true, {}, options, {
613 defaultDataset: {
614 datasetId: this.id,
615 },
616 location: this.location,
617 });
618 return this.bigQuery.query(options, callback);
619 }
620 /**
621 * Create a {@link Routine} object.
622 *
623 * @throws {TypeError} if routine ID is missing.
624 *
625 * @param {string} id The ID of the routine.
626 * @returns {Routine}
627 *
628 * @example
629 * ```
630 * const {BigQuery} = require('@google-cloud/bigquery');
631 * const bigquery = new BigQuery();
632 * const dataset = bigquery.dataset('institutions');
633 *
634 * const routine = dataset.routine('my_routine');
635 * ```
636 */
637 routine(id) {
638 if (typeof id !== 'string') {
639 throw new TypeError('A routine ID is required.');
640 }
641 return new routine_1.Routine(this, id);
642 }
643 /**
644 * Create a {@link Table} object.
645 *
646 * @throws {TypeError} if table ID is missing.
647 *
648 * @param {string} id The ID of the table.
649 * @param {object} [options] Table options.
650 * @param {string} [options.location] The geographic location of the table, by
651 * default this value is inherited from the dataset. This can be used to
652 * configure the location of all jobs created through a table instance.
653 * It cannot be used to set the actual location of the table. This value will
654 * be superseded by any API responses containing location data for the
655 * table.
656 * @return {Table}
657 *
658 * @example
659 * ```
660 * const {BigQuery} = require('@google-cloud/bigquery');
661 * const bigquery = new BigQuery();
662 * const dataset = bigquery.dataset('institutions');
663 *
664 * const institutions = dataset.table('institution_data');
665 * ```
666 */
667 table(id, options) {
668 if (typeof id !== 'string') {
669 throw new TypeError('A table ID is required.');
670 }
671 options = extend({
672 location: this.location,
673 }, options);
674 return new table_1.Table(this, id, options);
675 }
676}
677exports.Dataset = Dataset;
678/*! Developer Documentation
679 *
680 * These methods can be auto-paginated.
681 */
682paginator_1.paginator.extend(Dataset, ['getModels', 'getRoutines', 'getTables']);
683/*! Developer Documentation
684 *
685 * All async methods (except for streams) will return a Promise in the event
686 * that a callback is omitted.
687 */
688(0, promisify_1.promisifyAll)(Dataset, {
689 exclude: ['model', 'routine', 'table'],
690});
691//# sourceMappingURL=dataset.js.map
\No newline at end of file