UNPKG

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