UNPKG

26 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 this.bigQuery = bigQuery;
300 // Catch all for read-modify-write cycle
301 // https://cloud.google.com/bigquery/docs/api-performance#read-patch-write
302 this.interceptors.push({
303 request: (reqOpts) => {
304 if (reqOpts.method === 'PATCH' && reqOpts.json.etag) {
305 reqOpts.headers = reqOpts.headers || {};
306 reqOpts.headers['If-Match'] = reqOpts.json.etag;
307 }
308 if (this.projectId) {
309 // Override projectId if provided
310 reqOpts.uri = reqOpts.uri.replace(`/projects/${this.bigQuery.projectId}/`, `/projects/${this.projectId}/`);
311 }
312 return reqOpts;
313 },
314 });
315 /**
316 * List all or some of the {@link Model} objects in your project
317 * as a readable object stream.
318 *
319 * @method Dataset#getModelsStream
320 * @param {object} [options] Configuration object. See
321 * {@link Dataset#getModels} for a complete list of options.
322 * @return {stream}
323 *
324 * @example
325 * ```
326 * const {BigQuery} = require('@google-cloud/bigquery');
327 * const bigquery = new BigQuery();
328 * const dataset = bigquery.dataset('institutions');
329 *
330 * dataset.getModelsStream()
331 * .on('error', console.error)
332 * .on('data', (model) => {})
333 * .on('end', () => {
334 * // All models have been retrieved
335 * });
336 *
337 * ```
338 * @example If you anticipate many results, you can end a stream early to prevent unnecessary processing and API requests.
339 * ```
340 * dataset.getModelsStream()
341 * .on('data', function(model) {
342 * this.end();
343 * });
344 * ```
345 */
346 this.getModelsStream = paginator_1.paginator.streamify('getModels');
347 /**
348 * List all or some of the {@link Routine} objects in your project as a
349 * readable object stream.
350 *
351 * @method Dataset#getRoutinesStream
352 * @param {GetRoutinesOptions} [options] Configuration object.
353 * @returns {stream}
354 *
355 * @example
356 * ```
357 * const {BigQuery} = require('@google-cloud/bigquery');
358 * const bigquery = new BigQuery();
359 * const dataset = bigquery.dataset('institutions');
360 *
361 * dataset.getRoutinesStream()
362 * .on('error', console.error)
363 * .on('data', (routine) => {})
364 * .on('end', () => {
365 * // All routines have been retrieved
366 * });
367 *
368 * ```
369 * @example If you anticipate many results, you can end a stream early to prevent unnecessary processing and API requests.
370 * ```
371 * dataset.getRoutinesStream()
372 * .on('data', function(routine) {
373 * this.end();
374 * });
375 * ```
376 */
377 this.getRoutinesStream = paginator_1.paginator.streamify('getRoutines');
378 /**
379 * List all or some of the {@link Table} objects in your project
380 * as a readable object stream.
381 *
382 * @method Dataset#getTablesStream
383 * @param {object} [options] Configuration object. See
384 * {@link Dataset#getTables} for a complete list of options.
385 * @return {stream}
386 *
387 * @example
388 * ```
389 * const {BigQuery} = require('@google-cloud/bigquery');
390 * const bigquery = new BigQuery();
391 * const dataset = bigquery.dataset('institutions');
392 *
393 * dataset.getTablesStream()
394 * .on('error', console.error)
395 * .on('data', (table) => {})
396 * .on('end', () => {
397 * // All tables have been retrieved
398 * });
399 *
400 * //-
401 * // If you anticipate many results, you can end a stream early to prevent
402 * // unnecessary processing and API requests.
403 * //-
404 * dataset.getTablesStream()
405 * .on('data', function(table) {
406 * this.end();
407 * });
408 * ```
409 */
410 this.getTablesStream = paginator_1.paginator.streamify('getTables');
411 }
412 createQueryJob(options, callback) {
413 if (typeof options === 'string') {
414 options = {
415 query: options,
416 };
417 }
418 options = extend(true, {}, options, {
419 defaultDataset: {
420 datasetId: this.id,
421 },
422 location: this.location,
423 });
424 return this.bigQuery.createQueryJob(options, callback);
425 }
426 /**
427 * Run a query scoped to your dataset as a readable object stream.
428 *
429 * See {@link BigQuery#createQueryStream} for full documentation of this
430 * method.
431 *
432 * @param {object} options See {@link BigQuery#createQueryStream} for full
433 * documentation of this method.
434 * @returns {stream}
435 */
436 createQueryStream(options) {
437 if (typeof options === 'string') {
438 options = {
439 query: options,
440 };
441 }
442 options = extend(true, {}, options, {
443 defaultDataset: {
444 datasetId: this.id,
445 },
446 location: this.location,
447 });
448 return this.bigQuery.createQueryStream(options);
449 }
450 createRoutine(id, config, callback) {
451 const json = Object.assign({}, config, {
452 routineReference: {
453 routineId: id,
454 datasetId: this.id,
455 projectId: this.bigQuery.projectId,
456 },
457 });
458 this.request({
459 method: 'POST',
460 uri: '/routines',
461 json,
462 }, (err, resp) => {
463 if (err) {
464 callback(err, null, resp);
465 return;
466 }
467 const routine = this.routine(resp.routineReference.routineId);
468 routine.metadata = resp;
469 callback(null, routine, resp);
470 });
471 }
472 createTable(id, optionsOrCallback, cb) {
473 const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
474 const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb;
475 const body = table_1.Table.formatMetadata_(options);
476 // eslint-disable-next-line @typescript-eslint/no-explicit-any
477 body.tableReference = {
478 datasetId: this.id,
479 projectId: this.bigQuery.projectId,
480 tableId: id,
481 };
482 this.request({
483 method: 'POST',
484 uri: '/tables',
485 json: body,
486 }, (err, resp) => {
487 if (err) {
488 callback(err, null, resp);
489 return;
490 }
491 const table = this.table(resp.tableReference.tableId, {
492 location: resp.location,
493 });
494 table.metadata = resp;
495 callback(null, table, resp);
496 });
497 }
498 delete(optionsOrCallback, callback) {
499 const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
500 callback =
501 typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
502 const query = {
503 deleteContents: !!options.force,
504 };
505 this.request({
506 method: 'DELETE',
507 uri: '',
508 qs: query,
509 }, callback);
510 }
511 getModels(optsOrCb, cb) {
512 const options = typeof optsOrCb === 'object' ? optsOrCb : {};
513 const callback = typeof optsOrCb === 'function' ? optsOrCb : cb;
514 this.request({
515 uri: '/models',
516 qs: options,
517 }, (err, resp) => {
518 if (err) {
519 callback(err, null, null, resp);
520 return;
521 }
522 let nextQuery = null;
523 if (resp.nextPageToken) {
524 nextQuery = Object.assign({}, options, {
525 pageToken: resp.nextPageToken,
526 });
527 }
528 const models = (resp.models || []).map(modelObject => {
529 const model = this.model(modelObject.modelReference.modelId);
530 model.metadata = modelObject;
531 return model;
532 });
533 callback(null, models, nextQuery, resp);
534 });
535 }
536 getRoutines(optsOrCb, cb) {
537 const options = typeof optsOrCb === 'object' ? optsOrCb : {};
538 const callback = typeof optsOrCb === 'function' ? optsOrCb : cb;
539 this.request({
540 uri: '/routines',
541 qs: options,
542 }, (err, resp) => {
543 if (err) {
544 callback(err, null, null, resp);
545 return;
546 }
547 let nextQuery = null;
548 if (resp.nextPageToken) {
549 nextQuery = Object.assign({}, options, {
550 pageToken: resp.nextPageToken,
551 });
552 }
553 const routines = (resp.routines || []).map(metadata => {
554 const routine = this.routine(metadata.routineReference.routineId);
555 routine.metadata = metadata;
556 return routine;
557 });
558 callback(null, routines, nextQuery, resp);
559 });
560 }
561 getTables(optionsOrCallback, cb) {
562 const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
563 const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb;
564 this.request({
565 uri: '/tables',
566 qs: options,
567 }, (err, resp) => {
568 if (err) {
569 callback(err, null, null, resp);
570 return;
571 }
572 let nextQuery = null;
573 if (resp.nextPageToken) {
574 nextQuery = Object.assign({}, options, {
575 pageToken: resp.nextPageToken,
576 });
577 }
578 // eslint-disable-next-line @typescript-eslint/no-explicit-any
579 const tables = (resp.tables || []).map((tableObject) => {
580 const table = this.table(tableObject.tableReference.tableId, {
581 location: tableObject.location,
582 });
583 table.metadata = tableObject;
584 return table;
585 });
586 callback(null, tables, nextQuery, resp);
587 });
588 }
589 /**
590 * Create a {@link Model} object.
591 *
592 * @throws {TypeError} if model ID is missing.
593 *
594 * @param {string} id The ID of the model.
595 * @return {Model}
596 *
597 * @example
598 * ```
599 * const {BigQuery} = require('@google-cloud/bigquery');
600 * const bigquery = new BigQuery();
601 * const dataset = bigquery.dataset('institutions');
602 *
603 * const model = dataset.model('my-model');
604 * ```
605 */
606 model(id) {
607 if (typeof id !== 'string') {
608 throw new TypeError('A model ID is required.');
609 }
610 return new model_1.Model(this, id);
611 }
612 query(options, callback) {
613 if (typeof options === 'string') {
614 options = {
615 query: options,
616 };
617 }
618 options = extend(true, {}, options, {
619 defaultDataset: {
620 datasetId: this.id,
621 },
622 location: this.location,
623 });
624 return this.bigQuery.query(options, callback);
625 }
626 /**
627 * Create a {@link Routine} object.
628 *
629 * @throws {TypeError} if routine ID is missing.
630 *
631 * @param {string} id The ID of the routine.
632 * @returns {Routine}
633 *
634 * @example
635 * ```
636 * const {BigQuery} = require('@google-cloud/bigquery');
637 * const bigquery = new BigQuery();
638 * const dataset = bigquery.dataset('institutions');
639 *
640 * const routine = dataset.routine('my_routine');
641 * ```
642 */
643 routine(id) {
644 if (typeof id !== 'string') {
645 throw new TypeError('A routine ID is required.');
646 }
647 return new routine_1.Routine(this, id);
648 }
649 /**
650 * Create a {@link Table} object.
651 *
652 * @throws {TypeError} if table ID is missing.
653 *
654 * @param {string} id The ID of the table.
655 * @param {object} [options] Table options.
656 * @param {string} [options.location] The geographic location of the table, by
657 * default this value is inherited from the dataset. This can be used to
658 * configure the location of all jobs created through a table instance.
659 * It cannot be used to set the actual location of the table. This value will
660 * be superseded by any API responses containing location data for the
661 * table.
662 * @return {Table}
663 *
664 * @example
665 * ```
666 * const {BigQuery} = require('@google-cloud/bigquery');
667 * const bigquery = new BigQuery();
668 * const dataset = bigquery.dataset('institutions');
669 *
670 * const institutions = dataset.table('institution_data');
671 * ```
672 */
673 table(id, options) {
674 if (typeof id !== 'string') {
675 throw new TypeError('A table ID is required.');
676 }
677 options = extend({
678 location: this.location,
679 }, options);
680 return new table_1.Table(this, id, options);
681 }
682}
683exports.Dataset = Dataset;
684/*! Developer Documentation
685 *
686 * These methods can be auto-paginated.
687 */
688paginator_1.paginator.extend(Dataset, ['getModels', 'getRoutines', 'getTables']);
689/*! Developer Documentation
690 *
691 * All async methods (except for streams) will return a Promise in the event
692 * that a callback is omitted.
693 */
694(0, promisify_1.promisifyAll)(Dataset, {
695 exclude: ['model', 'routine', 'table'],
696});
697//# sourceMappingURL=dataset.js.map
\No newline at end of file