From 0490928431e32a830fe11055ad47793253cdbd7c Mon Sep 17 00:00:00 2001 From: Dave Gramlich Date: Tue, 21 May 2019 14:52:38 -0400 Subject: [PATCH 1/9] feat(model): dataset model support --- src/dataset.ts | 153 ++++++++++++++++++++++++++++++++++++++- src/model.ts | 189 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 341 insertions(+), 1 deletion(-) create mode 100644 src/model.ts diff --git a/src/dataset.ts b/src/dataset.ts index f3db4e877..3911e75ee 100644 --- a/src/dataset.ts +++ b/src/dataset.ts @@ -43,6 +43,7 @@ import { TableMetadata, TableOptions, } from './table'; +import {Model} from './model'; import bigquery from './types'; export interface DatasetDeleteOptions { @@ -55,6 +56,18 @@ export interface DatasetOptions { export type CreateDatasetOptions = bigquery.IDataset; +export type GetModelsOptions = PagedRequest; +export type GetModelsResponse = PagedRequest< + Model, + GetModelsOptions, + bigquery.IListModelsResponse +>; +export type GetModelsCallback = PagedCallback< + Model, + GetModelsOptions, + bigquery.IListModelsResponse +>; + export type GetTablesOptions = PagedRequest; export type GetTablesResponse = PagedResponse< Table, @@ -89,6 +102,7 @@ export type TableCallback = ResourceCallback; class Dataset extends ServiceObject { bigQuery: BigQuery; location?: string; + getModelsStream: (options?: GetModelsOptions) => ResourceStream; getTablesStream: (options?: GetTablesOptions) => ResourceStream; constructor(bigQuery: BigQuery, id: string, options?: DatasetOptions) { const methods = { @@ -288,6 +302,35 @@ class Dataset extends ServiceObject { }, }); + /** + * List all or some of the {module:bigquery/model} objects in your project + * as a readable object stream. + * + * @param {object} [options] Configuration object. See + * {@link Dataset#getModels} 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.getModelsStream() + * .on('error', console.error) + * .on('data', (model) => {}) + * .on('end', () => { + * // All models have been retrieved + * }); + * + * @example + * dataset.getModelsStream() + * .on('data', function(model) { + * this.end(); + * }); + */ + this.getModelsStream = paginator.streamify('getModels'); + /** * List all or some of the {module:bigquery/table} objects in your project * as a readable object stream. @@ -529,6 +572,91 @@ class Dataset extends ServiceObject { ); } + getModels(options?: GetModelsOptions): Promise; + getModels(options: GetModelsOptions, callback: GetModelsCallback): void; + getModels(callback: GetModelsCallback): void; + /** + * Get a list of models. + * + * @see [Models: list API Documentation]{@link https://cloud.google.com/bigquery/docs/reference/rest/v2/models/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 {Model[]} callback.models The list of models from + * your Dataset. + * @returns {Promise} + * + * @example + * const {BigQuery} = require('@google-cloud/bigquery'); + * const bigquery = new BigQuery(); + * const dataset = bigquery.dataset('institutions'); + * + * dataset.getModels((err, models) => { + * // models is an array of `Model` objects. + * }); + * + * @example + * function manualPaginationCallback(err, models, nextQuery, apiResponse) { + * if (nextQuery) { + * // More results exist. + * dataset.getModels(nextQuery, manualPaginationCallback); + * } + * } + * + * dataset.getModels({ + * autoPaginate: false + * }, manualPaginationCallback); + * + * @example + * dataset.getModels().then((data) => { + * const models = data[0]; + * }); + */ + getModels( + optsOrCb?: GetModelsOptions | GetModelsCallback, + cb: GetModelsCallback + ): void | Promise { + const options = typeof optsOrCb === 'object' ? optsOrCb : {}; + const callback = typeof optsOrCb === 'function' ? optsOrCb : cb; + + this.request( + { + uri: '/models', + qs: options, + }, + (err: null | Error, resp: bigquery.IListModelsResponse) => { + if (err) { + callback!(err, null, null, resp); + return; + } + + let nextQuery: {} | null = null; + if (resp.nextPageToken) { + nextQuery = extend({}, options, { + pageToken: resp.nextPageToken, + }); + } + + const models = (resp.models || []).map(modelObject => { + const model = this.model(modelObject.modelReference.modelId); + model.metadata = modelObject; + return model; + }); + + callback!(null, models, nextQuery, resp); + } + ); + } + /** * Get a list of tables. * @@ -620,6 +748,29 @@ class Dataset extends ServiceObject { ); } + /** + * Create a Model object. + * + * @throws {TypeError} if model ID is missing. + * + * @param {string} id The ID of the model. + * @return {Model} + * + * @example + * const {BigQuery} = require('@google-cloud/bigquery'); + * const bigquery = new BigQuery(); + * const dataset = bigquery.dataset('institutions'); + * + * const model = dataset.model('my-model'); + */ + model(id: string): Model { + if (typeof id !== 'string') { + throw new TypeError('A model ID is required.'); + } + + return new Model(this, id); + } + /** * Run a query scoped to your dataset. * @@ -692,7 +843,7 @@ class Dataset extends ServiceObject { * * These methods can be auto-paginated. */ -paginator.extend(Dataset, ['getTables']); +paginator.extend(Dataset, ['getModels', 'getTables']); /*! Developer Documentation * diff --git a/src/model.ts b/src/model.ts new file mode 100644 index 000000000..5ccadb1c3 --- /dev/null +++ b/src/model.ts @@ -0,0 +1,189 @@ +/*! + * Copyright 2019 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. + */ + +import * as common from '@google-cloud/common'; +import {Dataset} from './dataset'; + +/** + * Model objects are returned by methods such as {@link Dataset#model} and + * {@link Dataset#getModels}. + * + * @class + * @param {Dataset} dataset {@link Dataset} instance. + * @param {string} id The ID of the model. + * + * @example + * const {BigQuery} = require('@google-cloud/bigquery'); + * const bigquery = new BigQuery(); + * const dataset = bigquery.dataset('my-dataset'); + * + * const model = dataset.model('my-model'); + */ +class Model extends common.ServiceObject { + constructor(dataset: Dataset, id: string) { + const methods = { + /** + * Delete a model. + * + * @see [Models: delete API Documentation]{@link https://cloud.google.com/bigquery/docs/reference/rest/v2/models/delete} + * + * @method Model#delete + * @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('my-dataset'); + * const model = dataset.model('my-model'); + * + * model.delete((err, apiResponse) => {}); + * + * @example + * const [apiResponse] = await model.delete(); + */ + delete: true, + + /** + * Check if the model exists. + * + * @method Model#exists + * @param {function} [callback] The callback function. + * @param {?error} callback.err An error returned while making this + * request. + * @param {boolean} callback.exists Whether the model exists or not. + * @returns {Promise} + * + * @example + * const {BigQuery} = require('@google-cloud/bigquery'); + * const bigquery = new BigQuery(); + * const dataset = bigquery.dataset('my-dataset'); + * const model = dataset.model('my-model'); + * + * model.exists((err, exists) => {}); + * + * @example + * const [exists] = await model.exists(); + */ + exists: true, + + /** + * Get a model if it exists. + * + * @see [Models: get API Documentation]{@link https://cloud.google.com/bigquery/docs/reference/rest/v2/models/get} + * + * @method Model#get: + * @param {function} [callback] The callback function. + * @param {?error} callback.err An error returned while making this + * request. + * @param {Model} callback.model The {@link Model}. + * @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('my-dataset'); + * const model = dataset.model('my-model'); + * + * model.get((err, model2, apiResponse) => { + * // `model.metadata` has been populated. + * }); + * + * @example + * const [model2, apiResponse] = await model.get(); + */ + get: true, + + /** + * Return the metadata associated with the Model. + * + * @see [Models: get API Documentation]{@link https://cloud.google.com/bigquery/docs/reference/rest/v2/models/get} + * + * @method Model#getMetadata + * @param {function} [callback] The callback function. + * @param {?error} callback.err An error returned while making this + * request. + * @param {object} callback.metadata The metadata of the Model. + * @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('my-dataset'); + * const model = dataset.model('my-model'); + * + * model.getMetadata((err, metadata, apiResponse) => {}); + * + * @example + * const [metadata, apiResponse] = await model.getMetadata(); + */ + getMetadata: true, + + /** + * @see [Models: patch API Documentation]{@link https://cloud.google.com/bigquery/docs/reference/rest/v2/models/patch} + * + * @method Model#setMetadata + * @param {object} metadata The metadata key/value object to set. + * @param {function} [callback] The callback function. + * @param {?error} callback.err An error returned while making this + * request. + * @param {object} callback.metadata The updated metadata of the Model. + * @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('my-dataset'); + * const model = dataset.model('my-model'); + * + * const metadata = { + * friendlyName: 'thebestmodelever' + * }; + * + * model.setMetadata(metadata, (err, metadata, apiResponse) => {}); + * + * @example + * const [metadata, apiResponse] = await model.setMetadata(metadata); + */ + setMetadata: true, + }; + + super({ + parent: dataset, + baseUrl: '/models', + id, + methods, + }); + } +} + +/** + * Reference to the {@link Model} class. + * @name module:@google-cloud/bigquery.Model + * @see Model + */ +export {Model}; From 31a79930bbc663e9f048392082570f96b98864fe Mon Sep 17 00:00:00 2001 From: Dave Gramlich Date: Tue, 21 May 2019 14:53:02 -0400 Subject: [PATCH 2/9] generate new bq req/res types --- package.json | 4 +- src/types.d.ts | 2909 +++++++++++++++++++++++++++++------------------- 2 files changed, 1760 insertions(+), 1153 deletions(-) diff --git a/package.json b/package.json index cd4c3ddc1..d3fdb341f 100644 --- a/package.json +++ b/package.json @@ -44,7 +44,8 @@ "pretest": "npm run compile", "posttest": "npm run check", "docs-test": "linkinator docs -r --skip www.googleapis.com", - "predocs-test": "npm run docs" + "predocs-test": "npm run docs", + "types": "dtsd bigquery v2 > ./src/types.d.ts" }, "dependencies": { "@google-cloud/common": "^1.0.0", @@ -74,6 +75,7 @@ "@types/tmp": "0.1.0", "@types/uuid": "^3.4.4", "codecov": "^3.0.0", + "discovery-tsd": "^0.1.0", "eslint": "^5.0.0", "eslint-config-prettier": "^4.0.0", "eslint-plugin-node": "^9.0.0", diff --git a/src/types.d.ts b/src/types.d.ts index 0c6063095..ebd149267 100644 --- a/src/types.d.ts +++ b/src/types.d.ts @@ -2,251 +2,264 @@ * BigQuery API */ declare namespace bigquery { - type IBigQueryModelTraining = { - /** - * [Output-only, Beta] Index of current ML training iteration. Updated during create model query job to show job progress. - */ - currentIteration?: number; + /** + * Information about a single training query run for the model. + */ + type ITrainingRun = { /** - * [Output-only, Beta] Expected number of iterations for the create model query job specified as num_iterations in the input query. The actual total number of iterations may be less than this number due to early stop. + * The evaluation metrics over training/eval data that were computed at the + * end of training. */ - expectedTotalIterations?: string; - }; - - type IBigtableColumn = { + evaluationMetrics?: IEvaluationMetrics; /** - * [Optional] The encoding of the values when the type is not STRING. Acceptable encoding values are: TEXT - indicates values are alphanumeric text strings. BINARY - indicates values are encoded using HBase Bytes.toBytes family of functions. 'encoding' can also be set at the column family level. However, the setting at this level takes precedence if 'encoding' is set at both levels. + * Options that were used for this training run, includes + * user specified and default options that were used. */ - encoding?: string; + trainingOptions?: ITrainingOptions; /** - * [Optional] If the qualifier is not a valid BigQuery field identifier i.e. does not match [a-zA-Z][a-zA-Z0-9_]*, a valid identifier must be provided as the column field name and is used as field name in queries. + * The start time of this training run. */ - fieldName?: string; + startTime?: string; /** - * [Optional] If this is set, only the latest version of value in this column are exposed. 'onlyReadLatest' can also be set at the column family level. However, the setting at this level takes precedence if 'onlyReadLatest' is set at both levels. + * Output of each iteration run, results.size() <= max_iterations. */ - onlyReadLatest?: boolean; + results?: Array; + }; + + type ITrainingOptions = { /** - * [Required] Qualifier of the column. Columns in the parent column family that has this exact qualifier are exposed as . field. If the qualifier is valid UTF-8 string, it can be specified in the qualifier_string field. Otherwise, a base-64 encoded value must be set to qualifier_encoded. The column field name is the same as the column qualifier. However, if the qualifier is not a valid BigQuery field identifier i.e. does not match [a-zA-Z][a-zA-Z0-9_]*, a valid identifier must be provided as field_name. + * Learning rate in training. Used only for iterative training algorithms. */ - qualifierEncoded?: string; - qualifierString?: string; + learnRate?: number; /** - * [Optional] The type to convert the value in cells of this column. The values are expected to be encoded using HBase Bytes.toBytes function when using the BINARY encoding value. Following BigQuery types are allowed (case-sensitive) - BYTES STRING INTEGER FLOAT BOOLEAN Default type is BYTES. 'type' can also be set at the column family level. However, the setting at this level takes precedence if 'type' is set at both levels. + * Optimization strategy for training linear regression models. */ - type?: string; - }; - - type IBigtableColumnFamily = { + optimizationStrategy?: + | 'OPTIMIZATION_STRATEGY_UNSPECIFIED' + | 'BATCH_GRADIENT_DESCENT' + | 'NORMAL_EQUATION'; /** - * [Optional] Lists of columns that should be exposed as individual fields as opposed to a list of (column name, value) pairs. All columns whose qualifier matches a qualifier in this list can be accessed as .. Other columns can be accessed as a list through .Column field. + * The maximum number of iterations in training. Used only for iterative + * training algorithms. */ - columns?: Array; + maxIterations?: string; /** - * [Optional] The encoding of the values when the type is not STRING. Acceptable encoding values are: TEXT - indicates values are alphanumeric text strings. BINARY - indicates values are encoded using HBase Bytes.toBytes family of functions. This can be overridden for a specific column by listing that column in 'columns' and specifying an encoding for it. + * The column to split data with. This column won't be used as a + * feature. + * 1. When data_split_method is CUSTOM, the corresponding column should + * be boolean. The rows with true value tag are eval data, and the false + * are training data. + * 2. When data_split_method is SEQ, the first DATA_SPLIT_EVAL_FRACTION + * rows (from smallest to largest) in the corresponding column are used + * as training data, and the rest are eval data. It respects the order + * in Orderable data types: + * https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#data-type-properties */ - encoding?: string; + dataSplitColumn?: string; /** - * Identifier of the column family. + * Weights associated with each label class, for rebalancing the + * training data. Only applicable for classification models. */ - familyId?: string; + labelClassWeights?: { [key: string]: number }; /** - * [Optional] If this is set only the latest version of value are exposed for all columns in this column family. This can be overridden for a specific column by listing that column in 'columns' and specifying a different setting for that column. + * L2 regularization coefficient. */ - onlyReadLatest?: boolean; + l2Regularization?: number; /** - * [Optional] The type to convert the value in cells of this column family. The values are expected to be encoded using HBase Bytes.toBytes function when using the BINARY encoding value. Following BigQuery types are allowed (case-sensitive) - BYTES STRING INTEGER FLOAT BOOLEAN Default type is BYTES. This can be overridden for a specific column by listing that column in 'columns' and specifying a type for it. + * Whether to stop early when the loss doesn't improve significantly + * any more (compared to min_relative_progress). Used only for iterative + * training algorithms. */ - type?: string; - }; - - type IBigtableOptions = { + earlyStop?: boolean; /** - * [Optional] List of column families to expose in the table schema along with their types. This list restricts the column families that can be referenced in queries and specifies their value types. You can use this list to do type conversions - see the 'type' field for more details. If you leave this list empty, all column families are present in the table schema and their values are read as BYTES. During a query only the column families referenced in that query are read from Bigtable. + * The fraction of evaluation data over the whole input data. The rest + * of data will be used as training data. The format should be double. + * Accurate to two decimal places. + * Default value is 0.2. */ - columnFamilies?: Array; + dataSplitEvalFraction?: number; /** - * [Optional] If field is true, then the column families that are not specified in columnFamilies list are not exposed in the table schema. Otherwise, they are read with BYTES type values. The default value is false. + * [Beta] Google Cloud Storage URI from which the model was imported. Only + * applicable for imported models. */ - ignoreUnspecifiedColumnFamilies?: boolean; + modelUri?: string; /** - * [Optional] If field is true, then the rowkey column families will be read and converted to string. Otherwise they are read with BYTES type values and users need to manually cast them with CAST if necessary. The default value is false. + * Specifies the initial learning rate for the line search learn rate + * strategy. */ - readRowkeyAsString?: boolean; - }; - - type IBqmlIterationResult = { + initialLearnRate?: number; /** - * [Output-only, Beta] Time taken to run the training iteration in milliseconds. + * When early_stop is true, stops training when accuracy improvement is + * less than 'min_relative_progress'. Used only for iterative training + * algorithms. */ - durationMs?: string; + minRelativeProgress?: number; /** - * [Output-only, Beta] Eval loss computed on the eval data at the end of the iteration. The eval loss is used for early stopping to avoid overfitting. No eval loss if eval_split_method option is specified as no_split or auto_split with input data size less than 500 rows. + * [Beta] Number of clusters for clustering models. */ - evalLoss?: number; + numClusters?: string; /** - * [Output-only, Beta] Index of the ML training iteration, starting from zero for each training run. + * Name of input label columns in training data. */ - index?: number; + inputLabelColumns?: Array; /** - * [Output-only, Beta] Learning rate used for this iteration, it varies for different training iterations if learn_rate_strategy option is not constant. + * The strategy to determine learn rate for the current iteration. */ - learnRate?: number; + learnRateStrategy?: + | 'LEARN_RATE_STRATEGY_UNSPECIFIED' + | 'LINE_SEARCH' + | 'CONSTANT'; /** - * [Output-only, Beta] Training loss computed on the training data at the end of the iteration. The training loss function is defined by model type. + * Whether to train a model from the last checkpoint. */ - trainingLoss?: number; - }; - - type IBqmlTrainingRun = { + warmStart?: boolean; /** - * [Output-only, Beta] List of each iteration results. + * The data split type for training and evaluation, e.g. RANDOM. */ - iterationResults?: Array; + dataSplitMethod?: + | 'DATA_SPLIT_METHOD_UNSPECIFIED' + | 'RANDOM' + | 'CUSTOM' + | 'SEQUENTIAL' + | 'NO_SPLIT' + | 'AUTO_SPLIT'; /** - * [Output-only, Beta] Training run start time in milliseconds since the epoch. + * Type of loss function used during training run. */ - startTime?: string; + lossType?: 'LOSS_TYPE_UNSPECIFIED' | 'MEAN_SQUARED_LOSS' | 'MEAN_LOG_LOSS'; /** - * [Output-only, Beta] Different state applicable for a training run. IN PROGRESS: Training run is in progress. FAILED: Training run ended due to a non-retryable failure. SUCCEEDED: Training run successfully completed. CANCELLED: Training run cancelled by the user. + * L1 regularization coefficient. */ - state?: string; + l1Regularization?: number; /** - * [Output-only, Beta] Training options used by this training run. These options are mutable for subsequent training runs. Default values are explicitly stored for options not specified in the input query of the first training run. For subsequent training runs, any option not explicitly specified in the input query will be copied from the previous training run. + * [Beta] Distance type for clustering models. */ - trainingOptions?: { - earlyStop?: boolean; - l1Reg?: number; - l2Reg?: number; - learnRate?: number; - learnRateStrategy?: string; - lineSearchInitLearnRate?: number; - maxIteration?: string; - minRelProgress?: number; - warmStart?: boolean; - }; + distanceType?: 'DISTANCE_TYPE_UNSPECIFIED' | 'EUCLIDEAN' | 'COSINE'; }; - type IClustering = { + type IJobConfiguration = { /** - * [Repeated] One or more fields on which data should be clustered. Only top-level, non-repeated, simple-type fields are supported. When you cluster a table using multiple columns, the order of columns you specify is important. The order of the specified columns determines the sort order of the data. + * [Optional] If set, don't actually run this job. A valid query will return a mostly empty response with some processing statistics, while an invalid query will return the same error it would if it wasn't a dry run. Behavior of non-query jobs is undefined. */ - fields?: Array; - }; - - type ICsvOptions = { + dryRun?: boolean; /** - * [Optional] Indicates if BigQuery should accept rows that are missing trailing optional columns. If true, BigQuery treats missing trailing columns as null values. If false, records with missing trailing columns are treated as bad records, and if there are too many bad records, an invalid error is returned in the job result. The default value is false. + * The labels associated with this job. You can use these to organize and group your jobs. Label keys and values can be no longer than 63 characters, can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. Label values are optional. Label keys must start with a letter and each label in the list must have a different key. */ - allowJaggedRows?: boolean; + labels?: { [key: string]: string }; /** - * [Optional] Indicates if BigQuery should allow quoted data sections that contain newline characters in a CSV file. The default value is false. + * [Pick one] Configures a load job. */ - allowQuotedNewlines?: boolean; + load?: IJobConfigurationLoad; /** - * [Optional] The character encoding of the data. The supported values are UTF-8 or ISO-8859-1. The default value is UTF-8. BigQuery decodes the data after the raw, binary data has been split using the values of the quote and fieldDelimiter properties. + * [Output-only] The type of the job. Can be QUERY, LOAD, EXTRACT, COPY or UNKNOWN. */ - encoding?: string; + jobType?: string; /** - * [Optional] The separator for fields in a CSV file. BigQuery converts the string to ISO-8859-1 encoding, and then uses the first byte of the encoded string to split the data in its raw, binary state. BigQuery also supports the escape sequence "\t" to specify a tab separator. The default value is a comma (','). + * [Pick one] Configures an extract job. */ - fieldDelimiter?: string; + extract?: IJobConfigurationExtract; /** - * [Optional] The value that is used to quote data sections in a CSV file. BigQuery converts the string to ISO-8859-1 encoding, and then uses the first byte of the encoded string to split the data in its raw, binary state. The default value is a double-quote ('"'). If your data does not contain quoted sections, set the property value to an empty string. If your data contains quoted newline characters, you must also set the allowQuotedNewlines property to true. + * [Pick one] Copies a table. */ - quote?: string; + copy?: IJobConfigurationTableCopy; /** - * [Optional] The number of rows at the top of a CSV file that BigQuery will skip when reading the data. The default value is 0. This property is useful if you have header rows in the file that should be skipped. + * [Optional] Job timeout in milliseconds. If this time limit is exceeded, BigQuery may attempt to terminate the job. */ - skipLeadingRows?: string; + jobTimeoutMs?: string; + /** + * [Pick one] Configures a query job. + */ + query?: IJobConfigurationQuery; }; - type IDataset = { + type IUserDefinedFunctionResource = { /** - * [Optional] An array of objects that define dataset access for one or more entities. You can set this property when inserting or updating a dataset in order to control who is allowed to access the data. If unspecified at dataset creation time, BigQuery adds default dataset access for the following entities: access.specialGroup: projectReaders; access.role: READER; access.specialGroup: projectWriters; access.role: WRITER; access.specialGroup: projectOwners; access.role: OWNER; access.userByEmail: [dataset creator email]; access.role: OWNER; + * [Pick one] A code resource to load from a Google Cloud Storage URI (gs://bucket/path). */ - access?: Array<{ - /** - * [Pick one] A domain to grant access to. Any users signed in with the domain specified will be granted the specified access. Example: "example.com". Maps to IAM policy member "domain:DOMAIN". - */ - domain?: string; - /** - * [Pick one] An email address of a Google Group to grant access to. Maps to IAM policy member "group:GROUP". - */ - groupByEmail?: string; - /** - * [Pick one] Some other type of member that appears in the IAM Policy but isn't a user, group, domain, or special group. - */ - iamMember?: string; - /** - * [Required] An IAM role ID that should be granted to the user, group, or domain specified in this access entry. The following legacy mappings will be applied: OWNER roles/bigquery.dataOwner WRITER roles/bigquery.dataEditor READER roles/bigquery.dataViewer This field will accept any of the above formats, but will return only the legacy format. For example, if you set this field to "roles/bigquery.dataOwner", it will be returned back as "OWNER". - */ - role?: string; - /** - * [Pick one] A special group to grant access to. Possible values include: projectOwners: Owners of the enclosing project. projectReaders: Readers of the enclosing project. projectWriters: Writers of the enclosing project. allAuthenticatedUsers: All authenticated BigQuery users. Maps to similarly-named IAM members. - */ - specialGroup?: string; - /** - * [Pick one] An email address of a user to grant access to. For example: fred@example.com. Maps to IAM policy member "user:EMAIL" or "serviceAccount:EMAIL". - */ - userByEmail?: string; - /** - * [Pick one] A view from a different dataset to grant access to. Queries executed against that view will have read access to tables in this dataset. The role field is not required when this field is set. If that view is updated by any user, access to the view needs to be granted again via an update operation. - */ - view?: ITableReference; - }>; + resourceUri?: string; /** - * [Output-only] The time when this dataset was created, in milliseconds since the epoch. + * [Pick one] An inline resource that contains code for a user-defined function (UDF). Providing a inline code resource is equivalent to providing a URI for a file containing the same code. */ - creationTime?: string; + inlineCode?: string; + }; + + /** + * Represents a single JSON object. + */ + type IJsonObject = { [key: string]: IJsonValue }; + + /** + * Aggregate metrics for classification/classifier models. For multi-class + * models, the metrics are either macro-averaged or micro-averaged. When + * macro-averaged, the metrics are calculated for each label and then an + * unweighted average is taken of those values. When micro-averaged, the + * metric is calculated globally by counting the total number of correctly + * predicted rows. + */ + type IAggregateClassificationMetrics = { /** - * [Required] A reference that identifies the dataset. + * The F1 score is an average of recall and precision. For multiclass + * this is a macro-averaged metric. */ - datasetReference?: IDatasetReference; + f1Score?: number; /** - * [Optional] The default partition expiration for all partitioned tables in the dataset, in milliseconds. Once this property is set, all newly-created partitioned tables in the dataset will have an expirationMs property in the timePartitioning settings set to this value, and changing the value will only affect new tables, not existing ones. The storage in a partition will have an expiration time of its partition time plus this value. Setting this property overrides the use of defaultTableExpirationMs for partitioned tables: only one of defaultTableExpirationMs and defaultPartitionExpirationMs will be used for any new partitioned table. If you provide an explicit timePartitioning.expirationMs when creating or updating a partitioned table, that value takes precedence over the default partition expiration time indicated by this property. + * Precision is the fraction of actual positive predictions that had + * positive actual labels. For multiclass this is a macro-averaged + * metric treating each class as a binary classifier. */ - defaultPartitionExpirationMs?: string; + precision?: number; /** - * [Optional] The default lifetime of all tables in the dataset, in milliseconds. The minimum value is 3600000 milliseconds (one hour). Once this property is set, all newly-created tables in the dataset will have an expirationTime property set to the creation time plus the value in this property, and changing the value will only affect new tables, not existing ones. When the expirationTime for a given table is reached, that table will be deleted automatically. If a table's expirationTime is modified or removed before the table expires, or if you provide an explicit expirationTime when creating a table, that value takes precedence over the default expiration time indicated by this property. + * Accuracy is the fraction of predictions given the correct label. For + * multiclass this is a micro-averaged metric. */ - defaultTableExpirationMs?: string; + accuracy?: number; /** - * [Optional] A user-friendly description of the dataset. + * Recall is the fraction of actual positive labels that were given a + * positive prediction. For multiclass this is a macro-averaged metric. */ - description?: string; + recall?: number; /** - * [Output-only] A hash of the resource. + * Threshold at which the metrics are computed. For binary + * classification models this is the positive class threshold. + * For multi-class classfication models this is the confidence + * threshold. */ - etag?: string; + threshold?: number; /** - * [Optional] A descriptive name for the dataset. + * Area Under a ROC Curve. For multiclass this is a macro-averaged + * metric. */ - friendlyName?: string; + rocAuc?: number; /** - * [Output-only] The fully-qualified unique name of the dataset in the format projectId:datasetId. The dataset name without the project name is given in the datasetId field. When creating a new dataset, leave this field blank, and instead specify the datasetId field. + * Logarithmic Loss. For multiclass this is a macro-averaged metric. */ - id?: string; + logLoss?: number; + }; + + type IExplainQueryStep = { /** - * [Output-only] The resource type. + * Human-readable stage descriptions. */ - kind?: string; + substeps?: Array; /** - * The labels associated with this dataset. You can use these to organize and group your datasets. You can set this property when inserting or updating a dataset. See Creating and Updating Dataset Labels for more information. + * Machine-readable operation type. */ - labels?: { [key: string]: string }; + kind?: string; + }; + + type IQueryParameter = { /** - * [Output-only] The date when this dataset or any of its tables was last modified, in milliseconds since the epoch. + * [Optional] If unset, this is a positional parameter. Otherwise, should be unique within a query. */ - lastModifiedTime?: string; + name?: string; /** - * The geographic location where the dataset should reside. The default value is US. See details at https://cloud.google.com/bigquery/docs/locations. + * [Required] The type of this parameter. */ - location?: string; + parameterType?: IQueryParameterType; /** - * [Output-only] A URL that can be used to access the resource again. You can use this URL in Get or Update requests to the resource. + * [Required] The value of this parameter. */ - selfLink?: string; + parameterValue?: IQueryParameterValue; }; type IDatasetList = { @@ -255,17 +268,17 @@ declare namespace bigquery { */ datasets?: Array<{ /** - * The dataset reference. Use this property to access specific parts of the dataset's ID, such as project ID or dataset ID. + * The fully-qualified, unique, opaque ID of the dataset. */ - datasetReference?: IDatasetReference; + id?: string; /** - * A descriptive name for the dataset, if one exists. + * The geographic location where the data resides. */ - friendlyName?: string; + location?: string; /** - * The fully-qualified, unique, opaque ID of the dataset. + * A descriptive name for the dataset, if one exists. */ - id?: string; + friendlyName?: string; /** * The resource type. This property always returns the value "bigquery#dataset". */ @@ -275,725 +288,1312 @@ declare namespace bigquery { */ labels?: { [key: string]: string }; /** - * The geographic location where the data resides. + * The dataset reference. Use this property to access specific parts of the dataset's ID, such as project ID or dataset ID. */ - location?: string; + datasetReference?: IDatasetReference; }>; /** - * A hash value of the results page. You can use this property to determine if the page has changed since the last request. + * A token that can be used to request the next results page. This property is omitted on the final results page. */ - etag?: string; + nextPageToken?: string; /** * The list type. This property always returns the value "bigquery#datasetList". */ kind?: string; /** - * A token that can be used to request the next results page. This property is omitted on the final results page. + * A hash value of the results page. You can use this property to determine if the page has changed since the last request. */ - nextPageToken?: string; + etag?: string; }; - type IDatasetReference = { + type IJobConfigurationTableCopy = { /** - * [Required] A unique ID for this dataset, without the project name. The ID must contain only letters (a-z, A-Z), numbers (0-9), or underscores (_). The maximum length is 1,024 characters. + * [Pick one] Source table to copy. */ - datasetId?: string; + sourceTable?: ITableReference; /** - * [Optional] The ID of the project containing this dataset. + * [Optional] Specifies the action that occurs if the destination table already exists. The following values are supported: WRITE_TRUNCATE: If the table already exists, BigQuery overwrites the table data. WRITE_APPEND: If the table already exists, BigQuery appends the data to the table. WRITE_EMPTY: If the table already exists and contains data, a 'duplicate' error is returned in the job result. The default value is WRITE_EMPTY. Each action is atomic and only occurs if BigQuery is able to complete the job successfully. Creation, truncation and append actions occur as one atomic update upon job completion. */ - projectId?: string; - }; - - type IDestinationTableProperties = { + writeDisposition?: string; /** - * [Optional] The description for the destination table. This will only be used if the destination table is newly created. If the table already exists and a value different than the current description is provided, the job will fail. + * [Required] The destination table */ - description?: string; + destinationTable?: ITableReference; /** - * [Optional] The friendly name for the destination table. This will only be used if the destination table is newly created. If the table already exists and a value different than the current friendly name is provided, the job will fail. + * Custom encryption configuration (e.g., Cloud KMS keys). */ - friendlyName?: string; + destinationEncryptionConfiguration?: IEncryptionConfiguration; /** - * [Optional] The labels associated with this table. You can use these to organize and group your tables. This will only be used if the destination table is newly created. If the table already exists and labels are different than the current labels are provided, the job will fail. + * [Pick one] Source tables to copy. */ - labels?: { [key: string]: string }; - }; - - type IEncryptionConfiguration = { + sourceTables?: Array; /** - * [Optional] Describes the Cloud KMS encryption key that will be used to protect destination BigQuery table. The BigQuery Service Account associated with your project requires access to this encryption key. + * [Optional] Specifies whether the job is allowed to create new tables. The following values are supported: CREATE_IF_NEEDED: If the table does not exist, BigQuery creates the table. CREATE_NEVER: The table must already exist. If it does not, a 'notFound' error is returned in the job result. The default value is CREATE_IF_NEEDED. Creation, truncation and append actions occur as one atomic update upon job completion. */ - kmsKeyName?: string; + createDisposition?: string; }; - type IErrorProto = { + /** + * Confusion matrix for binary classification models. + */ + type IBinaryConfusionMatrix = { /** - * Debugging information. This property is internal to Google and should not be used. + * Aggregate recall. */ - debugInfo?: string; + recall?: number; /** - * Specifies where the error occurred, if present. + * Number of false samples predicted as false. */ - location?: string; + falseNegatives?: string; /** - * A human-readable description of the error. + * Number of true samples predicted as false. */ - message?: string; + trueNegatives?: string; /** - * A short error code that summarizes the error. + * Number of false samples predicted as true. */ - reason?: string; - }; - - type IExplainQueryStage = { + falsePositives?: string; /** - * Number of parallel input segments completed. + * Aggregate precision. */ - completedParallelInputs?: string; + precision?: number; /** - * Milliseconds the average shard spent on CPU-bound tasks. + * Threshold value used when computing each of the following metric. */ - computeMsAvg?: string; + positiveClassThreshold?: number; /** - * Milliseconds the slowest shard spent on CPU-bound tasks. + * Number of true samples predicted as true. */ - computeMsMax?: string; + truePositives?: string; + }; + + type ITableRow = { /** - * Relative amount of time the average shard spent on CPU-bound tasks. + * Represents a single row in the result set, consisting of one or more fields. */ - computeRatioAvg?: number; + f?: Array; + }; + + /** + * Evaluation metrics for multi-class classification/classifier models. + */ + type IMultiClassClassificationMetrics = { /** - * Relative amount of time the slowest shard spent on CPU-bound tasks. + * Aggregate classification metrics. */ - computeRatioMax?: number; + aggregateClassificationMetrics?: IAggregateClassificationMetrics; /** - * Stage end time represented as milliseconds since epoch. + * Confusion matrix at different thresholds. */ - endMs?: string; + confusionMatrixList?: Array; + }; + + type IQueryTimelineSample = { /** - * Unique ID for stage within plan. + * Cumulative slot-ms consumed by the query. */ - id?: string; + totalSlotMs?: string; /** - * IDs for stages that are inputs to this stage. + * Total number of units currently being processed by workers. This does not correspond directly to slot usage. This is the largest value observed since the last sample. */ - inputStages?: Array; + activeUnits?: string; /** - * Human-readable name for stage. + * Total parallel units of work completed by this query. */ - name?: string; + completedUnits?: string; /** - * Number of parallel input segments to be processed. + * Milliseconds elapsed since the start of query execution. */ - parallelInputs?: string; + elapsedMs?: string; /** - * Milliseconds the average shard spent reading input. + * Total parallel units of work remaining for the active stages. */ - readMsAvg?: string; + pendingUnits?: string; + }; + + type IQueryRequest = { /** - * Milliseconds the slowest shard spent reading input. + * The geographic location where the job should run. See details at https://cloud.google.com/bigquery/docs/locations#specifying_your_location. */ - readMsMax?: string; + location?: string; /** - * Relative amount of time the average shard spent reading input. + * [Deprecated] This property is deprecated. */ - readRatioAvg?: number; + preserveNulls?: boolean; /** - * Relative amount of time the slowest shard spent reading input. + * [Optional] The maximum number of rows of data to return per page of results. Setting this flag to a small value such as 1000 and then paging through results might improve reliability when the query result set is large. In addition to this limit, responses are also limited to 10 MB. By default, there is no maximum row count, and only the byte limit applies. */ - readRatioMax?: number; + maxResults?: number; /** - * Number of records read into the stage. + * [Required] A query string, following the BigQuery query syntax, of the query to execute. Example: "SELECT count(f1) FROM [myProjectId:myDatasetId.myTableId]". */ - recordsRead?: string; + query?: string; /** - * Number of records written by the stage. + * [Optional] If set to true, BigQuery doesn't run the job. Instead, if the query is valid, BigQuery returns statistics about the job such as how many bytes would be processed. If the query is invalid, an error returns. The default value is false. */ - recordsWritten?: string; + dryRun?: boolean; /** - * Total number of bytes written to shuffle. + * Query parameters for Standard SQL queries. */ - shuffleOutputBytes?: string; + queryParameters?: Array; /** - * Total number of bytes written to shuffle and spilled to disk. + * Specifies whether to use BigQuery's legacy SQL dialect for this query. The default value is true. If set to false, the query will use BigQuery's standard SQL: https://cloud.google.com/bigquery/sql-reference/ When useLegacySql is set to false, the value of flattenResults is ignored; query will be run as if flattenResults is false. */ - shuffleOutputBytesSpilled?: string; + useLegacySql?: boolean; /** - * Stage start time represented as milliseconds since epoch. + * [Optional] How long to wait for the query to complete, in milliseconds, before the request times out and returns. Note that this is only a timeout for the request, not the query. If the query takes longer to run than the timeout value, the call returns without any results and with the 'jobComplete' flag set to false. You can call GetQueryResults() to wait for the query to complete and read the results. The default value is 10000 milliseconds (10 seconds). */ - startMs?: string; + timeoutMs?: number; /** - * Current status for the stage. + * The resource type of the request. */ - status?: string; + kind?: string; /** - * List of operations within the stage in dependency order (approximately chronological). + * Standard SQL only. Set to POSITIONAL to use positional (?) query parameters or to NAMED to use named (@myparam) query parameters in this query. */ - steps?: Array; + parameterMode?: string; /** - * Milliseconds the average shard spent waiting to be scheduled. + * [Optional] Whether to look for the result in the query cache. The query cache is a best-effort cache that will be flushed whenever tables in the query are modified. The default value is true. */ - waitMsAvg?: string; + useQueryCache?: boolean; /** - * Milliseconds the slowest shard spent waiting to be scheduled. + * [Optional] Specifies the default datasetId and projectId to assume for any unqualified table names in the query. If not set, all table names in the query string must be qualified in the format 'datasetId.tableId'. */ - waitMsMax?: string; + defaultDataset?: IDatasetReference; + }; + + type IErrorProto = { /** - * Relative amount of time the average shard spent waiting to be scheduled. + * A short error code that summarizes the error. */ - waitRatioAvg?: number; + reason?: string; /** - * Relative amount of time the slowest shard spent waiting to be scheduled. + * A human-readable description of the error. */ - waitRatioMax?: number; + message?: string; /** - * Milliseconds the average shard spent on writing output. + * Specifies where the error occurred, if present. */ - writeMsAvg?: string; + location?: string; /** - * Milliseconds the slowest shard spent on writing output. + * Debugging information. This property is internal to Google and should not be used. */ - writeMsMax?: string; + debugInfo?: string; + }; + + /** + * Evaluation metrics for binary classification/classifier models. + */ + type IBinaryClassificationMetrics = { /** - * Relative amount of time the average shard spent on writing output. + * Binary confusion matrix at multiple thresholds. */ - writeRatioAvg?: number; + binaryConfusionMatrixList?: Array; /** - * Relative amount of time the slowest shard spent on writing output. + * Aggregate classification metrics. */ - writeRatioMax?: number; + aggregateClassificationMetrics?: IAggregateClassificationMetrics; }; - type IExplainQueryStep = { + type IRangePartitioning = { /** - * Machine-readable operation type. + * [TrustedTester] [Required] The table is partitioned by this field. The field must be a top-level NULLABLE/REQUIRED field. The only supported type is INTEGER/INT64. */ - kind?: string; + field?: string; /** - * Human-readable stage descriptions. + * [TrustedTester] [Required] Defines the ranges for range partitioning. */ - substeps?: Array; + range?: { + /** + * [TrustedTester] [Required] The start of range partitioning, inclusive. + */ + start?: string; + /** + * [TrustedTester] [Required] The end of range partitioning, exclusive. + */ + end?: string; + /** + * [TrustedTester] [Required] The width of each interval. + */ + interval?: string; + }; }; - type IExternalDataConfiguration = { - /** - * Try to detect schema and format options automatically. Any option specified explicitly will be honored. - */ - autodetect?: boolean; + type IClustering = { /** - * [Optional] Additional options if sourceFormat is set to BIGTABLE. + * [Repeated] One or more fields on which data should be clustered. Only top-level, non-repeated, simple-type fields are supported. When you cluster a table using multiple columns, the order of columns you specify is important. The order of the specified columns determines the sort order of the data. */ - bigtableOptions?: IBigtableOptions; + fields?: Array; + }; + + type IBqmlTrainingRun = { /** - * [Optional] The compression type of the data source. Possible values include GZIP and NONE. The default value is NONE. This setting is ignored for Google Cloud Bigtable, Google Cloud Datastore backups and Avro formats. + * [Output-only, Beta] List of each iteration results. */ - compression?: string; + iterationResults?: Array; /** - * Additional properties to set if sourceFormat is set to CSV. + * [Output-only, Beta] Training run start time in milliseconds since the epoch. */ - csvOptions?: ICsvOptions; + startTime?: string; /** - * [Optional] Additional options if sourceFormat is set to GOOGLE_SHEETS. + * [Output-only, Beta] Training options used by this training run. These options are mutable for subsequent training runs. Default values are explicitly stored for options not specified in the input query of the first training run. For subsequent training runs, any option not explicitly specified in the input query will be copied from the previous training run. */ - googleSheetsOptions?: IGoogleSheetsOptions; + trainingOptions?: { + lineSearchInitLearnRate?: number; + earlyStop?: boolean; + l1Reg?: number; + maxIteration?: string; + learnRate?: number; + minRelProgress?: number; + l2Reg?: number; + warmStart?: boolean; + learnRateStrategy?: string; + }; /** - * [Optional, Experimental] If hive partitioning is enabled, which mode to use. Two modes are supported: - AUTO: automatically infer partition key name(s) and type(s). - STRINGS: automatic infer partition key name(s). All types are strings. Not all storage formats support hive partitioning -- requesting hive partitioning on an unsupported format will lead to an error. + * [Output-only, Beta] Different state applicable for a training run. IN PROGRESS: Training run is in progress. FAILED: Training run ended due to a non-retryable failure. SUCCEEDED: Training run successfully completed. CANCELLED: Training run cancelled by the user. */ - hivePartitioningMode?: string; + state?: string; + }; + + type IBigtableColumnFamily = { /** - * [Optional] Indicates if BigQuery should allow extra values that are not represented in the table schema. If true, the extra values are ignored. If false, records with extra columns are treated as bad records, and if there are too many bad records, an invalid error is returned in the job result. The default value is false. The sourceFormat property determines what BigQuery treats as an extra value: CSV: Trailing columns JSON: Named values that don't match any column names Google Cloud Bigtable: This setting is ignored. Google Cloud Datastore backups: This setting is ignored. Avro: This setting is ignored. + * [Optional] The encoding of the values when the type is not STRING. Acceptable encoding values are: TEXT - indicates values are alphanumeric text strings. BINARY - indicates values are encoded using HBase Bytes.toBytes family of functions. This can be overridden for a specific column by listing that column in 'columns' and specifying an encoding for it. */ - ignoreUnknownValues?: boolean; + encoding?: string; /** - * [Optional] The maximum number of bad records that BigQuery can ignore when reading data. If the number of bad records exceeds this value, an invalid error is returned in the job result. This is only valid for CSV, JSON, and Google Sheets. The default value is 0, which requires that all records are valid. This setting is ignored for Google Cloud Bigtable, Google Cloud Datastore backups and Avro formats. + * [Optional] Lists of columns that should be exposed as individual fields as opposed to a list of (column name, value) pairs. All columns whose qualifier matches a qualifier in this list can be accessed as .. Other columns can be accessed as a list through .Column field. */ - maxBadRecords?: number; + columns?: Array; /** - * [Optional] The schema for the data. Schema is required for CSV and JSON formats. Schema is disallowed for Google Cloud Bigtable, Cloud Datastore backups, and Avro formats. + * [Optional] The type to convert the value in cells of this column family. The values are expected to be encoded using HBase Bytes.toBytes function when using the BINARY encoding value. Following BigQuery types are allowed (case-sensitive) - BYTES STRING INTEGER FLOAT BOOLEAN Default type is BYTES. This can be overridden for a specific column by listing that column in 'columns' and specifying a type for it. */ - schema?: ITableSchema; + type?: string; /** - * [Required] The data format. For CSV files, specify "CSV". For Google sheets, specify "GOOGLE_SHEETS". For newline-delimited JSON, specify "NEWLINE_DELIMITED_JSON". For Avro files, specify "AVRO". For Google Cloud Datastore backups, specify "DATASTORE_BACKUP". [Beta] For Google Cloud Bigtable, specify "BIGTABLE". + * Identifier of the column family. */ - sourceFormat?: string; + familyId?: string; /** - * [Required] The fully-qualified URIs that point to your data in Google Cloud. For Google Cloud Storage URIs: Each URI can contain one '*' wildcard character and it must come after the 'bucket' name. Size limits related to load jobs apply to external data sources. For Google Cloud Bigtable URIs: Exactly one URI can be specified and it has be a fully specified and valid HTTPS URL for a Google Cloud Bigtable table. For Google Cloud Datastore backups, exactly one URI can be specified. Also, the '*' wildcard character is not allowed. + * [Optional] If this is set only the latest version of value are exposed for all columns in this column family. This can be overridden for a specific column by listing that column in 'columns' and specifying a different setting for that column. */ - sourceUris?: Array; + onlyReadLatest?: boolean; }; - type IGetQueryResultsResponse = { + type IJobConfigurationLoad = { /** - * Whether the query result was fetched from the query cache. + * Custom encryption configuration (e.g., Cloud KMS keys). */ - cacheHit?: boolean; + destinationEncryptionConfiguration?: IEncryptionConfiguration; /** - * [Output-only] The first errors or warnings encountered during the running of the job. The final message includes the number of errors that caused the process to stop. Errors here do not necessarily mean that the job has completed or was unsuccessful. + * Allows the schema of the destination table to be updated as a side effect of the load job if a schema is autodetected or supplied in the job configuration. Schema update options are supported in two cases: when writeDisposition is WRITE_APPEND; when writeDisposition is WRITE_TRUNCATE and the destination table is a partition of a table, specified by partition decorators. For normal tables, WRITE_TRUNCATE will always overwrite the schema. One or more of the following values are specified: ALLOW_FIELD_ADDITION: allow adding a nullable field to the schema. ALLOW_FIELD_RELAXATION: allow relaxing a required field in the original schema to nullable. */ - errors?: Array; + schemaUpdateOptions?: Array; /** - * A hash of this response. + * [Deprecated] The inline schema. For CSV schemas, specify as "Field1:Type1[,Field2:Type2]*". For example, "foo:STRING, bar:INTEGER, baz:FLOAT". */ - etag?: string; + schemaInline?: string; /** - * Whether the query has completed or not. If rows or totalRows are present, this will always be true. If this is false, totalRows will not be available. + * [TrustedTester] Range partitioning specification for this table. Only one of timePartitioning and rangePartitioning should be specified. */ - jobComplete?: boolean; + rangePartitioning?: IRangePartitioning; /** - * Reference to the BigQuery Job that was created to run the query. This field will be present even if the original request timed out, in which case GetQueryResults can be used to read the results once the query has completed. Since this API only returns the first page of results, subsequent pages can be fetched via the same mechanism (GetQueryResults). + * [Optional] Specifies a string that represents a null value in a CSV file. For example, if you specify "\N", BigQuery interprets "\N" as a null value when loading a CSV file. The default value is the empty string. If you set this property to a custom value, BigQuery throws an error if an empty string is present for all data types except for STRING and BYTE. For STRING and BYTE columns, BigQuery interprets the empty string as an empty value. */ - jobReference?: IJobReference; + nullMarker?: string; /** - * The resource type of the response. + * [Optional] The schema for the destination table. The schema can be omitted if the destination table already exists, or if you're loading data from Google Cloud Datastore. */ - kind?: string; + schema?: ITableSchema; /** - * [Output-only] The number of rows affected by a DML statement. Present only for DML statements INSERT, UPDATE or DELETE. + * [Deprecated] The format of the schemaInline property. */ - numDmlAffectedRows?: string; + schemaInlineFormat?: string; /** - * A token used for paging results. + * [Optional] The value that is used to quote data sections in a CSV file. BigQuery converts the string to ISO-8859-1 encoding, and then uses the first byte of the encoded string to split the data in its raw, binary state. The default value is a double-quote ('"'). If your data does not contain quoted sections, set the property value to an empty string. If your data contains quoted newline characters, you must also set the allowQuotedNewlines property to true. */ - pageToken?: string; + quote?: string; /** - * An object with as many results as can be contained within the maximum permitted reply size. To get any additional rows, you can call GetQueryResults and specify the jobReference returned above. Present only when the query completes successfully. + * [Optional] Specifies the action that occurs if the destination table already exists. The following values are supported: WRITE_TRUNCATE: If the table already exists, BigQuery overwrites the table data. WRITE_APPEND: If the table already exists, BigQuery appends the data to the table. WRITE_EMPTY: If the table already exists and contains data, a 'duplicate' error is returned in the job result. The default value is WRITE_APPEND. Each action is atomic and only occurs if BigQuery is able to complete the job successfully. Creation, truncation and append actions occur as one atomic update upon job completion. */ - rows?: Array; + writeDisposition?: string; /** - * The schema of the results. Present only when the query completes successfully. + * [Beta] [Optional] Properties with which to create the destination table if it is new. */ - schema?: ITableSchema; + destinationTableProperties?: IDestinationTableProperties; /** - * The total number of bytes processed for this query. + * [Optional] The format of the data files. For CSV files, specify "CSV". For datastore backups, specify "DATASTORE_BACKUP". For newline-delimited JSON, specify "NEWLINE_DELIMITED_JSON". For Avro, specify "AVRO". For parquet, specify "PARQUET". For orc, specify "ORC". The default value is CSV. */ - totalBytesProcessed?: string; + sourceFormat?: string; /** - * The total number of rows in the complete query result set, which can be more than the number of rows in this single page of results. Present only when the query completes successfully. + * [Optional] Indicates if BigQuery should allow extra values that are not represented in the table schema. If true, the extra values are ignored. If false, records with extra columns are treated as bad records, and if there are too many bad records, an invalid error is returned in the job result. The default value is false. The sourceFormat property determines what BigQuery treats as an extra value: CSV: Trailing columns JSON: Named values that don't match any column names */ - totalRows?: string; - }; - - type IGetServiceAccountResponse = { + ignoreUnknownValues?: boolean; /** - * The service account email address. + * [Required] The destination table to load the data into. */ - email?: string; + destinationTable?: ITableReference; /** - * The resource type of the response. + * [Optional] The character encoding of the data. The supported values are UTF-8 or ISO-8859-1. The default value is UTF-8. BigQuery decodes the data after the raw, binary data has been split using the values of the quote and fieldDelimiter properties. */ - kind?: string; - }; - - type IGoogleSheetsOptions = { + encoding?: string; /** - * [Beta] [Optional] Range of a sheet to query from. Only used when non-empty. Typical format: sheet_name!top_left_cell_id:bottom_right_cell_id For example: sheet1!A1:B20 + * [Beta] Clustering specification for the destination table. Must be specified with time-based partitioning, data in the table will be first partitioned and subsequently clustered. */ - range?: string; + clustering?: IClustering; /** - * [Optional] The number of rows at the top of a sheet that BigQuery will skip when reading the data. The default value is 0. This property is useful if you have header rows that should be skipped. When autodetect is on, behavior is the following: * skipLeadingRows unspecified - Autodetect tries to detect headers in the first row. If they are not detected, the row is read as data. Otherwise data is read starting from the second row. * skipLeadingRows is 0 - Instructs autodetect that there are no headers and data should be read starting from the first row. * skipLeadingRows = N > 0 - Autodetect skips N-1 rows and tries to detect headers in row N. If headers are not detected, row N is just skipped. Otherwise row N is used to extract column names for the detected schema. + * [Optional, Experimental] If hive partitioning is enabled, which mode to use. Two modes are supported: - AUTO: automatically infer partition key name(s) and type(s). - STRINGS: automatic infer partition key name(s). All types are strings. Not all storage formats support hive partitioning -- requesting hive partitioning on an unsupported format will lead to an error. */ - skipLeadingRows?: string; - }; - - type IJob = { + hivePartitioningMode?: string; /** - * [Required] Describes the job configuration. + * [Optional] Specifies whether the job is allowed to create new tables. The following values are supported: CREATE_IF_NEEDED: If the table does not exist, BigQuery creates the table. CREATE_NEVER: The table must already exist. If it does not, a 'notFound' error is returned in the job result. The default value is CREATE_IF_NEEDED. Creation, truncation and append actions occur as one atomic update upon job completion. */ - configuration?: IJobConfiguration; + createDisposition?: string; /** - * [Output-only] A hash of this resource. + * [Required] The fully-qualified URIs that point to your data in Google Cloud. For Google Cloud Storage URIs: Each URI can contain one '*' wildcard character and it must come after the 'bucket' name. Size limits related to load jobs apply to external data sources. For Google Cloud Bigtable URIs: Exactly one URI can be specified and it has be a fully specified and valid HTTPS URL for a Google Cloud Bigtable table. For Google Cloud Datastore backups: Exactly one URI can be specified. Also, the '*' wildcard character is not allowed. */ - etag?: string; + sourceUris?: Array; /** - * [Output-only] Opaque ID field of the job + * [Optional] The maximum number of bad records that BigQuery can ignore when running the job. If the number of bad records exceeds this value, an invalid error is returned in the job result. This is only valid for CSV and JSON. The default value is 0, which requires that all records are valid. */ - id?: string; + maxBadRecords?: number; /** - * [Optional] Reference describing the unique-per-user name of the job. + * [Optional] Accept rows that are missing trailing optional columns. The missing values are treated as nulls. If false, records with missing trailing columns are treated as bad records, and if there are too many bad records, an invalid error is returned in the job result. The default value is false. Only applicable to CSV, ignored for other formats. */ - jobReference?: IJobReference; + allowJaggedRows?: boolean; /** - * [Output-only] The type of the resource. + * [Optional] The separator for fields in a CSV file. The separator can be any ISO-8859-1 single-byte character. To use a character in the range 128-255, you must encode the character as UTF8. BigQuery converts the string to ISO-8859-1 encoding, and then uses the first byte of the encoded string to split the data in its raw, binary state. BigQuery also supports the escape sequence "\t" to specify a tab separator. The default value is a comma (','). */ - kind?: string; + fieldDelimiter?: string; /** - * [Output-only] A URL that can be used to access this resource again. + * If sourceFormat is set to "DATASTORE_BACKUP", indicates which entity properties to load into BigQuery from a Cloud Datastore backup. Property names are case sensitive and must be top-level properties. If no properties are specified, BigQuery loads all properties. If any named property isn't found in the Cloud Datastore backup, an invalid error is returned in the job result. */ - selfLink?: string; + projectionFields?: Array; /** - * [Output-only] Information about the job, including starting time and ending time of the job. + * Indicates if BigQuery should allow quoted data sections that contain newline characters in a CSV file. The default value is false. */ - statistics?: IJobStatistics; + allowQuotedNewlines?: boolean; /** - * [Output-only] The status of this job. Examine this value when polling an asynchronous job to see if the job is complete. + * [Optional] If sourceFormat is set to "AVRO", indicates whether to enable interpreting logical types into their corresponding types (ie. TIMESTAMP), instead of only using their raw types (ie. INTEGER). */ - status?: IJobStatus; + useAvroLogicalTypes?: boolean; /** - * [Output-only] Email address of the user who ran the job. + * [Optional] The number of rows at the top of a CSV file that BigQuery will skip when loading the data. The default value is 0. This property is useful if you have header rows in the file that should be skipped. */ - user_email?: string; - }; - - type IJobCancelResponse = { + skipLeadingRows?: number; /** - * The final state of the job. + * Time-based partitioning specification for the destination table. Only one of timePartitioning and rangePartitioning should be specified. */ - job?: IJob; + timePartitioning?: ITimePartitioning; /** - * The resource type of the response. + * [Optional] Indicates if we should automatically infer the options and schema for CSV and JSON sources. */ - kind?: string; + autodetect?: boolean; }; - type IJobConfiguration = { + type IExternalDataConfiguration = { /** - * [Pick one] Copies a table. + * [Required] The fully-qualified URIs that point to your data in Google Cloud. For Google Cloud Storage URIs: Each URI can contain one '*' wildcard character and it must come after the 'bucket' name. Size limits related to load jobs apply to external data sources. For Google Cloud Bigtable URIs: Exactly one URI can be specified and it has be a fully specified and valid HTTPS URL for a Google Cloud Bigtable table. For Google Cloud Datastore backups, exactly one URI can be specified. Also, the '*' wildcard character is not allowed. */ - copy?: IJobConfigurationTableCopy; + sourceUris?: Array; /** - * [Optional] If set, don't actually run this job. A valid query will return a mostly empty response with some processing statistics, while an invalid query will return the same error it would if it wasn't a dry run. Behavior of non-query jobs is undefined. + * [Optional] The maximum number of bad records that BigQuery can ignore when reading data. If the number of bad records exceeds this value, an invalid error is returned in the job result. This is only valid for CSV, JSON, and Google Sheets. The default value is 0, which requires that all records are valid. This setting is ignored for Google Cloud Bigtable, Google Cloud Datastore backups and Avro formats. */ - dryRun?: boolean; + maxBadRecords?: number; /** - * [Pick one] Configures an extract job. + * [Optional] Additional options if sourceFormat is set to GOOGLE_SHEETS. */ - extract?: IJobConfigurationExtract; + googleSheetsOptions?: IGoogleSheetsOptions; /** - * [Optional] Job timeout in milliseconds. If this time limit is exceeded, BigQuery may attempt to terminate the job. + * Try to detect schema and format options automatically. Any option specified explicitly will be honored. */ - jobTimeoutMs?: string; + autodetect?: boolean; /** - * [Output-only] The type of the job. Can be QUERY, LOAD, EXTRACT, COPY or UNKNOWN. + * [Optional] Indicates if BigQuery should allow extra values that are not represented in the table schema. If true, the extra values are ignored. If false, records with extra columns are treated as bad records, and if there are too many bad records, an invalid error is returned in the job result. The default value is false. The sourceFormat property determines what BigQuery treats as an extra value: CSV: Trailing columns JSON: Named values that don't match any column names Google Cloud Bigtable: This setting is ignored. Google Cloud Datastore backups: This setting is ignored. Avro: This setting is ignored. */ - jobType?: string; + ignoreUnknownValues?: boolean; /** - * The labels associated with this job. You can use these to organize and group your jobs. Label keys and values can be no longer than 63 characters, can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. Label values are optional. Label keys must start with a letter and each label in the list must have a different key. + * [Required] The data format. For CSV files, specify "CSV". For Google sheets, specify "GOOGLE_SHEETS". For newline-delimited JSON, specify "NEWLINE_DELIMITED_JSON". For Avro files, specify "AVRO". For Google Cloud Datastore backups, specify "DATASTORE_BACKUP". [Beta] For Google Cloud Bigtable, specify "BIGTABLE". */ - labels?: { [key: string]: string }; + sourceFormat?: string; /** - * [Pick one] Configures a load job. + * Additional properties to set if sourceFormat is set to CSV. */ - load?: IJobConfigurationLoad; + csvOptions?: ICsvOptions; /** - * [Pick one] Configures a query job. + * [Optional] Additional options if sourceFormat is set to BIGTABLE. */ - query?: IJobConfigurationQuery; - }; - - type IJobConfigurationExtract = { + bigtableOptions?: IBigtableOptions; /** - * [Optional] The compression type to use for exported files. Possible values include GZIP, DEFLATE, SNAPPY, and NONE. The default value is NONE. DEFLATE and SNAPPY are only supported for Avro. + * [Optional] The compression type of the data source. Possible values include GZIP and NONE. The default value is NONE. This setting is ignored for Google Cloud Bigtable, Google Cloud Datastore backups and Avro formats. */ compression?: string; /** - * [Optional] The exported file format. Possible values include CSV, NEWLINE_DELIMITED_JSON and AVRO. The default value is CSV. Tables with nested or repeated fields cannot be exported as CSV. - */ - destinationFormat?: string; - /** - * [Pick one] DEPRECATED: Use destinationUris instead, passing only one URI as necessary. The fully-qualified Google Cloud Storage URI where the extracted table should be written. - */ - destinationUri?: string; - /** - * [Pick one] A list of fully-qualified Google Cloud Storage URIs where the extracted table should be written. - */ - destinationUris?: Array; - /** - * [Optional] Delimiter to use between fields in the exported data. Default is ',' - */ - fieldDelimiter?: string; - /** - * [Optional] Whether to print out a header row in the results. Default is true. + * [Optional] The schema for the data. Schema is required for CSV and JSON formats. Schema is disallowed for Google Cloud Bigtable, Cloud Datastore backups, and Avro formats. */ - printHeader?: boolean; + schema?: ITableSchema; /** - * [Required] A reference to the table being exported. + * [Optional, Experimental] If hive partitioning is enabled, which mode to use. Two modes are supported: - AUTO: automatically infer partition key name(s) and type(s). - STRINGS: automatic infer partition key name(s). All types are strings. Not all storage formats support hive partitioning -- requesting hive partitioning on an unsupported format will lead to an error. */ - sourceTable?: ITableReference; + hivePartitioningMode?: string; }; - type IJobConfigurationLoad = { - /** - * [Optional] Accept rows that are missing trailing optional columns. The missing values are treated as nulls. If false, records with missing trailing columns are treated as bad records, and if there are too many bad records, an invalid error is returned in the job result. The default value is false. Only applicable to CSV, ignored for other formats. - */ - allowJaggedRows?: boolean; - /** - * Indicates if BigQuery should allow quoted data sections that contain newline characters in a CSV file. The default value is false. - */ - allowQuotedNewlines?: boolean; - /** - * [Optional] Indicates if we should automatically infer the options and schema for CSV and JSON sources. - */ - autodetect?: boolean; - /** - * [Beta] Clustering specification for the destination table. Must be specified with time-based partitioning, data in the table will be first partitioned and subsequently clustered. - */ - clustering?: IClustering; - /** - * [Optional] Specifies whether the job is allowed to create new tables. The following values are supported: CREATE_IF_NEEDED: If the table does not exist, BigQuery creates the table. CREATE_NEVER: The table must already exist. If it does not, a 'notFound' error is returned in the job result. The default value is CREATE_IF_NEEDED. Creation, truncation and append actions occur as one atomic update upon job completion. - */ - createDisposition?: string; - /** - * Custom encryption configuration (e.g., Cloud KMS keys). - */ - destinationEncryptionConfiguration?: IEncryptionConfiguration; - /** - * [Required] The destination table to load the data into. - */ - destinationTable?: ITableReference; + type IGoogleSheetsOptions = { /** - * [Beta] [Optional] Properties with which to create the destination table if it is new. + * [Beta] [Optional] Range of a sheet to query from. Only used when non-empty. Typical format: sheet_name!top_left_cell_id:bottom_right_cell_id For example: sheet1!A1:B20 */ - destinationTableProperties?: IDestinationTableProperties; + range?: string; /** - * [Optional] The character encoding of the data. The supported values are UTF-8 or ISO-8859-1. The default value is UTF-8. BigQuery decodes the data after the raw, binary data has been split using the values of the quote and fieldDelimiter properties. + * [Optional] The number of rows at the top of a sheet that BigQuery will skip when reading the data. The default value is 0. This property is useful if you have header rows that should be skipped. When autodetect is on, behavior is the following: * skipLeadingRows unspecified - Autodetect tries to detect headers in the first row. If they are not detected, the row is read as data. Otherwise data is read starting from the second row. * skipLeadingRows is 0 - Instructs autodetect that there are no headers and data should be read starting from the first row. * skipLeadingRows = N > 0 - Autodetect skips N-1 rows and tries to detect headers in row N. If headers are not detected, row N is just skipped. Otherwise row N is used to extract column names for the detected schema. */ - encoding?: string; + skipLeadingRows?: string; + }; + + type ITableDataInsertAllRequest = { /** - * [Optional] The separator for fields in a CSV file. The separator can be any ISO-8859-1 single-byte character. To use a character in the range 128-255, you must encode the character as UTF8. BigQuery converts the string to ISO-8859-1 encoding, and then uses the first byte of the encoded string to split the data in its raw, binary state. BigQuery also supports the escape sequence "\t" to specify a tab separator. The default value is a comma (','). + * The resource type of the response. */ - fieldDelimiter?: string; + kind?: string; /** - * [Optional, Experimental] If hive partitioning is enabled, which mode to use. Two modes are supported: - AUTO: automatically infer partition key name(s) and type(s). - STRINGS: automatic infer partition key name(s). All types are strings. Not all storage formats support hive partitioning -- requesting hive partitioning on an unsupported format will lead to an error. + * If specified, treats the destination table as a base template, and inserts the rows into an instance table named "{destination}{templateSuffix}". BigQuery will manage creation of the instance table, using the schema of the base template table. See https://cloud.google.com/bigquery/streaming-data-into-bigquery#template-tables for considerations when working with templates tables. */ - hivePartitioningMode?: string; + templateSuffix?: string; /** - * [Optional] Indicates if BigQuery should allow extra values that are not represented in the table schema. If true, the extra values are ignored. If false, records with extra columns are treated as bad records, and if there are too many bad records, an invalid error is returned in the job result. The default value is false. The sourceFormat property determines what BigQuery treats as an extra value: CSV: Trailing columns JSON: Named values that don't match any column names + * [Optional] Accept rows that contain values that do not match the schema. The unknown values are ignored. Default is false, which treats unknown values as errors. */ ignoreUnknownValues?: boolean; /** - * [Optional] The maximum number of bad records that BigQuery can ignore when running the job. If the number of bad records exceeds this value, an invalid error is returned in the job result. This is only valid for CSV and JSON. The default value is 0, which requires that all records are valid. - */ - maxBadRecords?: number; - /** - * [Optional] Specifies a string that represents a null value in a CSV file. For example, if you specify "\N", BigQuery interprets "\N" as a null value when loading a CSV file. The default value is the empty string. If you set this property to a custom value, BigQuery throws an error if an empty string is present for all data types except for STRING and BYTE. For STRING and BYTE columns, BigQuery interprets the empty string as an empty value. - */ - nullMarker?: string; - /** - * If sourceFormat is set to "DATASTORE_BACKUP", indicates which entity properties to load into BigQuery from a Cloud Datastore backup. Property names are case sensitive and must be top-level properties. If no properties are specified, BigQuery loads all properties. If any named property isn't found in the Cloud Datastore backup, an invalid error is returned in the job result. - */ - projectionFields?: Array; - /** - * [Optional] The value that is used to quote data sections in a CSV file. BigQuery converts the string to ISO-8859-1 encoding, and then uses the first byte of the encoded string to split the data in its raw, binary state. The default value is a double-quote ('"'). If your data does not contain quoted sections, set the property value to an empty string. If your data contains quoted newline characters, you must also set the allowQuotedNewlines property to true. - */ - quote?: string; - /** - * [TrustedTester] Range partitioning specification for this table. Only one of timePartitioning and rangePartitioning should be specified. + * [Optional] Insert all valid rows of a request, even if invalid rows exist. The default value is false, which causes the entire request to fail if any invalid rows exist. */ - rangePartitioning?: IRangePartitioning; + skipInvalidRows?: boolean; /** - * [Optional] The schema for the destination table. The schema can be omitted if the destination table already exists, or if you're loading data from Google Cloud Datastore. + * The rows to insert. */ - schema?: ITableSchema; + rows?: Array<{ + /** + * [Optional] A unique ID for each row. BigQuery uses this property to detect duplicate insertion requests on a best-effort basis. + */ + insertId?: string; + /** + * [Required] A JSON object that contains a row of data. The object's properties and values must match the destination table's schema. + */ + json?: IJsonObject; + }>; + }; + + type ITableList = { /** - * [Deprecated] The inline schema. For CSV schemas, specify as "Field1:Type1[,Field2:Type2]*". For example, "foo:STRING, bar:INTEGER, baz:FLOAT". + * The total number of tables in the dataset. */ - schemaInline?: string; + totalItems?: number; /** - * [Deprecated] The format of the schemaInline property. + * The type of list. */ - schemaInlineFormat?: string; + kind?: string; /** - * Allows the schema of the destination table to be updated as a side effect of the load job if a schema is autodetected or supplied in the job configuration. Schema update options are supported in two cases: when writeDisposition is WRITE_APPEND; when writeDisposition is WRITE_TRUNCATE and the destination table is a partition of a table, specified by partition decorators. For normal tables, WRITE_TRUNCATE will always overwrite the schema. One or more of the following values are specified: ALLOW_FIELD_ADDITION: allow adding a nullable field to the schema. ALLOW_FIELD_RELAXATION: allow relaxing a required field in the original schema to nullable. + * Tables in the requested dataset. */ - schemaUpdateOptions?: Array; + tables?: Array<{ + /** + * Additional details for a view. + */ + view?: { + /** + * True if view is defined in legacy SQL dialect, false if in standard SQL. + */ + useLegacySql?: boolean; + }; + /** + * The time when this table was created, in milliseconds since the epoch. + */ + creationTime?: string; + /** + * The labels associated with this table. You can use these to organize and group your tables. + */ + labels?: { [key: string]: string }; + /** + * The type of table. Possible values are: TABLE, VIEW. + */ + type?: string; + /** + * [Beta] Clustering specification for this table, if configured. + */ + clustering?: IClustering; + /** + * An opaque ID of the table + */ + id?: string; + /** + * [Optional] The time when this table expires, in milliseconds since the epoch. If not present, the table will persist indefinitely. Expired tables will be deleted and their storage reclaimed. + */ + expirationTime?: string; + /** + * A reference uniquely identifying the table. + */ + tableReference?: ITableReference; + /** + * The user-friendly name for this table. + */ + friendlyName?: string; + /** + * The time-based partitioning specification for this table, if configured. + */ + timePartitioning?: ITimePartitioning; + /** + * The resource type. + */ + kind?: string; + }>; + /** + * A hash of this page of results. + */ + etag?: string; + /** + * A token to request the next page of results. + */ + nextPageToken?: string; + }; + + type IBigtableColumn = { + /** + * [Optional] If the qualifier is not a valid BigQuery field identifier i.e. does not match [a-zA-Z][a-zA-Z0-9_]*, a valid identifier must be provided as the column field name and is used as field name in queries. + */ + fieldName?: string; + qualifierString?: string; + /** + * [Optional] The encoding of the values when the type is not STRING. Acceptable encoding values are: TEXT - indicates values are alphanumeric text strings. BINARY - indicates values are encoded using HBase Bytes.toBytes family of functions. 'encoding' can also be set at the column family level. However, the setting at this level takes precedence if 'encoding' is set at both levels. + */ + encoding?: string; + /** + * [Optional] The type to convert the value in cells of this column. The values are expected to be encoded using HBase Bytes.toBytes function when using the BINARY encoding value. Following BigQuery types are allowed (case-sensitive) - BYTES STRING INTEGER FLOAT BOOLEAN Default type is BYTES. 'type' can also be set at the column family level. However, the setting at this level takes precedence if 'type' is set at both levels. + */ + type?: string; + /** + * [Optional] If this is set, only the latest version of value in this column are exposed. 'onlyReadLatest' can also be set at the column family level. However, the setting at this level takes precedence if 'onlyReadLatest' is set at both levels. + */ + onlyReadLatest?: boolean; + /** + * [Required] Qualifier of the column. Columns in the parent column family that has this exact qualifier are exposed as . field. If the qualifier is valid UTF-8 string, it can be specified in the qualifier_string field. Otherwise, a base-64 encoded value must be set to qualifier_encoded. The column field name is the same as the column qualifier. However, if the qualifier is not a valid BigQuery field identifier i.e. does not match [a-zA-Z][a-zA-Z0-9_]*, a valid identifier must be provided as field_name. + */ + qualifierEncoded?: string; + }; + + type ITableFieldSchema = { + /** + * [Required] The field name. The name must contain only letters (a-z, A-Z), numbers (0-9), or underscores (_), and must start with a letter or underscore. The maximum length is 128 characters. + */ + name?: string; + /** + * [Required] The field data type. Possible values include STRING, BYTES, INTEGER, INT64 (same as INTEGER), FLOAT, FLOAT64 (same as FLOAT), BOOLEAN, BOOL (same as BOOLEAN), TIMESTAMP, DATE, TIME, DATETIME, RECORD (where RECORD indicates that the field contains a nested schema) or STRUCT (same as RECORD). + */ + type?: string; + /** + * [Optional] The categories attached to this field, used for field-level access control. + */ + categories?: { + /** + * A list of category resource names. For example, "projects/1/taxonomies/2/categories/3". At most 5 categories are allowed. + */ + names?: Array; + }; + /** + * [Optional] The field mode. Possible values include NULLABLE, REQUIRED and REPEATED. The default value is NULLABLE. + */ + mode?: string; + /** + * [Optional] The field description. The maximum length is 1,024 characters. + */ + description?: string; + /** + * [Optional] Describes the nested schema fields if the type property is set to RECORD. + */ + fields?: Array; + }; + + type IBqmlIterationResult = { + /** + * [Output-only, Beta] Eval loss computed on the eval data at the end of the iteration. The eval loss is used for early stopping to avoid overfitting. No eval loss if eval_split_method option is specified as no_split or auto_split with input data size less than 500 rows. + */ + evalLoss?: number; + /** + * [Output-only, Beta] Index of the ML training iteration, starting from zero for each training run. + */ + index?: number; + /** + * [Output-only, Beta] Learning rate used for this iteration, it varies for different training iterations if learn_rate_strategy option is not constant. + */ + learnRate?: number; + /** + * [Output-only, Beta] Time taken to run the training iteration in milliseconds. + */ + durationMs?: string; + /** + * [Output-only, Beta] Training loss computed on the training data at the end of the iteration. The training loss function is defined by model type. + */ + trainingLoss?: number; + }; + + /** + * Evaluation metrics for clustering models. + */ + type IClusteringMetrics = { + /** + * Mean of squared distances between each sample to its cluster centroid. + */ + meanSquaredDistance?: number; + /** + * Davies-Bouldin index. + */ + daviesBouldinIndex?: number; + }; + + type ITableDataInsertAllResponse = { + /** + * An array of errors for rows that were not inserted. + */ + insertErrors?: Array<{ + /** + * Error information for the row indicated by the index property. + */ + errors?: Array; + /** + * The index of the row that error applies to. + */ + index?: number; + }>; + /** + * The resource type of the response. + */ + kind?: string; + }; + + type IGetServiceAccountResponse = { + /** + * The service account email address. + */ + email?: string; + /** + * The resource type of the response. + */ + kind?: string; + }; + + type IDataset = { + /** + * [Optional] An array of objects that define dataset access for one or more entities. You can set this property when inserting or updating a dataset in order to control who is allowed to access the data. If unspecified at dataset creation time, BigQuery adds default dataset access for the following entities: access.specialGroup: projectReaders; access.role: READER; access.specialGroup: projectWriters; access.role: WRITER; access.specialGroup: projectOwners; access.role: OWNER; access.userByEmail: [dataset creator email]; access.role: OWNER; + */ + access?: Array<{ + /** + * [Pick one] A view from a different dataset to grant access to. Queries executed against that view will have read access to tables in this dataset. The role field is not required when this field is set. If that view is updated by any user, access to the view needs to be granted again via an update operation. + */ + view?: ITableReference; + /** + * [Pick one] An email address of a Google Group to grant access to. Maps to IAM policy member "group:GROUP". + */ + groupByEmail?: string; + /** + * [Pick one] An email address of a user to grant access to. For example: fred@example.com. Maps to IAM policy member "user:EMAIL" or "serviceAccount:EMAIL". + */ + userByEmail?: string; + /** + * [Pick one] A domain to grant access to. Any users signed in with the domain specified will be granted the specified access. Example: "example.com". Maps to IAM policy member "domain:DOMAIN". + */ + domain?: string; + /** + * [Pick one] Some other type of member that appears in the IAM Policy but isn't a user, group, domain, or special group. + */ + iamMember?: string; + /** + * [Pick one] A special group to grant access to. Possible values include: projectOwners: Owners of the enclosing project. projectReaders: Readers of the enclosing project. projectWriters: Writers of the enclosing project. allAuthenticatedUsers: All authenticated BigQuery users. Maps to similarly-named IAM members. + */ + specialGroup?: string; + /** + * [Required] An IAM role ID that should be granted to the user, group, or domain specified in this access entry. The following legacy mappings will be applied: OWNER roles/bigquery.dataOwner WRITER roles/bigquery.dataEditor READER roles/bigquery.dataViewer This field will accept any of the above formats, but will return only the legacy format. For example, if you set this field to "roles/bigquery.dataOwner", it will be returned back as "OWNER". + */ + role?: string; + }>; + /** + * [Output-only] The resource type. + */ + kind?: string; + /** + * [Optional] A user-friendly description of the dataset. + */ + description?: string; + /** + * [Optional] The default lifetime of all tables in the dataset, in milliseconds. The minimum value is 3600000 milliseconds (one hour). Once this property is set, all newly-created tables in the dataset will have an expirationTime property set to the creation time plus the value in this property, and changing the value will only affect new tables, not existing ones. When the expirationTime for a given table is reached, that table will be deleted automatically. If a table's expirationTime is modified or removed before the table expires, or if you provide an explicit expirationTime when creating a table, that value takes precedence over the default expiration time indicated by this property. + */ + defaultTableExpirationMs?: string; + /** + * [Output-only] A hash of the resource. + */ + etag?: string; + /** + * [Output-only] The time when this dataset was created, in milliseconds since the epoch. + */ + creationTime?: string; + /** + * [Required] A reference that identifies the dataset. + */ + datasetReference?: IDatasetReference; + /** + * [Output-only] The fully-qualified unique name of the dataset in the format projectId:datasetId. The dataset name without the project name is given in the datasetId field. When creating a new dataset, leave this field blank, and instead specify the datasetId field. + */ + id?: string; + /** + * The geographic location where the dataset should reside. The default value is US. See details at https://cloud.google.com/bigquery/docs/locations. + */ + location?: string; + /** + * [Optional] A descriptive name for the dataset. + */ + friendlyName?: string; + /** + * [Output-only] The date when this dataset or any of its tables was last modified, in milliseconds since the epoch. + */ + lastModifiedTime?: string; + /** + * The labels associated with this dataset. You can use these to organize and group your datasets. You can set this property when inserting or updating a dataset. See Creating and Updating Dataset Labels for more information. + */ + labels?: { [key: string]: string }; + /** + * [Output-only] A URL that can be used to access the resource again. You can use this URL in Get or Update requests to the resource. + */ + selfLink?: string; + /** + * [Optional] The default partition expiration for all partitioned tables in the dataset, in milliseconds. Once this property is set, all newly-created partitioned tables in the dataset will have an expirationMs property in the timePartitioning settings set to this value, and changing the value will only affect new tables, not existing ones. The storage in a partition will have an expiration time of its partition time plus this value. Setting this property overrides the use of defaultTableExpirationMs for partitioned tables: only one of defaultTableExpirationMs and defaultPartitionExpirationMs will be used for any new partitioned table. If you provide an explicit timePartitioning.expirationMs when creating or updating a partitioned table, that value takes precedence over the default partition expiration time indicated by this property. + */ + defaultPartitionExpirationMs?: string; + }; + + type IDatasetReference = { + /** + * [Optional] The ID of the project containing this dataset. + */ + projectId?: string; + /** + * [Required] A unique ID for this dataset, without the project name. The ID must contain only letters (a-z, A-Z), numbers (0-9), or underscores (_). The maximum length is 1,024 characters. + */ + datasetId?: string; + }; + + type IModelDefinition = { + /** + * [Output-only, Beta] Model options used for the first training run. These options are immutable for subsequent training runs. Default values are used for any options not specified in the input query. + */ + modelOptions?: { + labels?: Array; + lossType?: string; + modelType?: string; + }; /** - * [Optional] The number of rows at the top of a CSV file that BigQuery will skip when loading the data. The default value is 0. This property is useful if you have header rows in the file that should be skipped. + * [Output-only, Beta] Information about ml training runs, each training run comprises of multiple iterations and there may be multiple training runs for the model if warm start is used or if a user decides to continue a previously cancelled query. */ - skipLeadingRows?: number; + trainingRuns?: Array; + }; + + type IJobStatus = { /** - * [Optional] The format of the data files. For CSV files, specify "CSV". For datastore backups, specify "DATASTORE_BACKUP". For newline-delimited JSON, specify "NEWLINE_DELIMITED_JSON". For Avro, specify "AVRO". For parquet, specify "PARQUET". For orc, specify "ORC". The default value is CSV. + * [Output-only] The first errors encountered during the running of the job. The final message includes the number of errors that caused the process to stop. Errors here do not necessarily mean that the job has completed or was unsuccessful. */ - sourceFormat?: string; + errors?: Array; /** - * [Required] The fully-qualified URIs that point to your data in Google Cloud. For Google Cloud Storage URIs: Each URI can contain one '*' wildcard character and it must come after the 'bucket' name. Size limits related to load jobs apply to external data sources. For Google Cloud Bigtable URIs: Exactly one URI can be specified and it has be a fully specified and valid HTTPS URL for a Google Cloud Bigtable table. For Google Cloud Datastore backups: Exactly one URI can be specified. Also, the '*' wildcard character is not allowed. + * [Output-only] Running state of the job. */ - sourceUris?: Array; + state?: string; /** - * Time-based partitioning specification for the destination table. Only one of timePartitioning and rangePartitioning should be specified. + * [Output-only] Final error result of the job. If present, indicates that the job has completed and was unsuccessful. */ - timePartitioning?: ITimePartitioning; + errorResult?: IErrorProto; + }; + + type IListModelsResponse = { /** - * [Optional] If sourceFormat is set to "AVRO", indicates whether to enable interpreting logical types into their corresponding types (ie. TIMESTAMP), instead of only using their raw types (ie. INTEGER). + * Models in the requested dataset. Only the following fields are populated: + * model_reference, model_type, creation_time, last_modified_time and + * labels. */ - useAvroLogicalTypes?: boolean; + models?: Array; /** - * [Optional] Specifies the action that occurs if the destination table already exists. The following values are supported: WRITE_TRUNCATE: If the table already exists, BigQuery overwrites the table data. WRITE_APPEND: If the table already exists, BigQuery appends the data to the table. WRITE_EMPTY: If the table already exists and contains data, a 'duplicate' error is returned in the job result. The default value is WRITE_APPEND. Each action is atomic and only occurs if BigQuery is able to complete the job successfully. Creation, truncation and append actions occur as one atomic update upon job completion. + * A token to request the next page of results. */ - writeDisposition?: string; + nextPageToken?: string; }; - type IJobConfigurationQuery = { + type IJobStatistics3 = { /** - * [Optional] If true and query uses legacy SQL dialect, allows the query to produce arbitrarily large result tables at a slight cost in performance. Requires destinationTable to be set. For standard SQL queries, this flag is ignored and large results are always allowed. However, you must still set destinationTable when result size exceeds the allowed maximum response size. + * [Output-only] The number of bad records encountered. Note that if the job has failed because of more bad records encountered than the maximum allowed in the load job configuration, then this number can be less than the total number of bad records present in the input data. */ - allowLargeResults?: boolean; + badRecords?: string; /** - * [Beta] Clustering specification for the destination table. Must be specified with time-based partitioning, data in the table will be first partitioned and subsequently clustered. + * [Output-only] Number of bytes of source data in a load job. + */ + inputFileBytes?: string; + /** + * [Output-only] Number of source files in a load job. + */ + inputFiles?: string; + /** + * [Output-only] Number of rows imported in a load job. Note that while an import job is in the running state, this value may change. + */ + outputRows?: string; + /** + * [Output-only] Size of the loaded data in bytes. Note that while a load job is in the running state, this value may change. + */ + outputBytes?: string; + }; + + /** + * A field or a column. + */ + type IStandardSqlField = { + /** + * Optional. The name of this field. Can be absent for struct fields. + */ + name?: string; + /** + * Optional. The type of this parameter. Absent if not explicitly + * specified (e.g., CREATE FUNCTION statement can omit the return type; + * in this case the output parameter does not have this "type" field). + */ + type?: IStandardSqlDataType; + }; + + /** + * Evaluation metrics of a model. These are either computed on all training + * data or just the eval data based on whether eval data was used during + * training. These are not present for imported models. + */ + type IEvaluationMetrics = { + /** + * Populated for binary classification/classifier models. + */ + binaryClassificationMetrics?: IBinaryClassificationMetrics; + /** + * Populated for regression models. + */ + regressionMetrics?: IRegressionMetrics; + /** + * Populated for multi-class classification/classifier models. + */ + multiClassClassificationMetrics?: IMultiClassClassificationMetrics; + /** + * [Beta] Populated for clustering models. + */ + clusteringMetrics?: IClusteringMetrics; + }; + + /** + * A single entry in the confusion matrix. + */ + type IEntry = { + /** + * The predicted label. For confidence_threshold > 0, we will + * also add an entry indicating the number of items under the + * confidence threshold. + */ + predictedLabel?: string; + /** + * Number of items being predicted as this label. + */ + itemCount?: string; + }; + + type IStreamingbuffer = { + /** + * [Output-only] A lower-bound estimate of the number of bytes currently in the streaming buffer. + */ + estimatedBytes?: string; + /** + * [Output-only] A lower-bound estimate of the number of rows currently in the streaming buffer. + */ + estimatedRows?: string; + /** + * [Output-only] Contains the timestamp of the oldest entry in the streaming buffer, in milliseconds since the epoch, if the streaming buffer is available. + */ + oldestEntryTime?: string; + }; + + type ITable = { + /** + * [Output-only] The number of rows of data in this table, excluding any data in the streaming buffer. + */ + numRows?: string; + /** + * [Beta] Clustering specification for the table. Must be specified with partitioning, data in the table will be first partitioned and subsequently clustered. */ clustering?: IClustering; /** - * [Optional] Specifies whether the job is allowed to create new tables. The following values are supported: CREATE_IF_NEEDED: If the table does not exist, BigQuery creates the table. CREATE_NEVER: The table must already exist. If it does not, a 'notFound' error is returned in the job result. The default value is CREATE_IF_NEEDED. Creation, truncation and append actions occur as one atomic update upon job completion. + * [Output-only] Describes the table type. The following values are supported: TABLE: A normal BigQuery table. VIEW: A virtual table defined by a SQL query. [TrustedTester] MATERIALIZED_VIEW: SQL query whose result is persisted. EXTERNAL: A table that references data stored in an external storage system, such as Google Cloud Storage. The default value is TABLE. + */ + type?: string; + /** + * [Optional] The view definition. + */ + view?: IViewDefinition; + /** + * [Output-only] The number of bytes in the table that are considered "long-term storage". + */ + numLongTermBytes?: string; + /** + * [Output-only] A hash of the table metadata. Used to ensure there were no concurrent modifications to the resource when attempting an update. Not guaranteed to change when the table contents or the fields numRows, numBytes, numLongTermBytes or lastModifiedTime change. + */ + etag?: string; + /** + * Custom encryption configuration (e.g., Cloud KMS keys). + */ + encryptionConfiguration?: IEncryptionConfiguration; + /** + * [Output-only] Contains information regarding this table's streaming buffer, if one is present. This field will be absent if the table is not being streamed to or if there is no data in the streaming buffer. + */ + streamingBuffer?: IStreamingbuffer; + /** + * [Output-only] The geographic location where the table resides. This value is inherited from the dataset. + */ + location?: string; + /** + * [Output-only] The size of this table in bytes, excluding any data in the streaming buffer. + */ + numBytes?: string; + /** + * Time-based partitioning specification for this table. Only one of timePartitioning and rangePartitioning should be specified. + */ + timePartitioning?: ITimePartitioning; + /** + * [Optional] A descriptive name for this table. + */ + friendlyName?: string; + /** + * The labels associated with this table. You can use these to organize and group your tables. Label keys and values can be no longer than 63 characters, can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. Label values are optional. Label keys must start with a letter and each label in the list must have a different key. + */ + labels?: { [key: string]: string }; + /** + * [Output-only] [TrustedTester] The physical size of this table in bytes, excluding any data in the streaming buffer. This includes compression and storage used for time travel. + */ + numPhysicalBytes?: string; + /** + * [Optional] Describes the data format, location, and other properties of a table stored outside of BigQuery. By defining these properties, the data source can then be queried as if it were a standard BigQuery table. + */ + externalDataConfiguration?: IExternalDataConfiguration; + /** + * [Output-only] A URL that can be used to access this resource again. + */ + selfLink?: string; + /** + * [Output-only, Beta] Present iff this table represents a ML model. Describes the training information for the model, and it is required to run 'PREDICT' queries. + */ + model?: IModelDefinition; + /** + * [Optional] The time when this table expires, in milliseconds since the epoch. If not present, the table will persist indefinitely. Expired tables will be deleted and their storage reclaimed. The defaultTableExpirationMs property of the encapsulating dataset can be used to set a default expirationTime on newly created tables. + */ + expirationTime?: string; + /** + * [Optional] A user-friendly description of this table. + */ + description?: string; + /** + * [Output-only] The type of the resource. + */ + kind?: string; + /** + * [Output-only] The time when this table was created, in milliseconds since the epoch. + */ + creationTime?: string; + /** + * [TrustedTester] Range partitioning specification for this table. Only one of timePartitioning and rangePartitioning should be specified. + */ + rangePartitioning?: IRangePartitioning; + /** + * [Optional] Describes the schema of this table. + */ + schema?: ITableSchema; + /** + * [Output-only] An opaque ID uniquely identifying the table. + */ + id?: string; + /** + * [Beta] [Optional] If set to true, queries over this table require a partition filter that can be used for partition elimination to be specified. + */ + requirePartitionFilter?: boolean; + /** + * [Optional] Materialized view definition. + */ + materializedView?: IMaterializedViewDefinition; + /** + * [Required] Reference describing the ID of this table. + */ + tableReference?: ITableReference; + /** + * [Output-only] The time when this table was last modified, in milliseconds since the epoch. + */ + lastModifiedTime?: string; + }; + + /** + * Confusion matrix for multi-class classification models. + */ + type IConfusionMatrix = { + /** + * Confidence threshold used when computing the entries of the + * confusion matrix. + */ + confidenceThreshold?: number; + /** + * One row per actual label. + */ + rows?: Array; + }; + + type ITableCell = { v?: any }; + + type IMaterializedViewDefinition = { + /** + * [Output-only] [TrustedTester] The time when this materialized view was last modified, in milliseconds since the epoch. + */ + lastRefreshTime?: string; + /** + * [Required] A query whose result is persisted. + */ + query?: string; + }; + + type ITableReference = { + /** + * [Required] The ID of the project containing this table. + */ + projectId?: string; + /** + * [Required] The ID of the dataset containing this table. + */ + datasetId?: string; + /** + * [Required] The ID of the table. The ID must contain only letters (a-z, A-Z), numbers (0-9), or underscores (_). The maximum length is 1,024 characters. + */ + tableId?: string; + }; + + type IQueryParameterValue = { + /** + * [Optional] The struct field values, in order of the struct type's declaration. + */ + structValues?: { [key: string]: IQueryParameterValue }; + /** + * [Optional] The array values, if this is an array type. */ - createDisposition?: string; + arrayValues?: Array; /** - * [Optional] Specifies the default dataset to use for unqualified table names in the query. Note that this does not alter behavior of unqualified dataset names. + * [Optional] The value of this value, if a simple scalar type. */ - defaultDataset?: IDatasetReference; + value?: string; + }; + + type IModel = { /** - * Custom encryption configuration (e.g., Cloud KMS keys). + * Output only. The geographic location where the model resides. This value + * is inherited from the dataset. */ - destinationEncryptionConfiguration?: IEncryptionConfiguration; + location?: string; /** - * [Optional] Describes the table where the query results should be stored. If not present, a new table will be created to store the results. This property must be set for large results that exceed the maximum response size. + * [Optional] A descriptive name for this model. + * @mutable bigquery.models.patch */ - destinationTable?: ITableReference; + friendlyName?: string; /** - * [Optional] If true and query uses legacy SQL dialect, flattens all nested and repeated fields in the query results. allowLargeResults must be true if this is set to false. For standard SQL queries, this flag is ignored and results are never flattened. + * Output only. The time when this model was last modified, in millisecs + * since the epoch. */ - flattenResults?: boolean; + lastModifiedTime?: string; /** - * [Optional] Limits the billing tier for this job. Queries that have resource usage beyond this tier will fail (without incurring a charge). If unspecified, this will be set to your project default. + * [Optional] The labels associated with this model. You can use these to + * organize and group your models. Label keys and values can be no longer + * than 63 characters, can only contain lowercase letters, numeric + * characters, underscores and dashes. International characters are allowed. + * Label values are optional. Label keys must start with a letter and each + * label in the list must have a different key. + * @mutable bigquery.models.patch */ - maximumBillingTier?: number; + labels?: { [key: string]: string }; /** - * [Optional] Limits the bytes billed for this job. Queries that will have bytes billed beyond this limit will fail (without incurring a charge). If unspecified, this will be set to your project default. + * Output only. Label columns that were used to train this model. + * The output of the model will have a "predicted_" prefix to these columns. */ - maximumBytesBilled?: string; + labelColumns?: Array; /** - * Standard SQL only. Set to POSITIONAL to use positional (?) query parameters or to NAMED to use named (@myparam) query parameters in this query. + * Output only. Type of the model resource. */ - parameterMode?: string; + modelType?: + | 'MODEL_TYPE_UNSPECIFIED' + | 'LINEAR_REGRESSION' + | 'LOGISTIC_REGRESSION' + | 'KMEANS' + | 'TENSORFLOW'; /** - * [Deprecated] This property is deprecated. + * Output only. Input feature columns that were used to train this model. */ - preserveNulls?: boolean; + featureColumns?: Array; /** - * [Optional] Specifies a priority for the query. Possible values include INTERACTIVE and BATCH. The default value is INTERACTIVE. + * [Optional] The time when this model expires, in milliseconds since the + * epoch. If not present, the model will persist indefinitely. Expired models + * will be deleted and their storage reclaimed. The defaultTableExpirationMs + * property of the encapsulating dataset can be used to set a default + * expirationTime on newly created models. + * @mutable bigquery.models.patch */ - priority?: string; + expirationTime?: string; /** - * [Required] SQL query text to execute. The useLegacySql field can be used to indicate whether the query uses legacy SQL or standard SQL. + * Output only. Information for all training runs in increasing order of + * start_time. */ - query?: string; + trainingRuns?: Array; /** - * Query parameters for standard SQL queries. + * Required. Unique identifier for this model. */ - queryParameters?: Array; + modelReference?: IModelReference; /** - * [TrustedTester] Range partitioning specification for this table. Only one of timePartitioning and rangePartitioning should be specified. + * [Optional] A user-friendly description of this model. + * @mutable bigquery.models.patch */ - rangePartitioning?: IRangePartitioning; + description?: string; /** - * Allows the schema of the destination table to be updated as a side effect of the query job. Schema update options are supported in two cases: when writeDisposition is WRITE_APPEND; when writeDisposition is WRITE_TRUNCATE and the destination table is a partition of a table, specified by partition decorators. For normal tables, WRITE_TRUNCATE will always overwrite the schema. One or more of the following values are specified: ALLOW_FIELD_ADDITION: allow adding a nullable field to the schema. ALLOW_FIELD_RELAXATION: allow relaxing a required field in the original schema to nullable. + * Output only. A hash of this resource. */ - schemaUpdateOptions?: Array; + etag?: string; /** - * [Optional] If querying an external data source outside of BigQuery, describes the data format, location and other properties of the data source. By defining these properties, the data source can then be queried as if it were a standard BigQuery table. + * Output only. The time when this model was created, in millisecs since the + * epoch. */ - tableDefinitions?: { [key: string]: IExternalDataConfiguration }; + creationTime?: string; + }; + + type IStandardSqlStructType = { fields?: Array }; + + /** + * The type of a variable, e.g., a function argument. + * Examples: + * INT64: {type_kind="INT64"} + * ARRAY: {type_kind="ARRAY", array_element_type="STRING"} + * STRUCT>: + * {type_kind="STRUCT", + * struct_type={fields=[ + * {name="x", type={type_kind="STRING"}}, + * {name="y", type={type_kind="ARRAY", array_element_type="DATE"}} + * ]}} + */ + type IStandardSqlDataType = { + /** + * Required. The top level type of this field. + * Can be any standard SQL data type (e.g., "INT64", "DATE", "ARRAY"). + */ + typeKind?: + | 'TYPE_KIND_UNSPECIFIED' + | 'INT64' + | 'BOOL' + | 'FLOAT64' + | 'STRING' + | 'BYTES' + | 'TIMESTAMP' + | 'DATE' + | 'TIME' + | 'DATETIME' + | 'GEOGRAPHY' + | 'NUMERIC' + | 'ARRAY' + | 'STRUCT'; + /** + * The fields of this struct, in order, if type_kind = "STRUCT". + */ + structType?: IStandardSqlStructType; + /** + * The type of the array's elements, if type_kind = "ARRAY". + */ + arrayElementType?: IStandardSqlDataType; + }; + + /** + * Id path of a model. + */ + type IModelReference = { /** - * Time-based partitioning specification for the destination table. Only one of timePartitioning and rangePartitioning should be specified. + * [Required] The ID of the project containing this model. */ - timePartitioning?: ITimePartitioning; + projectId?: string; /** - * Specifies whether to use BigQuery's legacy SQL dialect for this query. The default value is true. If set to false, the query will use BigQuery's standard SQL: https://cloud.google.com/bigquery/sql-reference/ When useLegacySql is set to false, the value of flattenResults is ignored; query will be run as if flattenResults is false. + * [Required] The ID of the dataset containing this model. */ - useLegacySql?: boolean; + datasetId?: string; /** - * [Optional] Whether to look for the result in the query cache. The query cache is a best-effort cache that will be flushed whenever tables in the query are modified. Moreover, the query cache is only available when a query does not have a destination table specified. The default value is true. + * [Required] The ID of the model. The ID must contain only + * letters (a-z, A-Z), numbers (0-9), or underscores (_). The maximum + * length is 1,024 characters. */ - useQueryCache?: boolean; + modelId?: string; + }; + + type IJobStatistics4 = { /** - * Describes user-defined function resources used in the query. + * [Output-only] Number of user bytes extracted into the result. This is the byte count as computed by BigQuery for billing purposes. */ - userDefinedFunctionResources?: Array; + inputBytes?: string; /** - * [Optional] Specifies the action that occurs if the destination table already exists. The following values are supported: WRITE_TRUNCATE: If the table already exists, BigQuery overwrites the table data and uses the schema from the query result. WRITE_APPEND: If the table already exists, BigQuery appends the data to the table. WRITE_EMPTY: If the table already exists and contains data, a 'duplicate' error is returned in the job result. The default value is WRITE_EMPTY. Each action is atomic and only occurs if BigQuery is able to complete the job successfully. Creation, truncation and append actions occur as one atomic update upon job completion. + * [Output-only] Number of files per destination URI or URI pattern specified in the extract configuration. These values will be in the same order as the URIs specified in the 'destinationUris' field. */ - writeDisposition?: string; + destinationUriFileCounts?: Array; }; - type IJobConfigurationTableCopy = { + type ICsvOptions = { /** - * [Optional] Specifies whether the job is allowed to create new tables. The following values are supported: CREATE_IF_NEEDED: If the table does not exist, BigQuery creates the table. CREATE_NEVER: The table must already exist. If it does not, a 'notFound' error is returned in the job result. The default value is CREATE_IF_NEEDED. Creation, truncation and append actions occur as one atomic update upon job completion. + * [Optional] The character encoding of the data. The supported values are UTF-8 or ISO-8859-1. The default value is UTF-8. BigQuery decodes the data after the raw, binary data has been split using the values of the quote and fieldDelimiter properties. */ - createDisposition?: string; + encoding?: string; /** - * Custom encryption configuration (e.g., Cloud KMS keys). + * [Optional] Indicates if BigQuery should allow quoted data sections that contain newline characters in a CSV file. The default value is false. */ - destinationEncryptionConfiguration?: IEncryptionConfiguration; + allowQuotedNewlines?: boolean; /** - * [Required] The destination table + * [Optional] The value that is used to quote data sections in a CSV file. BigQuery converts the string to ISO-8859-1 encoding, and then uses the first byte of the encoded string to split the data in its raw, binary state. The default value is a double-quote ('"'). If your data does not contain quoted sections, set the property value to an empty string. If your data contains quoted newline characters, you must also set the allowQuotedNewlines property to true. */ - destinationTable?: ITableReference; + quote?: string; /** - * [Pick one] Source table to copy. + * [Optional] The number of rows at the top of a CSV file that BigQuery will skip when reading the data. The default value is 0. This property is useful if you have header rows in the file that should be skipped. */ - sourceTable?: ITableReference; + skipLeadingRows?: string; /** - * [Pick one] Source tables to copy. + * [Optional] Indicates if BigQuery should accept rows that are missing trailing optional columns. If true, BigQuery treats missing trailing columns as null values. If false, records with missing trailing columns are treated as bad records, and if there are too many bad records, an invalid error is returned in the job result. The default value is false. */ - sourceTables?: Array; + allowJaggedRows?: boolean; /** - * [Optional] Specifies the action that occurs if the destination table already exists. The following values are supported: WRITE_TRUNCATE: If the table already exists, BigQuery overwrites the table data. WRITE_APPEND: If the table already exists, BigQuery appends the data to the table. WRITE_EMPTY: If the table already exists and contains data, a 'duplicate' error is returned in the job result. The default value is WRITE_EMPTY. Each action is atomic and only occurs if BigQuery is able to complete the job successfully. Creation, truncation and append actions occur as one atomic update upon job completion. + * [Optional] The separator for fields in a CSV file. BigQuery converts the string to ISO-8859-1 encoding, and then uses the first byte of the encoded string to split the data in its raw, binary state. BigQuery also supports the escape sequence "\t" to specify a tab separator. The default value is a comma (','). */ - writeDisposition?: string; + fieldDelimiter?: string; }; - type IJobList = { + type IJobConfigurationExtract = { /** - * A hash of this page of results. + * [Optional] Whether to print out a header row in the results. Default is true. */ - etag?: string; + printHeader?: boolean; /** - * List of jobs that were requested. + * [Optional] The compression type to use for exported files. Possible values include GZIP, DEFLATE, SNAPPY, and NONE. The default value is NONE. DEFLATE and SNAPPY are only supported for Avro. */ - jobs?: Array<{ - /** - * [Full-projection-only] Specifies the job configuration. - */ - configuration?: IJobConfiguration; - /** - * A result object that will be present only if the job has failed. - */ - errorResult?: IErrorProto; - /** - * Unique opaque ID of the job. - */ - id?: string; - /** - * Job reference uniquely identifying the job. - */ - jobReference?: IJobReference; - /** - * The resource type. - */ - kind?: string; - /** - * Running state of the job. When the state is DONE, errorResult can be checked to determine whether the job succeeded or failed. - */ - state?: string; - /** - * [Output-only] Information about the job, including starting time and ending time of the job. - */ - statistics?: IJobStatistics; - /** - * [Full-projection-only] Describes the state of the job. - */ - status?: IJobStatus; - /** - * [Full-projection-only] Email address of the user who ran the job. - */ - user_email?: string; - }>; + compression?: string; /** - * The resource type of the response. + * [Pick one] A list of fully-qualified Google Cloud Storage URIs where the extracted table should be written. */ - kind?: string; + destinationUris?: Array; /** - * A token to request the next page of results. + * [Required] A reference to the table being exported. */ - nextPageToken?: string; + sourceTable?: ITableReference; + /** + * [Optional] The exported file format. Possible values include CSV, NEWLINE_DELIMITED_JSON and AVRO. The default value is CSV. Tables with nested or repeated fields cannot be exported as CSV. + */ + destinationFormat?: string; + /** + * [Optional] Delimiter to use between fields in the exported data. Default is ',' + */ + fieldDelimiter?: string; + /** + * [Pick one] DEPRECATED: Use destinationUris instead, passing only one URI as necessary. The fully-qualified Google Cloud Storage URI where the extracted table should be written. + */ + destinationUri?: string; }; type IJobReference = { @@ -1001,260 +1601,271 @@ declare namespace bigquery { * [Required] The ID of the job. The ID must contain only letters (a-z, A-Z), numbers (0-9), underscores (_), or dashes (-). The maximum length is 1,024 characters. */ jobId?: string; - /** - * The geographic location of the job. See details at https://cloud.google.com/bigquery/docs/locations#specifying_your_location. - */ - location?: string; /** * [Required] The ID of the project containing this job. */ projectId?: string; + /** + * The geographic location of the job. See details at https://cloud.google.com/bigquery/docs/locations#specifying_your_location. + */ + location?: string; }; - type IJobStatistics = { + type IJobConfigurationQuery = { /** - * [TrustedTester] [Output-only] Job progress (0.0 -> 1.0) for LOAD and EXTRACT jobs. + * [Required] SQL query text to execute. The useLegacySql field can be used to indicate whether the query uses legacy SQL or standard SQL. */ - completionRatio?: number; + query?: string; /** - * [Output-only] Creation time of this job, in milliseconds since the epoch. This field will be present on all jobs. + * Describes user-defined function resources used in the query. */ - creationTime?: string; + userDefinedFunctionResources?: Array; /** - * [Output-only] End time of this job, in milliseconds since the epoch. This field will be present whenever a job is in the DONE state. + * [Optional] Describes the table where the query results should be stored. If not present, a new table will be created to store the results. This property must be set for large results that exceed the maximum response size. */ - endTime?: string; + destinationTable?: ITableReference; /** - * [Output-only] Statistics for an extract job. + * Query parameters for standard SQL queries. */ - extract?: IJobStatistics4; + queryParameters?: Array; /** - * [Output-only] Statistics for a load job. + * Specifies whether to use BigQuery's legacy SQL dialect for this query. The default value is true. If set to false, the query will use BigQuery's standard SQL: https://cloud.google.com/bigquery/sql-reference/ When useLegacySql is set to false, the value of flattenResults is ignored; query will be run as if flattenResults is false. */ - load?: IJobStatistics3; + useLegacySql?: boolean; /** - * [Output-only] Number of child jobs executed. + * [Beta] Clustering specification for the destination table. Must be specified with time-based partitioning, data in the table will be first partitioned and subsequently clustered. */ - numChildJobs?: string; + clustering?: IClustering; /** - * [Output-only] If this is a child job, the id of the parent. + * Custom encryption configuration (e.g., Cloud KMS keys). */ - parentJobId?: string; + destinationEncryptionConfiguration?: IEncryptionConfiguration; /** - * [Output-only] Statistics for a query job. + * [Optional] Specifies whether the job is allowed to create new tables. The following values are supported: CREATE_IF_NEEDED: If the table does not exist, BigQuery creates the table. CREATE_NEVER: The table must already exist. If it does not, a 'notFound' error is returned in the job result. The default value is CREATE_IF_NEEDED. Creation, truncation and append actions occur as one atomic update upon job completion. */ - query?: IJobStatistics2; + createDisposition?: string; /** - * [Output-only] Quotas which delayed this job's start time. + * [Optional] Limits the bytes billed for this job. Queries that will have bytes billed beyond this limit will fail (without incurring a charge). If unspecified, this will be set to your project default. */ - quotaDeferments?: Array; + maximumBytesBilled?: string; /** - * [Output-only] Job resource usage breakdown by reservation. + * Allows the schema of the destination table to be updated as a side effect of the query job. Schema update options are supported in two cases: when writeDisposition is WRITE_APPEND; when writeDisposition is WRITE_TRUNCATE and the destination table is a partition of a table, specified by partition decorators. For normal tables, WRITE_TRUNCATE will always overwrite the schema. One or more of the following values are specified: ALLOW_FIELD_ADDITION: allow adding a nullable field to the schema. ALLOW_FIELD_RELAXATION: allow relaxing a required field in the original schema to nullable. */ - reservationUsage?: Array<{ - /** - * [Output-only] Reservation name or "unreserved" for on-demand resources usage. - */ - name?: string; - /** - * [Output-only] Slot-milliseconds the job spent in the given reservation. - */ - slotMs?: string; - }>; + schemaUpdateOptions?: Array; /** - * [Output-only] Start time of this job, in milliseconds since the epoch. This field will be present when the job transitions from the PENDING state to either RUNNING or DONE. + * [Optional] Specifies a priority for the query. Possible values include INTERACTIVE and BATCH. The default value is INTERACTIVE. */ - startTime?: string; + priority?: string; /** - * [Output-only] [Deprecated] Use the bytes processed in the query statistics instead. + * [Optional] If true and query uses legacy SQL dialect, allows the query to produce arbitrarily large result tables at a slight cost in performance. Requires destinationTable to be set. For standard SQL queries, this flag is ignored and large results are always allowed. However, you must still set destinationTable when result size exceeds the allowed maximum response size. */ - totalBytesProcessed?: string; + allowLargeResults?: boolean; /** - * [Output-only] Slot-milliseconds for the job. + * [TrustedTester] Range partitioning specification for this table. Only one of timePartitioning and rangePartitioning should be specified. */ - totalSlotMs?: string; - }; - - type IJobStatistics2 = { + rangePartitioning?: IRangePartitioning; /** - * [Output-only] Billing tier for the job. + * Standard SQL only. Set to POSITIONAL to use positional (?) query parameters or to NAMED to use named (@myparam) query parameters in this query. */ - billingTier?: number; + parameterMode?: string; /** - * [Output-only] Whether the query result was fetched from the query cache. + * [Optional] Whether to look for the result in the query cache. The query cache is a best-effort cache that will be flushed whenever tables in the query are modified. Moreover, the query cache is only available when a query does not have a destination table specified. The default value is true. */ - cacheHit?: boolean; + useQueryCache?: boolean; /** - * The DDL operation performed, possibly dependent on the pre-existence of the DDL target. Possible values (new values might be added in the future): "CREATE": The query created the DDL target. "SKIP": No-op. Example cases: the query is CREATE TABLE IF NOT EXISTS while the table already exists, or the query is DROP TABLE IF EXISTS while the table does not exist. "REPLACE": The query replaced the DDL target. Example case: the query is CREATE OR REPLACE TABLE, and the table already exists. "DROP": The query deleted the DDL target. + * [Optional] If true and query uses legacy SQL dialect, flattens all nested and repeated fields in the query results. allowLargeResults must be true if this is set to false. For standard SQL queries, this flag is ignored and results are never flattened. + */ + flattenResults?: boolean; + /** + * [Optional] If querying an external data source outside of BigQuery, describes the data format, location and other properties of the data source. By defining these properties, the data source can then be queried as if it were a standard BigQuery table. + */ + tableDefinitions?: { [key: string]: IExternalDataConfiguration }; + /** + * [Optional] Specifies the default dataset to use for unqualified table names in the query. Note that this does not alter behavior of unqualified dataset names. */ - ddlOperationPerformed?: string; + defaultDataset?: IDatasetReference; /** - * The DDL target routine. Present only for CREATE/DROP FUNCTION/PROCEDURE queries. + * [Optional] Limits the billing tier for this job. Queries that have resource usage beyond this tier will fail (without incurring a charge). If unspecified, this will be set to your project default. */ - ddlTargetRoutine?: IRoutineReference; + maximumBillingTier?: number; /** - * The DDL target table. Present only for CREATE/DROP TABLE/VIEW queries. + * [Deprecated] This property is deprecated. */ - ddlTargetTable?: ITableReference; + preserveNulls?: boolean; /** - * [Output-only] The original estimate of bytes processed for the job. + * Time-based partitioning specification for the destination table. Only one of timePartitioning and rangePartitioning should be specified. */ - estimatedBytesProcessed?: string; + timePartitioning?: ITimePartitioning; /** - * [Output-only, Beta] Information about create model query job progress. + * [Optional] Specifies the action that occurs if the destination table already exists. The following values are supported: WRITE_TRUNCATE: If the table already exists, BigQuery overwrites the table data and uses the schema from the query result. WRITE_APPEND: If the table already exists, BigQuery appends the data to the table. WRITE_EMPTY: If the table already exists and contains data, a 'duplicate' error is returned in the job result. The default value is WRITE_EMPTY. Each action is atomic and only occurs if BigQuery is able to complete the job successfully. Creation, truncation and append actions occur as one atomic update upon job completion. */ - modelTraining?: IBigQueryModelTraining; + writeDisposition?: string; + }; + + /** + * Information about a single cluster for clustering model. + */ + type IClusterInfo = { /** - * [Output-only, Beta] Deprecated; do not use. + * Cluster radius, the average distance from centroid + * to each point assigned to the cluster. */ - modelTrainingCurrentIteration?: number; + clusterRadius?: number; /** - * [Output-only, Beta] Deprecated; do not use. + * Cluster size, the total number of points assigned to the cluster. */ - modelTrainingExpectedTotalIteration?: string; + clusterSize?: string; /** - * [Output-only] The number of rows affected by a DML statement. Present only for DML statements INSERT, UPDATE or DELETE. + * Centroid id. */ - numDmlAffectedRows?: string; + centroidId?: string; + }; + + type IQueryParameterType = { /** - * [Output-only] Describes execution plan for the query. + * [Optional] The type of the array's elements, if this is an array. */ - queryPlan?: Array; + arrayType?: IQueryParameterType; /** - * [Output-only] Referenced tables for the job. Queries that reference more than 50 tables will not have a complete list. + * [Required] The top level type of this field. */ - referencedTables?: Array; + type?: string; /** - * [Output-only] Job resource usage breakdown by reservation. + * [Optional] The types of the fields of this struct, in order, if this is a struct. */ - reservationUsage?: Array<{ + structTypes?: Array<{ /** - * [Output-only] Reservation name or "unreserved" for on-demand resources usage. + * [Optional] The name of this field. */ name?: string; /** - * [Output-only] Slot-milliseconds the job spent in the given reservation. + * [Optional] Human-oriented description of the field. */ - slotMs?: string; + description?: string; + /** + * [Required] The type of this field. + */ + type?: IQueryParameterType; }>; + }; + + type ITimePartitioning = { + requirePartitionFilter?: boolean; /** - * [Output-only] The schema of the results. Present only for successful dry run of non-legacy SQL queries. + * [Beta] [Optional] If not set, the table is partitioned by pseudo column, referenced via either '_PARTITIONTIME' as TIMESTAMP type, or '_PARTITIONDATE' as DATE type. If field is specified, the table is instead partitioned by this field. The field must be a top-level TIMESTAMP or DATE field. Its mode must be NULLABLE or REQUIRED. */ - schema?: ITableSchema; + field?: string; /** - * The type of query statement, if valid. Possible values (new values might be added in the future): "SELECT": SELECT query. "INSERT": INSERT query; see https://cloud.google.com/bigquery/docs/reference/standard-sql/data-manipulation-language. "UPDATE": UPDATE query; see https://cloud.google.com/bigquery/docs/reference/standard-sql/data-manipulation-language. "DELETE": DELETE query; see https://cloud.google.com/bigquery/docs/reference/standard-sql/data-manipulation-language. "MERGE": MERGE query; see https://cloud.google.com/bigquery/docs/reference/standard-sql/data-manipulation-language. "CREATE_TABLE": CREATE [OR REPLACE] TABLE without AS SELECT. "CREATE_TABLE_AS_SELECT": CREATE [OR REPLACE] TABLE ... AS SELECT ... . "DROP_TABLE": DROP TABLE query. "CREATE_VIEW": CREATE [OR REPLACE] VIEW ... AS SELECT ... . "DROP_VIEW": DROP VIEW query. "CREATE_FUNCTION": CREATE FUNCTION query. "DROP_FUNCTION" : DROP FUNCTION query. "ALTER_TABLE": ALTER TABLE query. "ALTER_VIEW": ALTER VIEW query. + * [Optional] Number of milliseconds for which to keep the storage for partitions in the table. The storage in a partition will have an expiration time of its partition time plus this value. */ - statementType?: string; + expirationMs?: string; /** - * [Output-only] [Beta] Describes a timeline of job execution. + * [Required] The only type supported is DAY, which will generate one partition per day. */ - timeline?: Array; + type?: string; + }; + + type IViewDefinition = { /** - * [Output-only] Total bytes billed for the job. + * Specifies whether to use BigQuery's legacy SQL for this view. The default value is true. If set to false, the view will use BigQuery's standard SQL: https://cloud.google.com/bigquery/sql-reference/ Queries and views that reference this view must use the same flag value. */ - totalBytesBilled?: string; + useLegacySql?: boolean; /** - * [Output-only] Total bytes processed for the job. + * [Required] A query that BigQuery executes when the view is referenced. */ - totalBytesProcessed?: string; + query?: string; /** - * [Output-only] For dry-run jobs, totalBytesProcessed is an estimate and this field specifies the accuracy of the estimate. Possible values can be: UNKNOWN: accuracy of the estimate is unknown. PRECISE: estimate is precise. LOWER_BOUND: estimate is lower bound of what the query would cost. UPPER_BOUND: estimate is upper bound of what the query would cost. + * Describes user-defined function resources used in the query. */ - totalBytesProcessedAccuracy?: string; + userDefinedFunctionResources?: Array; + }; + + type IJobStatistics = { /** - * [Output-only] Total number of partitions processed from all partitioned tables referenced in the job. + * [Output-only] If this is a child job, the id of the parent. */ - totalPartitionsProcessed?: string; + parentJobId?: string; /** - * [Output-only] Slot-milliseconds for the job. + * [Output-only] Quotas which delayed this job's start time. */ - totalSlotMs?: string; + quotaDeferments?: Array; /** - * Standard SQL only: list of undeclared query parameters detected during a dry run validation. + * [Output-only] Creation time of this job, in milliseconds since the epoch. This field will be present on all jobs. */ - undeclaredQueryParameters?: Array; - }; - - type IJobStatistics3 = { + creationTime?: string; /** - * [Output-only] The number of bad records encountered. Note that if the job has failed because of more bad records encountered than the maximum allowed in the load job configuration, then this number can be less than the total number of bad records present in the input data. + * [Output-only] Job resource usage breakdown by reservation. */ - badRecords?: string; + reservationUsage?: Array<{ + /** + * [Output-only] Reservation name or "unreserved" for on-demand resources usage. + */ + name?: string; + /** + * [Output-only] Slot-milliseconds the job spent in the given reservation. + */ + slotMs?: string; + }>; /** - * [Output-only] Number of bytes of source data in a load job. + * [Output-only] Statistics for a load job. */ - inputFileBytes?: string; + load?: IJobStatistics3; /** - * [Output-only] Number of source files in a load job. + * [Output-only] Statistics for an extract job. */ - inputFiles?: string; + extract?: IJobStatistics4; /** - * [Output-only] Size of the loaded data in bytes. Note that while a load job is in the running state, this value may change. + * [Output-only] End time of this job, in milliseconds since the epoch. This field will be present whenever a job is in the DONE state. */ - outputBytes?: string; + endTime?: string; /** - * [Output-only] Number of rows imported in a load job. Note that while an import job is in the running state, this value may change. + * [Output-only] Start time of this job, in milliseconds since the epoch. This field will be present when the job transitions from the PENDING state to either RUNNING or DONE. */ - outputRows?: string; - }; - - type IJobStatistics4 = { + startTime?: string; /** - * [Output-only] Number of files per destination URI or URI pattern specified in the extract configuration. These values will be in the same order as the URIs specified in the 'destinationUris' field. + * [TrustedTester] [Output-only] Job progress (0.0 -> 1.0) for LOAD and EXTRACT jobs. */ - destinationUriFileCounts?: Array; + completionRatio?: number; /** - * [Output-only] Number of user bytes extracted into the result. This is the byte count as computed by BigQuery for billing purposes. + * [Output-only] Statistics for a query job. */ - inputBytes?: string; - }; - - type IJobStatus = { + query?: IJobStatistics2; /** - * [Output-only] Final error result of the job. If present, indicates that the job has completed and was unsuccessful. + * [Output-only] [Deprecated] Use the bytes processed in the query statistics instead. */ - errorResult?: IErrorProto; + totalBytesProcessed?: string; /** - * [Output-only] The first errors encountered during the running of the job. The final message includes the number of errors that caused the process to stop. Errors here do not necessarily mean that the job has completed or was unsuccessful. + * [Output-only] Number of child jobs executed. */ - errors?: Array; + numChildJobs?: string; /** - * [Output-only] Running state of the job. + * [Output-only] Slot-milliseconds for the job. */ - state?: string; + totalSlotMs?: string; }; - /** - * Represents a single JSON object. - */ - type IJsonObject = { [key: string]: IJsonValue }; - - type IJsonValue = any; - - type IMaterializedViewDefinition = { + type IBigQueryModelTraining = { /** - * [Output-only] [TrustedTester] The time when this materialized view was last modified, in milliseconds since the epoch. + * [Output-only, Beta] Index of current ML training iteration. Updated during create model query job to show job progress. */ - lastRefreshTime?: string; + currentIteration?: number; /** - * [Required] A query whose result is persisted. + * [Output-only, Beta] Expected number of iterations for the create model query job specified as num_iterations in the input query. The actual total number of iterations may be less than this number due to early stop. */ - query?: string; + expectedTotalIterations?: string; }; - type IModelDefinition = { - /** - * [Output-only, Beta] Model options used for the first training run. These options are immutable for subsequent training runs. Default values are used for any options not specified in the input query. - */ - modelOptions?: { - labels?: Array; - lossType?: string; - modelType?: string; - }; + /** + * BigQuery-specific metadata about a location. This will be set on + * google.cloud.location.Location.metadata in Cloud Location API + * responses. + */ + type ILocationMetadata = { /** - * [Output-only, Beta] Information about ml training runs, each training run comprises of multiple iterations and there may be multiple training runs for the model if warm start is used or if a user decides to continue a previously cancelled query. + * The legacy BigQuery location ID, e.g. “EU” for the “europe” location. + * This is for any API consumers that need the legacy “US” and “EU” locations. */ - trainingRuns?: Array; + legacyLocationId?: string; }; type IProjectList = { @@ -1262,14 +1873,6 @@ declare namespace bigquery { * A hash of the page of results */ etag?: string; - /** - * The type of list. - */ - kind?: string; - /** - * A token to request the next page of results. - */ - nextPageToken?: string; /** * Projects to which you have at least READ access. */ @@ -1279,634 +1882,618 @@ declare namespace bigquery { */ friendlyName?: string; /** - * An opaque ID of this project. + * The numeric ID of this project. */ - id?: string; + numericId?: string; /** * The resource type. */ kind?: string; /** - * The numeric ID of this project. + * An opaque ID of this project. */ - numericId?: string; + id?: string; /** * A unique reference to this project. */ projectReference?: IProjectReference; }>; + /** + * A token to request the next page of results. + */ + nextPageToken?: string; /** * The total number of projects in the list. */ totalItems?: number; + /** + * The type of list. + */ + kind?: string; }; - type IProjectReference = { + /** + * A single row in the confusion matrix. + */ + type IRow = { + /** + * Info describing predicted label distribution. + */ + entries?: Array; + /** + * The original label of this row. + */ + actualLabel?: string; + }; + + /** + * Evaluation metrics for regression models. + */ + type IRegressionMetrics = { + /** + * Mean absolute error. + */ + meanAbsoluteError?: number; + /** + * Mean squared error. + */ + meanSquaredError?: number; + /** + * R^2 score. + */ + rSquared?: number; + /** + * Median absolute error. + */ + medianAbsoluteError?: number; + /** + * Mean squared log error. + */ + meanSquaredLogError?: number; + }; + + type IJsonValue = any; + + type IGetQueryResultsResponse = { + /** + * The schema of the results. Present only when the query completes successfully. + */ + schema?: ITableSchema; + /** + * [Output-only] The first errors or warnings encountered during the running of the job. The final message includes the number of errors that caused the process to stop. Errors here do not necessarily mean that the job has completed or was unsuccessful. + */ + errors?: Array; + /** + * The total number of rows in the complete query result set, which can be more than the number of rows in this single page of results. Present only when the query completes successfully. + */ + totalRows?: string; + /** + * Whether the query has completed or not. If rows or totalRows are present, this will always be true. If this is false, totalRows will not be available. + */ + jobComplete?: boolean; + /** + * [Output-only] The number of rows affected by a DML statement. Present only for DML statements INSERT, UPDATE or DELETE. + */ + numDmlAffectedRows?: string; /** - * [Required] ID of the project. Can be either the numeric ID or the assigned ID of the project. + * The total number of bytes processed for this query. */ - projectId?: string; - }; - - type IQueryParameter = { + totalBytesProcessed?: string; /** - * [Optional] If unset, this is a positional parameter. Otherwise, should be unique within a query. + * An object with as many results as can be contained within the maximum permitted reply size. To get any additional rows, you can call GetQueryResults and specify the jobReference returned above. Present only when the query completes successfully. */ - name?: string; + rows?: Array; /** - * [Required] The type of this parameter. + * A token used for paging results. */ - parameterType?: IQueryParameterType; + pageToken?: string; /** - * [Required] The value of this parameter. + * The resource type of the response. */ - parameterValue?: IQueryParameterValue; - }; - - type IQueryParameterType = { + kind?: string; /** - * [Optional] The type of the array's elements, if this is an array. + * A hash of this response. */ - arrayType?: IQueryParameterType; + etag?: string; /** - * [Optional] The types of the fields of this struct, in order, if this is a struct. + * Whether the query result was fetched from the query cache. */ - structTypes?: Array<{ - /** - * [Optional] Human-oriented description of the field. - */ - description?: string; - /** - * [Optional] The name of this field. - */ - name?: string; - /** - * [Required] The type of this field. - */ - type?: IQueryParameterType; - }>; + cacheHit?: boolean; /** - * [Required] The top level type of this field. + * Reference to the BigQuery Job that was created to run the query. This field will be present even if the original request timed out, in which case GetQueryResults can be used to read the results once the query has completed. Since this API only returns the first page of results, subsequent pages can be fetched via the same mechanism (GetQueryResults). */ - type?: string; + jobReference?: IJobReference; }; - type IQueryParameterValue = { + type IRoutineReference = { /** - * [Optional] The array values, if this is an array type. + * [Required] The ID of the project containing this routine. */ - arrayValues?: Array; + projectId?: string; /** - * [Optional] The struct field values, in order of the struct type's declaration. + * [Required] The ID of the dataset containing this routine. */ - structValues?: { [key: string]: IQueryParameterValue }; + datasetId?: string; /** - * [Optional] The value of this value, if a simple scalar type. + * [Required] The ID of the routine. The ID must contain only letters (a-z, A-Z), numbers (0-9), or underscores (_). The maximum length is 256 characters. */ - value?: string; + routineId?: string; }; - type IQueryRequest = { - /** - * [Optional] Specifies the default datasetId and projectId to assume for any unqualified table names in the query. If not set, all table names in the query string must be qualified in the format 'datasetId.tableId'. - */ - defaultDataset?: IDatasetReference; - /** - * [Optional] If set to true, BigQuery doesn't run the job. Instead, if the query is valid, BigQuery returns statistics about the job such as how many bytes would be processed. If the query is invalid, an error returns. The default value is false. - */ - dryRun?: boolean; + type IJobList = { /** - * The resource type of the request. + * The resource type of the response. */ kind?: string; /** - * The geographic location where the job should run. See details at https://cloud.google.com/bigquery/docs/locations#specifying_your_location. + * A hash of this page of results. */ - location?: string; + etag?: string; /** - * [Optional] The maximum number of rows of data to return per page of results. Setting this flag to a small value such as 1000 and then paging through results might improve reliability when the query result set is large. In addition to this limit, responses are also limited to 10 MB. By default, there is no maximum row count, and only the byte limit applies. + * List of jobs that were requested. */ - maxResults?: number; + jobs?: Array<{ + /** + * [Full-projection-only] Email address of the user who ran the job. + */ + user_email?: string; + /** + * The resource type. + */ + kind?: string; + /** + * A result object that will be present only if the job has failed. + */ + errorResult?: IErrorProto; + /** + * Job reference uniquely identifying the job. + */ + jobReference?: IJobReference; + /** + * [Full-projection-only] Describes the state of the job. + */ + status?: IJobStatus; + /** + * Running state of the job. When the state is DONE, errorResult can be checked to determine whether the job succeeded or failed. + */ + state?: string; + /** + * [Output-only] Information about the job, including starting time and ending time of the job. + */ + statistics?: IJobStatistics; + /** + * Unique opaque ID of the job. + */ + id?: string; + /** + * [Full-projection-only] Specifies the job configuration. + */ + configuration?: IJobConfiguration; + }>; /** - * Standard SQL only. Set to POSITIONAL to use positional (?) query parameters or to NAMED to use named (@myparam) query parameters in this query. + * A token to request the next page of results. */ - parameterMode?: string; + nextPageToken?: string; + }; + + type IJobStatistics2 = { /** - * [Deprecated] This property is deprecated. + * [Output-only, Beta] Information about create model query job progress. */ - preserveNulls?: boolean; + modelTraining?: IBigQueryModelTraining; /** - * [Required] A query string, following the BigQuery query syntax, of the query to execute. Example: "SELECT count(f1) FROM [myProjectId:myDatasetId.myTableId]". + * [Output-only] [Beta] Describes a timeline of job execution. */ - query?: string; + timeline?: Array; /** - * Query parameters for Standard SQL queries. + * [Output-only] Whether the query result was fetched from the query cache. */ - queryParameters?: Array; + cacheHit?: boolean; /** - * [Optional] How long to wait for the query to complete, in milliseconds, before the request times out and returns. Note that this is only a timeout for the request, not the query. If the query takes longer to run than the timeout value, the call returns without any results and with the 'jobComplete' flag set to false. You can call GetQueryResults() to wait for the query to complete and read the results. The default value is 10000 milliseconds (10 seconds). + * [Output-only] Job resource usage breakdown by reservation. */ - timeoutMs?: number; + reservationUsage?: Array<{ + /** + * [Output-only] Reservation name or "unreserved" for on-demand resources usage. + */ + name?: string; + /** + * [Output-only] Slot-milliseconds the job spent in the given reservation. + */ + slotMs?: string; + }>; /** - * Specifies whether to use BigQuery's legacy SQL dialect for this query. The default value is true. If set to false, the query will use BigQuery's standard SQL: https://cloud.google.com/bigquery/sql-reference/ When useLegacySql is set to false, the value of flattenResults is ignored; query will be run as if flattenResults is false. + * Standard SQL only: list of undeclared query parameters detected during a dry run validation. */ - useLegacySql?: boolean; + undeclaredQueryParameters?: Array; /** - * [Optional] Whether to look for the result in the query cache. The query cache is a best-effort cache that will be flushed whenever tables in the query are modified. The default value is true. + * [Output-only] Describes execution plan for the query. */ - useQueryCache?: boolean; - }; - - type IQueryResponse = { + queryPlan?: Array; /** - * Whether the query result was fetched from the query cache. + * The DDL target routine. Present only for CREATE/DROP FUNCTION/PROCEDURE queries. */ - cacheHit?: boolean; + ddlTargetRoutine?: IRoutineReference; /** - * [Output-only] The first errors or warnings encountered during the running of the job. The final message includes the number of errors that caused the process to stop. Errors here do not necessarily mean that the job has completed or was unsuccessful. + * The DDL target table. Present only for CREATE/DROP TABLE/VIEW queries. */ - errors?: Array; + ddlTargetTable?: ITableReference; /** - * Whether the query has completed or not. If rows or totalRows are present, this will always be true. If this is false, totalRows will not be available. + * [Output-only] Total number of partitions processed from all partitioned tables referenced in the job. */ - jobComplete?: boolean; + totalPartitionsProcessed?: string; /** - * Reference to the Job that was created to run the query. This field will be present even if the original request timed out, in which case GetQueryResults can be used to read the results once the query has completed. Since this API only returns the first page of results, subsequent pages can be fetched via the same mechanism (GetQueryResults). + * [Output-only] The schema of the results. Present only for successful dry run of non-legacy SQL queries. */ - jobReference?: IJobReference; + schema?: ITableSchema; /** - * The resource type. + * [Output-only, Beta] Deprecated; do not use. */ - kind?: string; + modelTrainingExpectedTotalIteration?: string; /** - * [Output-only] The number of rows affected by a DML statement. Present only for DML statements INSERT, UPDATE or DELETE. + * [Output-only] The original estimate of bytes processed for the job. */ - numDmlAffectedRows?: string; + estimatedBytesProcessed?: string; /** - * A token used for paging results. + * [Output-only] Referenced tables for the job. Queries that reference more than 50 tables will not have a complete list. */ - pageToken?: string; + referencedTables?: Array; /** - * An object with as many results as can be contained within the maximum permitted reply size. To get any additional rows, you can call GetQueryResults and specify the jobReference returned above. + * [Output-only, Beta] Deprecated; do not use. */ - rows?: Array; + modelTrainingCurrentIteration?: number; /** - * The schema of the results. Present only when the query completes successfully. + * [Output-only] Total bytes processed for the job. */ - schema?: ITableSchema; + totalBytesProcessed?: string; /** - * The total number of bytes processed for this query. If this query was a dry run, this is the number of bytes that would be processed if the query were run. + * [Output-only] The number of rows affected by a DML statement. Present only for DML statements INSERT, UPDATE or DELETE. */ - totalBytesProcessed?: string; + numDmlAffectedRows?: string; /** - * The total number of rows in the complete query result set, which can be more than the number of rows in this single page of results. + * [Output-only] Slot-milliseconds for the job. */ - totalRows?: string; - }; - - type IQueryTimelineSample = { + totalSlotMs?: string; /** - * Total number of units currently being processed by workers. This does not correspond directly to slot usage. This is the largest value observed since the last sample. + * The type of query statement, if valid. Possible values (new values might be added in the future): "SELECT": SELECT query. "INSERT": INSERT query; see https://cloud.google.com/bigquery/docs/reference/standard-sql/data-manipulation-language. "UPDATE": UPDATE query; see https://cloud.google.com/bigquery/docs/reference/standard-sql/data-manipulation-language. "DELETE": DELETE query; see https://cloud.google.com/bigquery/docs/reference/standard-sql/data-manipulation-language. "MERGE": MERGE query; see https://cloud.google.com/bigquery/docs/reference/standard-sql/data-manipulation-language. "ALTER_TABLE": ALTER TABLE query. "ALTER_VIEW": ALTER VIEW query. "CREATE_FUNCTION": CREATE FUNCTION query. "CREATE_MODEL": CREATE [OR REPLACE] MODEL ... AS SELECT ... . "CREATE_PROCEDURE": CREATE PROCEDURE query. "CREATE_TABLE": CREATE [OR REPLACE] TABLE without AS SELECT. "CREATE_TABLE_AS_SELECT": CREATE [OR REPLACE] TABLE ... AS SELECT ... . "CREATE_VIEW": CREATE [OR REPLACE] VIEW ... AS SELECT ... . "DROP_FUNCTION" : DROP FUNCTION query. "DROP_PROCEDURE": DROP PROCEDURE query. "DROP_TABLE": DROP TABLE query. "DROP_VIEW": DROP VIEW query. */ - activeUnits?: string; + statementType?: string; /** - * Total parallel units of work completed by this query. + * The DDL operation performed, possibly dependent on the pre-existence of the DDL target. Possible values (new values might be added in the future): "CREATE": The query created the DDL target. "SKIP": No-op. Example cases: the query is CREATE TABLE IF NOT EXISTS while the table already exists, or the query is DROP TABLE IF EXISTS while the table does not exist. "REPLACE": The query replaced the DDL target. Example case: the query is CREATE OR REPLACE TABLE, and the table already exists. "DROP": The query deleted the DDL target. */ - completedUnits?: string; + ddlOperationPerformed?: string; /** - * Milliseconds elapsed since the start of query execution. + * [Output-only] Billing tier for the job. */ - elapsedMs?: string; + billingTier?: number; /** - * Total parallel units of work remaining for the active stages. + * [Output-only] Total bytes billed for the job. */ - pendingUnits?: string; + totalBytesBilled?: string; /** - * Cumulative slot-ms consumed by the query. + * [Output-only] For dry-run jobs, totalBytesProcessed is an estimate and this field specifies the accuracy of the estimate. Possible values can be: UNKNOWN: accuracy of the estimate is unknown. PRECISE: estimate is precise. LOWER_BOUND: estimate is lower bound of what the query would cost. UPPER_BOUND: estimate is upper bound of what the query would cost. */ - totalSlotMs?: string; + totalBytesProcessedAccuracy?: string; }; - type IRangePartitioning = { + type ITableDataList = { /** - * [TrustedTester] [Required] The table is partitioned by this field. The field must be a top-level NULLABLE/REQUIRED field. The only supported type is INTEGER/INT64. + * A token used for paging results. Providing this token instead of the startIndex parameter can help you retrieve stable results when an underlying table is changing. */ - field?: string; + pageToken?: string; /** - * [TrustedTester] [Required] Defines the ranges for range partitioning. + * The resource type of the response. */ - range?: { - /** - * [TrustedTester] [Required] The end of range partitioning, exclusive. - */ - end?: string; - /** - * [TrustedTester] [Required] The width of each interval. - */ - interval?: string; - /** - * [TrustedTester] [Required] The start of range partitioning, inclusive. - */ - start?: string; - }; - }; - - type IRoutineReference = { + kind?: string; /** - * [Required] The ID of the dataset containing this routine. + * The total number of rows in the complete table. */ - datasetId?: string; + totalRows?: string; /** - * [Required] The ID of the project containing this routine. + * A hash of this page of results. */ - projectId?: string; + etag?: string; /** - * [Required] The ID of the routine. The ID must contain only letters (a-z, A-Z), numbers (0-9), or underscores (_). The maximum length is 256 characters. + * Rows of results. */ - routineId?: string; + rows?: Array; }; - type IStreamingbuffer = { - /** - * [Output-only] A lower-bound estimate of the number of bytes currently in the streaming buffer. - */ - estimatedBytes?: string; + /** + * Information about a single iteration of the training run. + */ + type IIterationResult = { /** - * [Output-only] A lower-bound estimate of the number of rows currently in the streaming buffer. + * Time taken to run the iteration in milliseconds. */ - estimatedRows?: string; + durationMs?: string; /** - * [Output-only] Contains the timestamp of the oldest entry in the streaming buffer, in milliseconds since the epoch, if the streaming buffer is available. + * [Beta] Information about top clusters for clustering models. */ - oldestEntryTime?: string; - }; - - type ITable = { + clusterInfos?: Array; /** - * [Beta] Clustering specification for the table. Must be specified with partitioning, data in the table will be first partitioned and subsequently clustered. + * Loss computed on the training data at the end of iteration. */ - clustering?: IClustering; + trainingLoss?: number; /** - * [Output-only] The time when this table was created, in milliseconds since the epoch. + * Loss computed on the eval data at the end of iteration. */ - creationTime?: string; + evalLoss?: number; /** - * [Optional] A user-friendly description of this table. + * Index of the iteration, 0 based. */ - description?: string; + index?: number; /** - * Custom encryption configuration (e.g., Cloud KMS keys). + * Learn rate used for this iteration. */ - encryptionConfiguration?: IEncryptionConfiguration; + learnRate?: number; + }; + + type IJobCancelResponse = { /** - * [Output-only] A hash of the table metadata. Used to ensure there were no concurrent modifications to the resource when attempting an update. Not guaranteed to change when the table contents or the fields numRows, numBytes, numLongTermBytes or lastModifiedTime change. + * The resource type of the response. */ - etag?: string; + kind?: string; /** - * [Optional] The time when this table expires, in milliseconds since the epoch. If not present, the table will persist indefinitely. Expired tables will be deleted and their storage reclaimed. The defaultTableExpirationMs property of the encapsulating dataset can be used to set a default expirationTime on newly created tables. + * The final state of the job. */ - expirationTime?: string; + job?: IJob; + }; + + type IQueryResponse = { /** - * [Optional] Describes the data format, location, and other properties of a table stored outside of BigQuery. By defining these properties, the data source can then be queried as if it were a standard BigQuery table. + * An object with as many results as can be contained within the maximum permitted reply size. To get any additional rows, you can call GetQueryResults and specify the jobReference returned above. */ - externalDataConfiguration?: IExternalDataConfiguration; + rows?: Array; /** - * [Optional] A descriptive name for this table. + * [Output-only] The first errors or warnings encountered during the running of the job. The final message includes the number of errors that caused the process to stop. Errors here do not necessarily mean that the job has completed or was unsuccessful. */ - friendlyName?: string; + errors?: Array; /** - * [Output-only] An opaque ID uniquely identifying the table. + * A token used for paging results. */ - id?: string; + pageToken?: string; /** - * [Output-only] The type of the resource. + * The resource type. */ kind?: string; /** - * The labels associated with this table. You can use these to organize and group your tables. Label keys and values can be no longer than 63 characters, can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. Label values are optional. Label keys must start with a letter and each label in the list must have a different key. + * Whether the query has completed or not. If rows or totalRows are present, this will always be true. If this is false, totalRows will not be available. */ - labels?: { [key: string]: string }; + jobComplete?: boolean; /** - * [Output-only] The time when this table was last modified, in milliseconds since the epoch. + * [Output-only] The number of rows affected by a DML statement. Present only for DML statements INSERT, UPDATE or DELETE. */ - lastModifiedTime?: string; + numDmlAffectedRows?: string; /** - * [Output-only] The geographic location where the table resides. This value is inherited from the dataset. + * The total number of bytes processed for this query. If this query was a dry run, this is the number of bytes that would be processed if the query were run. */ - location?: string; + totalBytesProcessed?: string; /** - * [Optional] Materialized view definition. + * The total number of rows in the complete query result set, which can be more than the number of rows in this single page of results. */ - materializedView?: IMaterializedViewDefinition; + totalRows?: string; /** - * [Output-only, Beta] Present iff this table represents a ML model. Describes the training information for the model, and it is required to run 'PREDICT' queries. + * Reference to the Job that was created to run the query. This field will be present even if the original request timed out, in which case GetQueryResults can be used to read the results once the query has completed. Since this API only returns the first page of results, subsequent pages can be fetched via the same mechanism (GetQueryResults). */ - model?: IModelDefinition; + jobReference?: IJobReference; /** - * [Output-only] The size of this table in bytes, excluding any data in the streaming buffer. + * Whether the query result was fetched from the query cache. */ - numBytes?: string; + cacheHit?: boolean; /** - * [Output-only] The number of bytes in the table that are considered "long-term storage". + * The schema of the results. Present only when the query completes successfully. */ - numLongTermBytes?: string; + schema?: ITableSchema; + }; + + type IProjectReference = { /** - * [Output-only] [TrustedTester] The physical size of this table in bytes, excluding any data in the streaming buffer. This includes compression and storage used for time travel. + * [Required] ID of the project. Can be either the numeric ID or the assigned ID of the project. */ - numPhysicalBytes?: string; + projectId?: string; + }; + + type IExplainQueryStage = { /** - * [Output-only] The number of rows of data in this table, excluding any data in the streaming buffer. + * Total number of bytes written to shuffle and spilled to disk. */ - numRows?: string; + shuffleOutputBytesSpilled?: string; /** - * [TrustedTester] Range partitioning specification for this table. Only one of timePartitioning and rangePartitioning should be specified. + * Milliseconds the average shard spent reading input. */ - rangePartitioning?: IRangePartitioning; + readMsAvg?: string; /** - * [Beta] [Optional] If set to true, queries over this table require a partition filter that can be used for partition elimination to be specified. + * Milliseconds the average shard spent waiting to be scheduled. */ - requirePartitionFilter?: boolean; + waitMsAvg?: string; /** - * [Optional] Describes the schema of this table. + * Number of records read into the stage. */ - schema?: ITableSchema; + recordsRead?: string; /** - * [Output-only] A URL that can be used to access this resource again. + * Milliseconds the average shard spent on writing output. */ - selfLink?: string; + writeMsAvg?: string; /** - * [Output-only] Contains information regarding this table's streaming buffer, if one is present. This field will be absent if the table is not being streamed to or if there is no data in the streaming buffer. + * Relative amount of time the slowest shard spent waiting to be scheduled. */ - streamingBuffer?: IStreamingbuffer; + waitRatioMax?: number; /** - * [Required] Reference describing the ID of this table. + * Milliseconds the slowest shard spent waiting to be scheduled. */ - tableReference?: ITableReference; + waitMsMax?: string; /** - * Time-based partitioning specification for this table. Only one of timePartitioning and rangePartitioning should be specified. + * Relative amount of time the average shard spent on writing output. */ - timePartitioning?: ITimePartitioning; + writeRatioAvg?: number; /** - * [Output-only] Describes the table type. The following values are supported: TABLE: A normal BigQuery table. VIEW: A virtual table defined by a SQL query. [TrustedTester] MATERIALIZED_VIEW: SQL query whose result is persisted. EXTERNAL: A table that references data stored in an external storage system, such as Google Cloud Storage. The default value is TABLE. + * Relative amount of time the average shard spent on CPU-bound tasks. */ - type?: string; + computeRatioAvg?: number; /** - * [Optional] The view definition. + * Number of parallel input segments completed. */ - view?: IViewDefinition; - }; - - type ITableCell = { v?: any }; - - type ITableDataInsertAllRequest = { + completedParallelInputs?: string; /** - * [Optional] Accept rows that contain values that do not match the schema. The unknown values are ignored. Default is false, which treats unknown values as errors. + * Number of records written by the stage. */ - ignoreUnknownValues?: boolean; + recordsWritten?: string; /** - * The resource type of the response. + * Relative amount of time the average shard spent waiting to be scheduled. */ - kind?: string; + waitRatioAvg?: number; /** - * The rows to insert. + * Relative amount of time the slowest shard spent reading input. */ - rows?: Array<{ - /** - * [Optional] A unique ID for each row. BigQuery uses this property to detect duplicate insertion requests on a best-effort basis. - */ - insertId?: string; - /** - * [Required] A JSON object that contains a row of data. The object's properties and values must match the destination table's schema. - */ - json?: IJsonObject; - }>; + readRatioMax?: number; /** - * [Optional] Insert all valid rows of a request, even if invalid rows exist. The default value is false, which causes the entire request to fail if any invalid rows exist. + * Relative amount of time the average shard spent reading input. */ - skipInvalidRows?: boolean; + readRatioAvg?: number; /** - * If specified, treats the destination table as a base template, and inserts the rows into an instance table named "{destination}{templateSuffix}". BigQuery will manage creation of the instance table, using the schema of the base template table. See https://cloud.google.com/bigquery/streaming-data-into-bigquery#template-tables for considerations when working with templates tables. + * Unique ID for stage within plan. */ - templateSuffix?: string; - }; - - type ITableDataInsertAllResponse = { + id?: string; /** - * An array of errors for rows that were not inserted. + * Relative amount of time the slowest shard spent on writing output. */ - insertErrors?: Array<{ - /** - * Error information for the row indicated by the index property. - */ - errors?: Array; - /** - * The index of the row that error applies to. - */ - index?: number; - }>; + writeRatioMax?: number; /** - * The resource type of the response. + * Stage end time represented as milliseconds since epoch. */ - kind?: string; - }; - - type ITableDataList = { + endMs?: string; /** - * A hash of this page of results. + * IDs for stages that are inputs to this stage. */ - etag?: string; + inputStages?: Array; /** - * The resource type of the response. + * Milliseconds the average shard spent on CPU-bound tasks. */ - kind?: string; + computeMsAvg?: string; /** - * A token used for paging results. Providing this token instead of the startIndex parameter can help you retrieve stable results when an underlying table is changing. + * Milliseconds the slowest shard spent on CPU-bound tasks. */ - pageToken?: string; + computeMsMax?: string; /** - * Rows of results. + * Milliseconds the slowest shard spent reading input. */ - rows?: Array; + readMsMax?: string; /** - * The total number of rows in the complete table. + * Total number of bytes written to shuffle. */ - totalRows?: string; - }; - - type ITableFieldSchema = { + shuffleOutputBytes?: string; /** - * [Optional] The categories attached to this field, used for field-level access control. + * Number of parallel input segments to be processed. */ - categories?: { - /** - * A list of category resource names. For example, "projects/1/taxonomies/2/categories/3". At most 5 categories are allowed. - */ - names?: Array; - }; + parallelInputs?: string; /** - * [Optional] The field description. The maximum length is 1,024 characters. + * Current status for the stage. */ - description?: string; + status?: string; /** - * [Optional] Describes the nested schema fields if the type property is set to RECORD. + * Human-readable name for stage. */ - fields?: Array; + name?: string; /** - * [Optional] The field mode. Possible values include NULLABLE, REQUIRED and REPEATED. The default value is NULLABLE. + * Relative amount of time the slowest shard spent on CPU-bound tasks. */ - mode?: string; + computeRatioMax?: number; /** - * [Required] The field name. The name must contain only letters (a-z, A-Z), numbers (0-9), or underscores (_), and must start with a letter or underscore. The maximum length is 128 characters. + * List of operations within the stage in dependency order (approximately chronological). */ - name?: string; + steps?: Array; /** - * [Required] The field data type. Possible values include STRING, BYTES, INTEGER, INT64 (same as INTEGER), FLOAT, FLOAT64 (same as FLOAT), BOOLEAN, BOOL (same as BOOLEAN), TIMESTAMP, DATE, TIME, DATETIME, RECORD (where RECORD indicates that the field contains a nested schema) or STRUCT (same as RECORD). + * Stage start time represented as milliseconds since epoch. */ - type?: string; - }; - - type ITableList = { + startMs?: string; /** - * A hash of this page of results. + * Milliseconds the slowest shard spent on writing output. */ - etag?: string; + writeMsMax?: string; + }; + + type IJob = { /** - * The type of list. + * [Optional] Reference describing the unique-per-user name of the job. */ - kind?: string; + jobReference?: IJobReference; /** - * A token to request the next page of results. + * [Output-only] The status of this job. Examine this value when polling an asynchronous job to see if the job is complete. */ - nextPageToken?: string; + status?: IJobStatus; /** - * Tables in the requested dataset. + * [Output-only] Information about the job, including starting time and ending time of the job. */ - tables?: Array<{ - /** - * [Beta] Clustering specification for this table, if configured. - */ - clustering?: IClustering; - /** - * The time when this table was created, in milliseconds since the epoch. - */ - creationTime?: string; - /** - * [Optional] The time when this table expires, in milliseconds since the epoch. If not present, the table will persist indefinitely. Expired tables will be deleted and their storage reclaimed. - */ - expirationTime?: string; - /** - * The user-friendly name for this table. - */ - friendlyName?: string; - /** - * An opaque ID of the table - */ - id?: string; - /** - * The resource type. - */ - kind?: string; - /** - * The labels associated with this table. You can use these to organize and group your tables. - */ - labels?: { [key: string]: string }; - /** - * A reference uniquely identifying the table. - */ - tableReference?: ITableReference; - /** - * The time-based partitioning specification for this table, if configured. - */ - timePartitioning?: ITimePartitioning; - /** - * The type of table. Possible values are: TABLE, VIEW. - */ - type?: string; - /** - * Additional details for a view. - */ - view?: { - /** - * True if view is defined in legacy SQL dialect, false if in standard SQL. - */ - useLegacySql?: boolean; - }; - }>; + statistics?: IJobStatistics; /** - * The total number of tables in the dataset. + * [Output-only] A URL that can be used to access this resource again. */ - totalItems?: number; - }; - - type ITableReference = { + selfLink?: string; /** - * [Required] The ID of the dataset containing this table. + * [Output-only] Opaque ID field of the job */ - datasetId?: string; + id?: string; /** - * [Required] The ID of the project containing this table. + * [Required] Describes the job configuration. */ - projectId?: string; + configuration?: IJobConfiguration; /** - * [Required] The ID of the table. The ID must contain only letters (a-z, A-Z), numbers (0-9), or underscores (_). The maximum length is 1,024 characters. + * [Output-only] Email address of the user who ran the job. */ - tableId?: string; - }; - - type ITableRow = { + user_email?: string; /** - * Represents a single row in the result set, consisting of one or more fields. + * [Output-only] The type of the resource. */ - f?: Array; - }; - - type ITableSchema = { + kind?: string; /** - * Describes the fields in a table. + * [Output-only] A hash of this resource. */ - fields?: Array; + etag?: string; }; - type ITimePartitioning = { + type IBigtableOptions = { /** - * [Optional] Number of milliseconds for which to keep the storage for partitions in the table. The storage in a partition will have an expiration time of its partition time plus this value. + * [Optional] If field is true, then the rowkey column families will be read and converted to string. Otherwise they are read with BYTES type values and users need to manually cast them with CAST if necessary. The default value is false. */ - expirationMs?: string; + readRowkeyAsString?: boolean; /** - * [Beta] [Optional] If not set, the table is partitioned by pseudo column, referenced via either '_PARTITIONTIME' as TIMESTAMP type, or '_PARTITIONDATE' as DATE type. If field is specified, the table is instead partitioned by this field. The field must be a top-level TIMESTAMP or DATE field. Its mode must be NULLABLE or REQUIRED. + * [Optional] List of column families to expose in the table schema along with their types. This list restricts the column families that can be referenced in queries and specifies their value types. You can use this list to do type conversions - see the 'type' field for more details. If you leave this list empty, all column families are present in the table schema and their values are read as BYTES. During a query only the column families referenced in that query are read from Bigtable. */ - field?: string; - requirePartitionFilter?: boolean; + columnFamilies?: Array; /** - * [Required] The only type supported is DAY, which will generate one partition per day. + * [Optional] If field is true, then the column families that are not specified in columnFamilies list are not exposed in the table schema. Otherwise, they are read with BYTES type values. The default value is false. */ - type?: string; + ignoreUnspecifiedColumnFamilies?: boolean; }; - type IUserDefinedFunctionResource = { + type IEncryptionConfiguration = { /** - * [Pick one] An inline resource that contains code for a user-defined function (UDF). Providing a inline code resource is equivalent to providing a URI for a file containing the same code. + * [Optional] Describes the Cloud KMS encryption key that will be used to protect destination BigQuery table. The BigQuery Service Account associated with your project requires access to this encryption key. */ - inlineCode?: string; + kmsKeyName?: string; + }; + + type ITableSchema = { /** - * [Pick one] A code resource to load from a Google Cloud Storage URI (gs://bucket/path). + * Describes the fields in a table. */ - resourceUri?: string; + fields?: Array; }; - type IViewDefinition = { + type IDestinationTableProperties = { /** - * [Required] A query that BigQuery executes when the view is referenced. + * [Optional] The friendly name for the destination table. This will only be used if the destination table is newly created. If the table already exists and a value different than the current friendly name is provided, the job will fail. */ - query?: string; + friendlyName?: string; /** - * Specifies whether to use BigQuery's legacy SQL for this view. The default value is true. If set to false, the view will use BigQuery's standard SQL: https://cloud.google.com/bigquery/sql-reference/ Queries and views that reference this view must use the same flag value. + * [Optional] The description for the destination table. This will only be used if the destination table is newly created. If the table already exists and a value different than the current description is provided, the job will fail. */ - useLegacySql?: boolean; + description?: string; /** - * Describes user-defined function resources used in the query. + * [Optional] The labels associated with this table. You can use these to organize and group your tables. This will only be used if the destination table is newly created. If the table already exists and labels are different than the current labels are provided, the job will fail. */ - userDefinedFunctionResources?: Array; + labels?: { [key: string]: string }; }; namespace datasets { @@ -1924,6 +2511,14 @@ declare namespace bigquery { * Lists all datasets in the specified project to which you have been granted the READER dataset role. */ type IListParams = { + /** + * Page token, returned by a previous call, to request the next page of results + */ + pageToken?: string; + /** + * The maximum number of results to return + */ + maxResults?: number; /** * Whether to list all datasets, including hidden ones */ @@ -1932,18 +2527,54 @@ declare namespace bigquery { * An expression for filtering the results of the request by label. The syntax is "labels.[:]". Multiple filters can be ANDed together by connecting with a space. Example: "labels.department:receiving labels.active". See Filtering datasets using labels for details. */ filter?: string; + }; + } + + namespace models { + /** + * Lists all models in the specified dataset. Requires the READER dataset + * role. + */ + type IListParams = { /** - * The maximum number of results to return + * Page token, returned by a previous call to request the next page of + * results + */ + pageToken?: string; + /** + * The maximum number of results per page. */ maxResults?: number; + }; + } + + namespace jobs { + /** + * Retrieves the results of a query job. + */ + type IGetQueryResultsParams = { /** * Page token, returned by a previous call, to request the next page of results */ pageToken?: string; + /** + * How long to wait for the query to complete, in milliseconds, before returning. Default is 10 seconds. If the timeout passes before the job completes, the 'jobComplete' field in the response will be false + */ + timeoutMs?: number; + /** + * Maximum number of results to read + */ + maxResults?: number; + /** + * Zero-based index of the starting row + */ + startIndex?: string; + /** + * The geographic location where the job should run. Required except for US and EU. See details at https://cloud.google.com/bigquery/docs/locations#specifying_your_location. + */ + location?: string; }; - } - namespace jobs { /** * Requests that a job be cancelled. This call will return immediately, and the client will need to poll for the job status to see if the cancel completed successfully. Cancelled jobs may still incur costs. */ @@ -1965,35 +2596,21 @@ declare namespace bigquery { }; /** - * Retrieves the results of a query job. + * Lists all jobs that you started in the specified project. Job information is available for a six month period after creation. The job list is sorted in reverse chronological order, by job creation time. Requires the Can View project role, or the Is Owner project role if you set the allUsers property. */ - type IGetQueryResultsParams = { + type IListParams = { /** - * The geographic location where the job should run. Required except for US and EU. See details at https://cloud.google.com/bigquery/docs/locations#specifying_your_location. + * Restrict information returned to a set of selected fields */ - location?: string; + projection?: 'full' | 'minimal'; /** - * Maximum number of results to read + * Min value for job creation time, in milliseconds since the POSIX epoch. If set, only jobs created after or at this timestamp are returned */ - maxResults?: number; + minCreationTime?: string; /** * Page token, returned by a previous call, to request the next page of results */ pageToken?: string; - /** - * Zero-based index of the starting row - */ - startIndex?: string; - /** - * How long to wait for the query to complete, in milliseconds, before returning. Default is 10 seconds. If the timeout passes before the job completes, the 'jobComplete' field in the response will be false - */ - timeoutMs?: number; - }; - - /** - * Lists all jobs that you started in the specified project. Job information is available for a six month period after creation. The job list is sorted in reverse chronological order, by job creation time. Requires the Can View project role, or the Is Owner project role if you set the allUsers property. - */ - type IListParams = { /** * Whether to display jobs owned by all users in the project. Default false */ @@ -2006,18 +2623,6 @@ declare namespace bigquery { * Maximum number of results to return */ maxResults?: number; - /** - * Min value for job creation time, in milliseconds since the POSIX epoch. If set, only jobs created after or at this timestamp are returned - */ - minCreationTime?: string; - /** - * Page token, returned by a previous call, to request the next page of results - */ - pageToken?: string; - /** - * Restrict information returned to a set of selected fields - */ - projection?: 'full' | 'minimal'; /** * Filter for job state */ @@ -2030,14 +2635,14 @@ declare namespace bigquery { * Lists all projects to which you have been granted any project role. */ type IListParams = { - /** - * Maximum number of results to return - */ - maxResults?: number; /** * Page token, returned by a previous call, to request the next page of results */ pageToken?: string; + /** + * Maximum number of results to return + */ + maxResults?: number; }; } @@ -2046,14 +2651,6 @@ declare namespace bigquery { * Retrieves table data from a specified set of rows. Requires the READER dataset role. */ type IListParams = { - /** - * Maximum number of results to return - */ - maxResults?: number; - /** - * Page token, returned by a previous call, identifying the result set - */ - pageToken?: string; /** * List of fields to return (comma-separated). If unspecified, all fields are returned */ @@ -2062,6 +2659,14 @@ declare namespace bigquery { * Zero-based index of the starting row to read */ startIndex?: string; + /** + * Page token, returned by a previous call, identifying the result set + */ + pageToken?: string; + /** + * Maximum number of results to return + */ + maxResults?: number; }; } @@ -2080,14 +2685,14 @@ declare namespace bigquery { * Lists all tables in the specified dataset. Requires the READER dataset role. */ type IListParams = { - /** - * Maximum number of results to return - */ - maxResults?: number; /** * Page token, returned by a previous call, to request the next page of results */ pageToken?: string; + /** + * Maximum number of results to return + */ + maxResults?: number; }; } } From c7a45dd0f392e142765b18511ef734d0d8fffaa5 Mon Sep 17 00:00:00 2001 From: Dave Gramlich Date: Tue, 21 May 2019 15:11:03 -0400 Subject: [PATCH 3/9] set get models callback as optional --- src/dataset.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/dataset.ts b/src/dataset.ts index 3911e75ee..daeb15790 100644 --- a/src/dataset.ts +++ b/src/dataset.ts @@ -623,7 +623,7 @@ class Dataset extends ServiceObject { */ getModels( optsOrCb?: GetModelsOptions | GetModelsCallback, - cb: GetModelsCallback + cb?: GetModelsCallback ): void | Promise { const options = typeof optsOrCb === 'object' ? optsOrCb : {}; const callback = typeof optsOrCb === 'function' ? optsOrCb : cb; From 34464e9ab93f2a30bbc8b1557c95534d172a8811 Mon Sep 17 00:00:00 2001 From: Dave Gramlich Date: Tue, 21 May 2019 16:47:16 -0400 Subject: [PATCH 4/9] model system tests --- system-test/bigquery.ts | 52 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/system-test/bigquery.ts b/system-test/bigquery.ts index 8ca8fe66e..5b76f2916 100644 --- a/system-test/bigquery.ts +++ b/system-test/bigquery.ts @@ -30,6 +30,7 @@ import { Dataset, GetDatasetsOptions, Job, + Model, RowMetadata, Table, } from '../src'; @@ -623,6 +624,57 @@ describe('BigQuery', () => { }); }); + describe('BigQuery/Model', () => { + let model: Model; + + before(() => { + model = dataset.model('testmodel'); + return bigquery.query(` + CREATE MODEL \`${dataset.id}.${model.id}\` + OPTIONS ( + model_type='linear_reg', + max_iterations=1, + learn_rate=0.4, + learn_rate_strategy='constant' + ) AS ( + SELECT 'a' AS f1, 2.0 AS label + UNION ALL + SELECT 'b' AS f2, 3.8 AS label + ) + `); + }); + + after(() => model.delete()); + + it('should get a list of models', async () => { + const [models] = await dataset.getModels(); + assert.strictEqual(models.length, 1); + assert.ok(models[0] instanceof Model); + }); + + it('should check if a model exists', async () => { + const [exists] = await model.exists(); + assert.ok(exists); + }); + + it('should get a model', async () => { + const [model2] = await model.get(); + assert.deepStrictEqual(model, model2); + }); + + it('should get a model metadata', async () => { + const [metadata] = await model.getMetadata(); + assert.deepStrictEqual(metadata, model.metadata); + }); + + it('should set model metadata', async () => { + const friendlyName = 'modelfriend'; + await model.setMetadata({friendlyName}); + const [metadata] = await model.getMetadata(); + assert.strictEqual(metadata.friendlyName, friendlyName); + }); + }); + describe('BigQuery/Table', () => { const TEST_DATA_JSON_PATH = require.resolve( '../../system-test/data/kitten-test-data.json' From 0fbd26f310ff61b174d368bdb29596af38b0522a Mon Sep 17 00:00:00 2001 From: Dave Gramlich Date: Tue, 21 May 2019 16:47:40 -0400 Subject: [PATCH 5/9] export model class --- src/index.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/index.ts b/src/index.ts index 651bb527f..98f53ef45 100644 --- a/src/index.ts +++ b/src/index.ts @@ -27,6 +27,7 @@ import * as uuid from 'uuid'; import {Dataset, DatasetOptions} from './dataset'; import {Job, JobOptions, QueryResultsOptions} from './job'; +import {Model} from './model'; import { Table, TableField, @@ -1715,6 +1716,15 @@ export {Dataset}; */ export {Job}; +/** + * {@link Model} class. + * + * @name BigQuery.Model + * @see Model + * @type {constructor} + */ +export {Model}; + /** * {@link Table} class. * From 58c8347e22726d31a404bd113deb332bb6381d3c Mon Sep 17 00:00:00 2001 From: Dave Gramlich Date: Tue, 21 May 2019 16:48:04 -0400 Subject: [PATCH 6/9] blacklist model method from being promisified --- src/dataset.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/dataset.ts b/src/dataset.ts index daeb15790..5c6de53e0 100644 --- a/src/dataset.ts +++ b/src/dataset.ts @@ -57,7 +57,7 @@ export interface DatasetOptions { export type CreateDatasetOptions = bigquery.IDataset; export type GetModelsOptions = PagedRequest; -export type GetModelsResponse = PagedRequest< +export type GetModelsResponse = PagedResponse< Model, GetModelsOptions, bigquery.IListModelsResponse @@ -647,7 +647,7 @@ class Dataset extends ServiceObject { } const models = (resp.models || []).map(modelObject => { - const model = this.model(modelObject.modelReference.modelId); + const model = this.model(modelObject.modelReference!.modelId!); model.metadata = modelObject; return model; }); @@ -851,7 +851,7 @@ paginator.extend(Dataset, ['getModels', 'getTables']); * that a callback is omitted. */ promisifyAll(Dataset, { - exclude: ['table'], + exclude: ['model', 'table'], }); /** From eaa46e295bac4a0a5e1ca776e958aba47c0acb76 Mon Sep 17 00:00:00 2001 From: Dave Gramlich Date: Tue, 21 May 2019 17:08:29 -0400 Subject: [PATCH 7/9] unit tests --- test/dataset.ts | 140 +++++++++++++++++++++++++++++++++++++++++++++++- test/model.ts | 67 +++++++++++++++++++++++ 2 files changed, 205 insertions(+), 2 deletions(-) create mode 100644 test/model.ts diff --git a/test/dataset.ts b/test/dataset.ts index d4c03a69f..0e390fb51 100644 --- a/test/dataset.ts +++ b/test/dataset.ts @@ -37,7 +37,7 @@ const fakePfy = extend({}, pfy, { return; } promisified = true; - assert.deepStrictEqual(options.exclude, ['table']); + assert.deepStrictEqual(options.exclude, ['model', 'table']); }, }); @@ -50,7 +50,7 @@ const fakePaginator = { } methods = arrify(methods); assert.strictEqual(c.name, 'Dataset'); - assert.deepStrictEqual(methods, ['getTables']); + assert.deepStrictEqual(methods, ['getModels', 'getTables']); extended = true; }, streamify: (methodName: string) => { @@ -104,6 +104,7 @@ describe('BigQuery/Dataset', () => { it('should streamify the correct methods', () => { assert.strictEqual(ds.getTablesStream, 'getTables'); + assert.strictEqual(ds.getModelsStream, 'getModels'); }); it('should promisify all the things', () => { @@ -621,6 +622,127 @@ describe('BigQuery/Dataset', () => { }); }); + describe('getModels', () => { + it('should get models from the api', done => { + ds.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.uri, '/models'); + assert.deepStrictEqual(reqOpts.qs, {}); + done(); + }; + + ds.getModels(assert.ifError); + }); + + it('should accept a query', done => { + const query = { + maxResults: 8, + pageToken: 'token', + }; + + ds.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.qs, query); + done(); + }; + + ds.getModels(query, assert.ifError); + }); + + it('should default the query value to an empty object', done => { + ds.request = (reqOpts: DecorateRequestOptions) => { + assert.deepStrictEqual(reqOpts.qs, {}); + done(); + }; + + ds.getModels(assert.ifError); + }); + + it('should return error to callback', done => { + const error = new Error('Error.'); + + ds.request = (reqOpts: DecorateRequestOptions, callback: Function) => { + callback(error); + }; + + ds.getModels((err: Error) => { + assert.strictEqual(err, error); + done(); + }); + }); + + describe('success', () => { + const modelId = 'modelName'; + const apiResponse = { + models: [ + { + a: 'b', + c: 'd', + modelReference: {modelId}, + }, + ], + }; + + beforeEach(() => { + ds.request = (reqOpts: DecorateRequestOptions, callback: Function) => { + callback(null, apiResponse); + }; + }); + + it('should return Model & apiResponse', done => { + ds.getModels( + ( + err: Error, + models: _root.Model[], + nextQuery: {}, + apiResponse_: {} + ) => { + assert.ifError(err); + + const model = models[0]; + + assert(model instanceof _root.Model); + assert.strictEqual(model.id, modelId); + assert.strictEqual(apiResponse_, apiResponse); + done(); + } + ); + }); + + it('should assign metadata to the Model objects', done => { + ds.getModels((err: Error, models: _root.Model[]) => { + assert.ifError(err); + assert.strictEqual(models[0].metadata, apiResponse.models[0]); + done(); + }); + }); + + it('should return token if more results exist', done => { + const pageToken = 'token'; + + const query = { + maxResults: 5, + }; + + const expectedNextQuery = { + maxResults: 5, + pageToken, + }; + + ds.request = (reqOpts: DecorateRequestOptions, callback: Function) => { + callback(null, {nextPageToken: pageToken}); + }; + + ds.getModels( + query, + (err: Error, tables: _root.Model[], nextQuery: {}) => { + assert.ifError(err); + assert.deepStrictEqual(nextQuery, expectedNextQuery); + done(); + } + ); + }); + }); + }); + describe('getTables', () => { it('should get tables from the api', done => { ds.request = (reqOpts: DecorateRequestOptions) => { @@ -744,6 +866,20 @@ describe('BigQuery/Dataset', () => { }); }); + describe('model', () => { + it('should throw an error if the id is missing', () => { + const expectedErr = /A model ID is required\./; + assert.throws(() => ds.model(), expectedErr); + }); + + it('should return a Model object', () => { + const modelId = 'modelId'; + const model = ds.model(modelId); + assert(model instanceof _root.Model); + assert.strictEqual(model.id, modelId); + }); + }); + describe('query', () => { const options = { a: 'b', diff --git a/test/model.ts b/test/model.ts new file mode 100644 index 000000000..a75663b84 --- /dev/null +++ b/test/model.ts @@ -0,0 +1,67 @@ +/** + * Copyright 2019 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. + */ + +import * as assert from 'assert'; +import * as proxyquire from 'proxyquire'; +import * as m from '../src/model'; +import {Dataset} from '../src/dataset'; + +class FakeServiceObject { + _calledWith: IArguments; + constructor() { + this._calledWith = arguments; + } +} + +describe('BigQuery/Model', () => { + const MODEL_ID = 'my_model'; + const DATASET = {id: 'my_dataset'} as Dataset; + + // tslint:disable-next-line no-any variable-name + let Model: typeof m.Model; + let model: m.Model; + + before(() => { + Model = proxyquire('../src/model.js', { + '@google-cloud/common': { + ServiceObject: FakeServiceObject, + }, + }).Model; + }); + + beforeEach(() => { + model = new Model(DATASET, MODEL_ID); + }); + + describe('instantiation', () => { + it('should inherit from ServiceObject', () => { + assert(model instanceof FakeServiceObject); + + const [config] = ((model as {}) as FakeServiceObject)._calledWith; + + assert.strictEqual(config.parent, DATASET); + assert.strictEqual(config.baseUrl, '/models'); + assert.strictEqual(config.id, MODEL_ID); + assert.deepStrictEqual(config.methods, { + delete: true, + exists: true, + get: true, + getMetadata: true, + setMetadata: true, + }); + }); + }); +}); From c29ff141c5513ff948ac77f3724271d6f71ebf1e Mon Sep 17 00:00:00 2001 From: Dave Gramlich Date: Tue, 21 May 2019 17:10:30 -0400 Subject: [PATCH 8/9] remove no-any flag --- test/model.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/model.ts b/test/model.ts index a75663b84..717b23427 100644 --- a/test/model.ts +++ b/test/model.ts @@ -30,7 +30,7 @@ describe('BigQuery/Model', () => { const MODEL_ID = 'my_model'; const DATASET = {id: 'my_dataset'} as Dataset; - // tslint:disable-next-line no-any variable-name + // tslint:disable-next-line variable-name let Model: typeof m.Model; let model: m.Model; From 6febf18d1daf7bfcd992ed32f2816dd0b028d6e1 Mon Sep 17 00:00:00 2001 From: Dave Gramlich Date: Tue, 21 May 2019 20:58:12 -0400 Subject: [PATCH 9/9] various doc fixes --- src/dataset.ts | 2 +- src/model.ts | 28 +++++++++++++++------------- 2 files changed, 16 insertions(+), 14 deletions(-) diff --git a/src/dataset.ts b/src/dataset.ts index 5c6de53e0..db90d7cfa 100644 --- a/src/dataset.ts +++ b/src/dataset.ts @@ -749,7 +749,7 @@ class Dataset extends ServiceObject { } /** - * Create a Model object. + * Create a {@link Model} object. * * @throws {TypeError} if model ID is missing. * diff --git a/src/model.ts b/src/model.ts index 5ccadb1c3..59fdf36d9 100644 --- a/src/model.ts +++ b/src/model.ts @@ -36,7 +36,7 @@ class Model extends common.ServiceObject { constructor(dataset: Dataset, id: string) { const methods = { /** - * Delete a model. + * Delete the model. * * @see [Models: delete API Documentation]{@link https://cloud.google.com/bigquery/docs/reference/rest/v2/models/delete} * @@ -55,7 +55,7 @@ class Model extends common.ServiceObject { * * model.delete((err, apiResponse) => {}); * - * @example * const [apiResponse] = await model.delete(); */ @@ -79,7 +79,7 @@ class Model extends common.ServiceObject { * * model.exists((err, exists) => {}); * - * @example * const [exists] = await model.exists(); */ @@ -104,18 +104,20 @@ class Model extends common.ServiceObject { * const dataset = bigquery.dataset('my-dataset'); * const model = dataset.model('my-model'); * - * model.get((err, model2, apiResponse) => { - * // `model.metadata` has been populated. + * model.get(err => { + * if (!err) { + * // `model.metadata` has been populated. + * } * }); * - * @example - * const [model2, apiResponse] = await model.get(); + * await model.get(); */ get: true, /** - * Return the metadata associated with the Model. + * Return the metadata associated with the model. * * @see [Models: get API Documentation]{@link https://cloud.google.com/bigquery/docs/reference/rest/v2/models/get} * @@ -123,7 +125,7 @@ class Model extends common.ServiceObject { * @param {function} [callback] The callback function. * @param {?error} callback.err An error returned while making this * request. - * @param {object} callback.metadata The metadata of the Model. + * @param {object} callback.metadata The metadata of the model. * @param {object} callback.apiResponse The full API response. * @returns {Promise} * @@ -135,7 +137,7 @@ class Model extends common.ServiceObject { * * model.getMetadata((err, metadata, apiResponse) => {}); * - * @example * const [metadata, apiResponse] = await model.getMetadata(); */ @@ -149,7 +151,7 @@ class Model extends common.ServiceObject { * @param {function} [callback] The callback function. * @param {?error} callback.err An error returned while making this * request. - * @param {object} callback.metadata The updated metadata of the Model. + * @param {object} callback.metadata The updated metadata of the model. * @param {object} callback.apiResponse The full API response. * @returns {Promise} * @@ -160,12 +162,12 @@ class Model extends common.ServiceObject { * const model = dataset.model('my-model'); * * const metadata = { - * friendlyName: 'thebestmodelever' + * friendlyName: 'TheBestModelEver' * }; * * model.setMetadata(metadata, (err, metadata, apiResponse) => {}); * - * @example * const [metadata, apiResponse] = await model.setMetadata(metadata); */
If you anticipate many results, you can end a stream + * early to prevent unnecessary processing and API requests.To control how many API requests are made and page + * through the results manually, set `autoPaginate` to `false`.If the callback is omitted, we'll return a Promise. + * If the callback is omitted we'll return a Promise + * If the callback is omitted we'll return a Promise + * If the callback is omitted we'll return a Promise + * If the callback is omitted we'll return a Promise + * If the callback is omitted we'll return a Promise + * If the callback is omitted we'll return a Promise + * @example If the callback is omitted we'll return a Promise. * If the callback is omitted we'll return a Promise + * @example If the callback is omitted we'll return a Promise. * If the callback is omitted we'll return a Promise + * @example If the callback is omitted we'll return a Promise. * If the callback is omitted we'll return a Promise + * @example If the callback is omitted we'll return a Promise. * If the callback is omitted we'll return a Promise + * @example If the callback is omitted we'll return a Promise. *