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 getModelsStream(options) {
46 // placeholder body, overwritten in constructor
47 return new paginator_1.ResourceStream({}, () => { });
48 }
49 getRoutinesStream(options) {
50 // placeholder body, overwritten in constructor
51 return new paginator_1.ResourceStream({}, () => { });
52 }
53 getTablesStream(options) {
54 // placeholder body, overwritten in constructor
55 return new paginator_1.ResourceStream({}, () => { });
56 }
57 constructor(bigQuery, id, options) {
58 const methods = {
59 /**
60 * @callback CreateDatasetCallback
61 * @param {?Error} err Request error, if any.
62 * @param {Dataset} dataset The newly created dataset.
63 * @param {object} apiResponse The full API response.
64 */
65 /**
66 * @typedef {array} CreateDatasetResponse
67 * @property {Dataset} 0 The newly created dataset.
68 * @property {object} 1 The full API response body.
69 */
70 /**
71 * Create a dataset.
72 *
73 * @method Dataset#create
74 * @param {CreateDatasetCallback} [callback] The callback function.
75 * @param {?error} callback.err An error returned while making this
76 * request.
77 * @param {Dataset} callback.dataset The newly created dataset.
78 * @param {object} callback.apiResponse The full API response.
79 * @returns {Promise<CreateDatasetResponse>}
80 *
81 * @example
82 * ```
83 * const {BigQuery} = require('@google-cloud/bigquery');
84 * const bigquery = new BigQuery();
85 * const dataset = bigquery.dataset('institutions');
86 * dataset.create((err, dataset, apiResponse) => {
87 * if (!err) {
88 * // The dataset was created successfully.
89 * }
90 * });
91 *
92 * //-
93 * // If the callback is omitted, we'll return a Promise.
94 * //-
95 * dataset.create().then((data) => {
96 * const dataset = data[0];
97 * const apiResponse = data[1];
98 * });
99 * ```
100 */
101 create: true,
102 /**
103 * @callback DatasetExistsCallback
104 * @param {?Error} err Request error, if any.
105 * @param {boolean} exists Indicates if the dataset exists.
106 */
107 /**
108 * @typedef {array} DatasetExistsResponse
109 * @property {boolean} 0 Indicates if the dataset exists.
110 */
111 /**
112 * Check if the dataset exists.
113 *
114 * @method Dataset#exists
115 * @param {DatasetExistsCallback} [callback] The callback function.
116 * @param {?error} callback.err An error returned while making this
117 * request.
118 * @param {boolean} callback.exists Whether the dataset exists or not.
119 * @returns {Promise<DatasetExistsResponse>}
120 *
121 * @example
122 * ```
123 * const {BigQuery} = require('@google-cloud/bigquery');
124 * const bigquery = new BigQuery();
125 * const dataset = bigquery.dataset('institutions');
126 * dataset.exists((err, exists) => {});
127 *
128 * //-
129 * // If the callback is omitted, we'll return a Promise.
130 * //-
131 * dataset.exists().then((data) => {
132 * const exists = data[0];
133 * });
134 * ```
135 */
136 exists: true,
137 /**
138 * @callback GetDatasetCallback
139 * @param {?Error} err Request error, if any.
140 * @param {Dataset} dataset The dataset.
141 * @param {object} apiResponse The full API response body.
142 */
143 /**
144 * @typedef {array} GetDatasetResponse
145 * @property {Dataset} 0 The dataset.
146 * @property {object} 1 The full API response body.
147 */
148 /**
149 * Get a dataset if it exists.
150 *
151 * You may optionally use this to "get or create" an object by providing
152 * an object with `autoCreate` set to `true`. Any extra configuration that
153 * is normally required for the `create` method must be contained within
154 * this object as well.
155 *
156 * @method Dataset#get
157 * @param {options} [options] Configuration object.
158 * @param {boolean} [options.autoCreate=false] Automatically create the
159 * object if it does not exist.
160 * @param {GetDatasetCallback} [callback] The callback function.
161 * @param {?error} callback.err An error returned while making this
162 * request.
163 * @param {Dataset} callback.dataset The dataset.
164 * @param {object} callback.apiResponse The full API response.
165 * @returns {Promise<GetDatasetResponse>}
166 *
167 * @example
168 * ```
169 * const {BigQuery} = require('@google-cloud/bigquery');
170 * const bigquery = new BigQuery();
171 * const dataset = bigquery.dataset('institutions');
172 * dataset.get((err, dataset, apiResponse) => {
173 * if (!err) {
174 * // `dataset.metadata` has been populated.
175 * }
176 * });
177 *
178 * //-
179 * // If the callback is omitted, we'll return a Promise.
180 * //-
181 * dataset.get().then((data) => {
182 * const dataset = data[0];
183 * const apiResponse = data[1];
184 * });
185 * ```
186 */
187 get: true,
188 /**
189 * @callback GetDatasetMetadataCallback
190 * @param {?Error} err Request error, if any.
191 * @param {object} metadata The dataset metadata.
192 * @param {object} apiResponse The full API response.
193 */
194 /**
195 * @typedef {array} GetDatasetMetadataResponse
196 * @property {object} 0 The dataset metadata.
197 * @property {object} 1 The full API response.
198 */
199 /**
200 * Get the metadata for the Dataset.
201 *
202 * See {@link https://cloud.google.com/bigquery/docs/reference/v2/datasets/get| Datasets: get API Documentation}
203 *
204 * @method Dataset#getMetadata
205 * @param {GetDatasetMetadataCallback} [callback] The callback function.
206 * @param {?error} callback.err An error returned while making this
207 * request.
208 * @param {object} callback.metadata The dataset's metadata.
209 * @param {object} callback.apiResponse The full API response.
210 * @returns {Promise<GetDatasetMetadataResponse>}
211 *
212 * @example
213 * ```
214 * const {BigQuery} = require('@google-cloud/bigquery');
215 * const bigquery = new BigQuery();
216 * const dataset = bigquery.dataset('institutions');
217 * dataset.getMetadata((err, metadata, apiResponse) => {});
218 *
219 * //-
220 * // If the callback is omitted, we'll return a Promise.
221 * //-
222 * dataset.getMetadata().then((data) => {
223 * const metadata = data[0];
224 * const apiResponse = data[1];
225 * });
226 * ```
227 */
228 getMetadata: true,
229 /**
230 * @callback SetDatasetMetadataCallback
231 * @param {?Error} err Request error, if any.
232 * @param {object} apiResponse The full API response.
233 */
234 /**
235 * @typedef {array} SetDatasetMetadataResponse
236 * @property {object} 0 The full API response.
237 */
238 /**
239 * Sets the metadata of the Dataset object.
240 *
241 * See {@link https://cloud.google.com/bigquery/docs/reference/v2/datasets/patch| Datasets: patch API Documentation}
242 *
243 * @method Dataset#setMetadata
244 * @param {object} metadata Metadata to save on the Dataset.
245 * @param {SetDatasetMetadataCallback} [callback] The callback function.
246 * @param {?error} callback.err An error returned while making this
247 * request.
248 * @param {object} callback.apiResponse The full API response.
249 * @returns {Promise<SetDatasetMetadataResponse>}
250 *
251 * @example
252 * ```
253 * const {BigQuery} = require('@google-cloud/bigquery');
254 * const bigquery = new BigQuery();
255 * const dataset = bigquery.dataset('institutions');
256 *
257 * const metadata = {
258 * description: 'Info for every institution in the 2013 IPEDS universe'
259 * };
260 *
261 * dataset.setMetadata(metadata, (err, apiResponse) => {});
262 *
263 * //-
264 * // If the callback is omitted, we'll return a Promise.
265 * //-
266 * dataset.setMetadata(metadata).then((data) => {
267 * const apiResponse = data[0];
268 * });
269 * ```
270 */
271 setMetadata: true,
272 };
273 super({
274 parent: bigQuery,
275 baseUrl: '/datasets',
276 id,
277 methods,
278 createMethod: (id, optionsOrCallback, cb) => {
279 let options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
280 const callback = typeof optionsOrCallback === 'function'
281 ? optionsOrCallback
282 : cb;
283 options = extend({}, options, { location: this.location });
284 return bigQuery.createDataset(id, options, callback);
285 },
286 });
287 if (options && options.location) {
288 this.location = options.location;
289 }
290 if (options === null || options === void 0 ? void 0 : options.projectId) {
291 this.projectId = options.projectId;
292 }
293 this.bigQuery = bigQuery;
294 // Catch all for read-modify-write cycle
295 // https://cloud.google.com/bigquery/docs/api-performance#read-patch-write
296 this.interceptors.push({
297 request: (reqOpts) => {
298 if (reqOpts.method === 'PATCH' && reqOpts.json.etag) {
299 reqOpts.headers = reqOpts.headers || {};
300 reqOpts.headers['If-Match'] = reqOpts.json.etag;
301 }
302 if (this.projectId) {
303 // Override projectId if provided
304 reqOpts.uri = reqOpts.uri.replace(`/projects/${this.bigQuery.projectId}/`, `/projects/${this.projectId}/`);
305 }
306 return reqOpts;
307 },
308 });
309 /**
310 * List all or some of the {@link Model} objects in your project
311 * as a readable object stream.
312 *
313 * @method Dataset#getModelsStream
314 * @param {object} [options] Configuration object. See
315 * {@link Dataset#getModels} for a complete list of options.
316 * @return {stream}
317 *
318 * @example
319 * ```
320 * const {BigQuery} = require('@google-cloud/bigquery');
321 * const bigquery = new BigQuery();
322 * const dataset = bigquery.dataset('institutions');
323 *
324 * dataset.getModelsStream()
325 * .on('error', console.error)
326 * .on('data', (model) => {})
327 * .on('end', () => {
328 * // All models have been retrieved
329 * });
330 *
331 * ```
332 * @example If you anticipate many results, you can end a stream early to prevent unnecessary processing and API requests.
333 * ```
334 * dataset.getModelsStream()
335 * .on('data', function(model) {
336 * this.end();
337 * });
338 * ```
339 */
340 this.getModelsStream = paginator_1.paginator.streamify('getModels');
341 /**
342 * List all or some of the {@link Routine} objects in your project as a
343 * readable object stream.
344 *
345 * @method Dataset#getRoutinesStream
346 * @param {GetRoutinesOptions} [options] Configuration object.
347 * @returns {stream}
348 *
349 * @example
350 * ```
351 * const {BigQuery} = require('@google-cloud/bigquery');
352 * const bigquery = new BigQuery();
353 * const dataset = bigquery.dataset('institutions');
354 *
355 * dataset.getRoutinesStream()
356 * .on('error', console.error)
357 * .on('data', (routine) => {})
358 * .on('end', () => {
359 * // All routines have been retrieved
360 * });
361 *
362 * ```
363 * @example If you anticipate many results, you can end a stream early to prevent unnecessary processing and API requests.
364 * ```
365 * dataset.getRoutinesStream()
366 * .on('data', function(routine) {
367 * this.end();
368 * });
369 * ```
370 */
371 this.getRoutinesStream = paginator_1.paginator.streamify('getRoutines');
372 /**
373 * List all or some of the {@link Table} objects in your project
374 * as a readable object stream.
375 *
376 * @method Dataset#getTablesStream
377 * @param {object} [options] Configuration object. See
378 * {@link Dataset#getTables} for a complete list of options.
379 * @return {stream}
380 *
381 * @example
382 * ```
383 * const {BigQuery} = require('@google-cloud/bigquery');
384 * const bigquery = new BigQuery();
385 * const dataset = bigquery.dataset('institutions');
386 *
387 * dataset.getTablesStream()
388 * .on('error', console.error)
389 * .on('data', (table) => {})
390 * .on('end', () => {
391 * // All tables have been retrieved
392 * });
393 *
394 * //-
395 * // If you anticipate many results, you can end a stream early to prevent
396 * // unnecessary processing and API requests.
397 * //-
398 * dataset.getTablesStream()
399 * .on('data', function(table) {
400 * this.end();
401 * });
402 * ```
403 */
404 this.getTablesStream = paginator_1.paginator.streamify('getTables');
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