google_cloud_bigquery/http/job/
mod.rs

1use std::collections::HashMap;
2
3use time::OffsetDateTime;
4
5use crate::http::dataset::DatasetReference;
6use crate::http::model::{HparamTuningTrial, IterationResult, ModelReference, ModelType};
7use crate::http::routine::RoutineReference;
8use crate::http::row_access_policy::RowAccessPolicyReference;
9use crate::http::table::{
10    Clustering, DecimalTargetType, DestinationFormat, ExternalDataConfiguration, HivePartitioningOptions,
11    ParquetOptions, RangePartitioning, SourceFormat, TableReference, TableSchema, TimePartitioning,
12    UserDefinedFunctionResource,
13};
14use crate::http::types::{ConnectionProperty, EncryptionConfiguration, ErrorProto, QueryParameter};
15
16pub mod cancel;
17pub mod delete;
18pub mod get;
19pub mod get_query_results;
20pub mod insert;
21pub mod list;
22pub mod query;
23
24#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
25#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
26pub enum KeyResultStatementKind {
27    #[default]
28    Last,
29    FirstSelect,
30}
31
32#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
33#[serde(rename_all = "camelCase")]
34pub struct ScriptOptions {
35    /// Timeout period for each statement in a script.
36    #[serde(deserialize_with = "crate::http::from_str_option")]
37    #[serde(default)]
38    pub statement_timeout_ms: Option<i64>,
39    /// Limit on the number of bytes billed per statement. Exceeding this budget results in an error.
40    #[serde(deserialize_with = "crate::http::from_str_option")]
41    #[serde(default)]
42    pub statement_byte_budget: Option<i64>,
43    /// Determines which statement in the script represents the "key result",
44    /// used to populate the schema and query results of the script job. Default is LAST.
45    pub key_result_statement: Option<KeyResultStatementKind>,
46}
47
48#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
49#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
50pub enum CreateDisposition {
51    /// If the table does not exist, BigQuery creates the table.
52    #[default]
53    CreateIfNeeded,
54    /// The table must already exist. If it does not, a 'notFound' error is returned in the job result.
55    CreateNever,
56}
57
58#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
59#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
60pub enum WriteDisposition {
61    /// If the table already exists, BigQuery overwrites the table data and uses the schema from the query result..
62    WriteTruncate,
63    /// If the table already exists, BigQuery appends the data to the table..
64    WriteAppend,
65    /// If the table already exists and contains data, a 'duplicate' error is returned in the job result.
66    #[default]
67    WriteEmpty,
68}
69
70#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
71#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
72pub enum Priority {
73    #[default]
74    Interactive,
75    Batch,
76}
77#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug)]
78#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
79pub enum SchemaUpdateOption {
80    /// allow adding a nullable field to the schema.
81    AllowFieldAddition,
82    /// allow relaxing a required field in the original schema to nullable.
83    AllowFieldRelaxation,
84}
85
86#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
87#[serde(rename_all = "camelCase")]
88pub struct JobConfigurationLoad {
89    /// [Required] The fully-qualified URIs that point to your data in Google Cloud.
90    /// 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.
91    pub source_uris: Vec<String>,
92    /// 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.
93    pub schema: Option<TableSchema>,
94    /// [Required] The destination table to load the data into.
95    pub destination_table: TableReference,
96    /// Optional. [Experimental] Properties with which to create the destination table if it is new.
97    pub destination_table_properties: Option<DestinationTableProperties>,
98    /// Optional. Specifies whether the job is allowed to create new tables. The following values are supported:
99    /// CREATE_IF_NEEDED: If the table does not exist, BigQuery creates the table.
100    /// 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.
101    pub create_disposition: Option<CreateDisposition>,
102    /// Optional. Specifies the action that occurs if the destination table already exists. The following values are supported:
103    /// WRITE_TRUNCATE: If the table already exists, BigQuery overwrites the table data and uses the schema from the load.
104    /// WRITE_APPEND: If the table already exists, BigQuery appends the data to the table.
105    /// WRITE_EMPTY: If the table already exists and contains data, a 'duplicate' error is returned in the job result.
106    /// 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.
107    pub write_disposition: Option<WriteDisposition>,
108    /// Optional. Specifies a string that represents a null value in a CSV file.
109    /// 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.
110    pub null_marker: Option<String>,
111    /// Optional. The separator character for fields in a CSV file.
112    /// The separator is interpreted as a single byte. For files encoded in ISO-8859-1, any single character can be used as a separator. For files encoded in UTF-8, characters represented in decimal range 1-127 (U+0001-U+007F) can be used without any modification. UTF-8 characters encoded with multiple bytes (i.e. U+0080 and above) will have only the first byte used for separating fields. The remaining bytes will be treated as a part of the field. BigQuery also supports the escape sequence "\t" (U+0009) to specify a tab separator. The default value is comma (",", U+002C).
113    pub field_delimiter: Option<String>,
114    /// 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. When autodetect is on, the behavior is the following:
115    /// 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.
116    /// skipLeadingRows is 0 - Instructs autodetect that there are no headers and data should be read starting from the first row.
117    /// 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.
118    pub skip_leading_rows: Option<i64>,
119    /// Optional. The character encoding of the data.
120    /// The supported values are UTF-8, ISO-8859-1, UTF-16BE, UTF-16LE, UTF-32BE, and UTF-32LE. 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.
121    /// If you don't specify an encoding, or if you specify a UTF-8 encoding when the CSV file is not UTF-8 encoded, BigQuery attempts to convert the data to UTF-8. Generally, your data loads successfully, but it may not match byte-for-byte what you expect. To avoid this, specify the correct encoding by using the --encoding flag.
122    /// If BigQuery can't convert a character other than the ASCII 0 character, BigQuery converts the character to the standard Unicode replacement character: �.
123    pub encoding: Option<String>,
124    /// 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. To include the specific quote character within a quoted value, precede it with an additional matching quote character. For example, if you want to escape the default character ' " ', use ' "" '. @default "
125    pub quote: Option<String>,
126    /// Optional. The maximum number of bad records that BigQuery can ignore when running the job.
127    /// If the number of bad records exceeds this value, an invalid error is returned in the job result. The default value is 0, which requires that all records are valid. This is only supported for CSV and NEWLINE_DELIMITED_JSON file formats.
128    pub max_bad_records: Option<i64>,
129    /// Indicates if BigQuery should allow quoted data sections that contain newline characters in a CSV file.
130    /// The default value is false.
131    pub allow_quoted_newlines: Option<bool>,
132    /// Optional. The format of the data files.
133    /// For CSV files, specify "CSV".
134    /// For datastore backups, specify "DATASTORE_BACKUP".
135    /// For newline-delimited JSON, specify "NEWLINE_DELIMITED_JSON".
136    /// For Avro, specify "AVRO".
137    /// For parquet, specify "PARQUET".
138    /// For orc, specify "ORC".
139    /// The default value is CSV.
140    pub source_format: Option<SourceFormat>,
141    /// Optional. Accept rows that are missing trailing optional columns.
142    /// The missing values are treated as nulls.
143    /// If false, records with missing trailing columns are treated as bad records,
144    /// and if there are too many bad records, an invalid error is returned in the job result.
145    /// The default value is false.
146    /// Only applicable to CSV, ignored for other formats.
147    pub allow_jagged_rows: Option<bool>,
148    /// Optional. Indicates if BigQuery should allow extra values that are not represented in the table schema.
149    /// If true, the extra values are ignored.
150    /// If false, records with extra columns are treated as bad records, and if there are too many bad records,
151    /// an invalid error is returned in the job result.
152    /// The default value is false.
153    /// The sourceFormat property determines what BigQuery treats as an extra value:
154    /// CSV: Trailing columns JSON: Named values that don't match any column names in the
155    /// table schema Avro, Parquet, ORC: Fields in the file schema that don't exist in the table schema.
156    pub ignore_unknown_values: Option<bool>,
157    /// If sourceFormat is set to "DATASTORE_BACKUP",
158    /// indicates which entity properties to load into BigQuery from a Cloud Datastore backup.
159    /// Property names are case sensitive and must be top-level properties.
160    /// If no properties are specified, BigQuery loads all properties.
161    /// If any named property isn't found in the Cloud Datastore backup,
162    /// an invalid error is returned in the job result.
163    pub projection_fields: Option<Vec<String>>,
164    /// Optional. Indicates if we should automatically infer the options and schema for CSV and JSON sources.
165    pub autodetect: Option<bool>,
166    /// Allows the schema of the destination table to be updated as a side effect of
167    /// the load job if a schema is autodetected or supplied in the job configuration.
168    /// Schema update options are supported in two cases:
169    /// when writeDisposition is WRITE_APPEND;
170    /// when writeDisposition is WRITE_TRUNCATE
171    /// and the destination table is a partition of a table,
172    /// specified by partition decorators. For normal tables, WRITE_TRUNCATE will always overwrite the schema.
173    /// One or more of the following values are specified:
174    /// ALLOW_FIELD_ADDITION: allow adding a nullable field to the schema.
175    /// ALLOW_FIELD_RELAXATION: allow relaxing a required field in the original schema to nullable.
176    pub schema_update_options: Option<Vec<SchemaUpdateOption>>,
177    /// Time-based partitioning specification for the destination table.
178    /// Only one of timePartitioning and rangePartitioning should be specified.
179    pub time_partitioning: Option<TimePartitioning>,
180    /// Range partitioning specification for the destination table.
181    /// Only one of timePartitioning and rangePartitioning should be specified.
182    pub range_partitioning: Option<RangePartitioning>,
183    /// Clustering specification for the destination table.
184    pub clustering: Option<Clustering>,
185    /// Custom encryption configuration (e.g., Cloud KMS keys)
186    pub destination_encryption_configuration: Option<EncryptionConfiguration>,
187    /// Optional. If sourceFormat is set to "AVRO", indicates whether to interpret logical types as the corresponding BigQuery data type (for example, TIMESTAMP), instead of using the raw type (for example, INTEGER).
188    pub use_avro_logical_types: Option<bool>,
189    /// Optional. The user can provide a reference file with the reader schema. This file is only loaded if it is part of source URIs, but is not loaded otherwise. It is enabled for the following formats: AVRO, PARQUET, ORC.
190    pub reference_file_schema_uri: Option<String>,
191    /// Optional. When set, configures hive partitioning support.
192    /// Not all storage formats support hive partitioning -- requesting hive partitioning on an unsupported format will lead to an error, as will providing an invalid specification.
193    pub hive_partitioning_options: Option<HivePartitioningOptions>,
194    /// Defines the list of possible SQL data types to which the source decimal values are converted.
195    /// This list and the precision and the scale parameters of the decimal field determine the target type.
196    /// In the order of NUMERIC, BIGNUMERIC, and STRING,
197    /// a type is picked if it is in the specified list and if it supports the precision and the scale. STRING supports all precision and scale values. If none of the listed types supports the precision and the scale, the type supporting the widest range in the specified list is picked, and if a value exceeds the supported range when reading the data, an error will be thrown.
198    /// Example: Suppose the value of this field is ["NUMERIC", "BIGNUMERIC"]. If (precision,scale) is:
199    /// - (38,9)  NUMERIC;
200    /// - (39,9)  BIGNUMERIC (NUMERIC cannot hold 30 integer digits);
201    /// - (38,10)  BIGNUMERIC (NUMERIC cannot hold 10 fractional digits);
202    /// - (76,38)  BIGNUMERIC;
203    /// - (77,38)  BIGNUMERIC (error if value exeeds supported range).
204    ///   This field cannot contain duplicate types. The order of the types in this field is ignored. For example, ["BIGNUMERIC", "NUMERIC"] is the same as ["NUMERIC", "BIGNUMERIC"] and NUMERIC always takes precedence over BIGNUMERIC.
205    ///
206    /// Defaults to ["NUMERIC", "STRING"] for ORC and ["NUMERIC"] for the other file formats.
207    pub decimal_target_types: Option<Vec<DecimalTargetType>>,
208    /// Optional. Additional properties to set if sourceFormat is set to PARQUET.
209    pub parquet_options: Option<ParquetOptions>,
210    /// Optional. When sourceFormat is set to "CSV", this indicates whether the embedded ASCII control characters (the first 32 characters in the ASCII-table, from '\x00' to '\x1F') are preserved.
211    pub preserve_ascii_control_characters: Option<bool>,
212}
213
214#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug)]
215#[serde(rename_all = "camelCase")]
216pub enum JobConfigurationSourceTable {
217    SourceTable(TableReference),
218    SourceTables(Vec<TableReference>),
219}
220
221impl Default for JobConfigurationSourceTable {
222    fn default() -> Self {
223        Self::SourceTable(TableReference::default())
224    }
225}
226
227#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
228#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
229pub enum OperationType {
230    #[default]
231    OperationTypeUnspecified,
232    Copy,
233    Snapshot,
234    Restore,
235    Clone,
236}
237
238#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
239#[serde(rename_all = "camelCase")]
240pub struct JobConfigurationTableCopy {
241    #[serde(flatten)]
242    pub source_table: JobConfigurationSourceTable,
243    pub destination_table: TableReference,
244    /// Optional. Specifies whether the job is allowed to create new tables. The following values are supported:
245    /// CREATE_IF_NEEDED: If the table does not exist, BigQuery creates the table.
246    /// CREATE_NEVER: The table must already exist. If it does not, a 'notFound' error is returned in the job result.
247    /// The default value is CREATE_IF_NEEDED. Creation, truncation and append actions occur as one atomic update upon job completion.
248    pub create_disposition: Option<CreateDisposition>,
249    /// Optional. Specifies the action that occurs if the destination table already exists. The following values are supported:
250    /// WRITE_TRUNCATE: If the table already exists, BigQuery overwrites the table data and uses the schema from the source table.
251    /// WRITE_APPEND: If the table already exists, BigQuery appends the data to the table.
252    /// WRITE_EMPTY: If the table already exists and contains data, a 'duplicate' error is returned in the job result.
253    /// 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.
254    pub write_disposition: Option<WriteDisposition>,
255    /// Custom encryption configuration (e.g., Cloud KMS keys).
256    pub destination_encryption_configuration: Option<EncryptionConfiguration>,
257    /// Optional. Supported operation types in table copy job.
258    pub operation_type: Option<OperationType>,
259    /// Optional. The time when the destination table expires.
260    /// Expired tables will be deleted and their storage reclaimed.
261    #[serde(default, with = "time::serde::rfc3339::option")]
262    pub destination_expiration_time: Option<OffsetDateTime>,
263}
264
265#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
266#[serde(rename_all = "camelCase")]
267pub struct DestinationTableProperties {
268    /// Optional. Friendly name for the destination table.
269    /// If the table already exists, it should be same as the existing friendly name.
270    pub friendly_name: Option<String>,
271    /// Optional. The description for the destination table.
272    /// This will only be used if the destination table is newly created.
273    /// If the table already exists and a value different than the current description is provided, the job will fail.
274    pub description: Option<String>,
275    /// Optional. The labels associated with this table.
276    /// You can use these to organize and group your tables.
277    /// This will only be used if the destination table is newly created.
278    /// If the table already exists and labels are different than the current labels are provided, the job will fail.
279    /// An object containing a list of "key": value pairs.
280    /// Example: { "name": "wrench", "mass": "1.3kg", "count": "3" }.
281    pub labels: Option<HashMap<String, String>>,
282}
283
284#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug)]
285#[serde(rename_all = "camelCase")]
286pub enum JobConfigurationExtractSource {
287    SourceTable(TableReference),
288    SourceModel(ModelReference),
289}
290
291impl Default for JobConfigurationExtractSource {
292    fn default() -> Self {
293        Self::SourceTable(TableReference::default())
294    }
295}
296
297#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
298#[serde(rename_all = "camelCase")]
299pub struct ModelExtractOptions {
300    /// The 1-based ID of the trial to be exported from a hyperparameter tuning model.
301    /// If not specified, the trial with id = Model.defaultTrialId is exported.
302    /// This field is ignored for models not trained with hyperparameter tuning.
303    #[serde(deserialize_with = "crate::http::from_str")]
304    pub trial_id: i64,
305}
306
307#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
308#[serde(rename_all = "camelCase")]
309pub struct JobConfigurationExtract {
310    /// A list of fully-qualified Google Cloud Storage URIs where the extracted table should be written.
311    pub destination_uris: Vec<String>,
312    /// Optional. Whether to print out a header row in the results. Default is true. Not applicable when extracting models.
313    pub print_header: Option<bool>,
314    /// Optional. When extracting data in CSV format, this defines the delimiter to use between fields in the exported data. Default is ','. Not applicable when extracting models.
315    pub field_delimiter: Option<String>,
316    /// Optional. The exported file format.
317    /// Possible values include CSV, NEWLINE_DELIMITED_JSON, PARQUET, or AVRO for tables and ML_TF_SAVED_MODEL or ML_XGBOOST_BOOSTER for models. The default value for tables is CSV. Tables with nested or repeated fields cannot be exported as CSV. The default value for models is ML_TF_SAVED_MODEL.
318    pub destination_format: Option<DestinationFormat>,
319    /// Optional. The compression type to use for exported files. Possible values include DEFLATE, GZIP, NONE, SNAPPY, and ZSTD. The default value is NONE. Not all compression formats are support for all file formats. DEFLATE is only supported for Avro. ZSTD is only supported for Parquet. Not applicable when extracting models.
320    pub compression: Option<String>,
321    /// Whether to use logical types when extracting to AVRO format. Not applicable when extracting models.
322    pub use_avro_logical_types: Option<bool>,
323    /// Optional. Model extract options only applicable when extracting models.
324    pub model_extract_options: Option<ModelExtractOptions>,
325    #[serde(flatten)]
326    pub source: JobConfigurationExtractSource,
327}
328
329#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
330#[serde(rename_all = "camelCase")]
331pub struct JobConfigurationQuery {
332    /// [Required] SQL query text to execute.
333    /// The useLegacySql field can be used to indicate whether the query uses legacy SQL or GoogleSQL.
334    pub query: String,
335    /// Optional. Describes the table where the query results should be stored.
336    /// This property must be set for large results that exceed the maximum response size. For queries that produce anonymous (cached) results, this field will be populated by BigQuery.
337    pub destination_table: Option<TableReference>,
338    /// Optional. You can specify external table definitions,
339    /// which operate as ephemeral tables that can be queried. These definitions are configured using a JSON map, where the string key represents the table identifier, and the value is the corresponding external data configuration object.
340    /// An object containing a list of "key": value pairs. Example: { "name": "wrench", "mass": "1.3kg", "count": "3" }.
341    pub table_definitions: Option<HashMap<String, ExternalDataConfiguration>>,
342    /// Describes user-defined function resources used in the query.
343    pub user_defined_function_resources: Option<Vec<UserDefinedFunctionResource>>,
344    /// Optional. Specifies whether the job is allowed to create new tables. The following values are supported:
345    /// CREATE_IF_NEEDED: If the table does not exist, BigQuery creates the table.
346    /// CREATE_NEVER: The table must already exist. If it does not, a 'notFound' error is returned in the job result.
347    /// The default value is CREATE_IF_NEEDED. Creation, truncation and append actions occur as one atomic update upon job completion.
348    pub create_disposition: Option<CreateDisposition>,
349    /// Optional. Specifies the action that occurs if the destination table already exists. The following values are supported:
350    /// WRITE_TRUNCATE: If the table already exists, BigQuery overwrites the table data and uses the schema from the query result.
351    /// WRITE_APPEND: If the table already exists, BigQuery appends the data to the table.
352    /// WRITE_EMPTY: If the table already exists and contains data, a 'duplicate' error is returned in the job result.
353    /// 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.
354    pub write_disposition: Option<WriteDisposition>,
355    /// Optional. Specifies the default dataset to use for unqualified table names in the query.
356    /// This setting does not alter behavior of unqualified dataset names.
357    /// Setting the system variable @@dataset_id achieves the same behavior.
358    pub default_dataset: Option<DatasetReference>,
359    /// Optional. Specifies a priority for the query.
360    /// Possible values include INTERACTIVE and BATCH. The default value is INTERACTIVE.
361    pub priority: Option<Priority>,
362    /// Optional. If true and query uses legacy SQL dialect,
363    /// allows the query to produce arbitrarily large result tables at a slight cost in performance.
364    /// Requires destinationTable to be set.
365    /// For GoogleSQL queries, this flag is ignored and large results are always allowed.
366    /// However, you must still set destinationTable when result size exceeds the allowed maximum response size.
367    pub allow_large_results: Option<bool>,
368    /// Optional. Whether to look for the result in the query cache.
369    /// The query cache is a best-effort cache that will be flushed whenever tables in the query are modified.
370    /// Moreover, the query cache is only available when a query does not have a destination table specified.
371    /// The default value is true.
372    pub use_query_cache: Option<bool>,
373    /// Optional. If true and query uses legacy SQL dialect,
374    /// flattens all nested and repeated fields in the query results.
375    /// allowLargeResults must be true if this is set to false. For GoogleSQL queries,
376    /// this flag is ignored and results are never flattened.
377    pub flatten_results: Option<bool>,
378    /// Limits the bytes billed for this job.
379    /// Queries that will have bytes billed beyond this limit will fail (without incurring a charge).
380    /// If unspecified, this will be set to your project default.
381    #[serde(deserialize_with = "crate::http::from_str_option")]
382    #[serde(default)]
383    pub maximum_bytes_billed: Option<i64>,
384    /// Optional. Specifies whether to use BigQuery's legacy SQL dialect for this query.
385    /// The default value is true. If set to false, the query will use
386    /// BigQuery's GoogleSQL: https://cloud.google.com/bigquery/sql-reference/
387    /// When useLegacySql is set to false, the value of flattenResults is ignored;
388    /// query will be run as if flattenResults is false.
389    pub use_legacy_sql: Option<bool>,
390    /// GoogleSQL only. Set to POSITIONAL to use positional (?) query parameters or to NAMED to use named (@myparam) query parameters in this query.
391    pub parameter_mode: Option<String>,
392    /// Query parameters for GoogleSQL queries.
393    pub query_parameters: Option<Vec<QueryParameter>>,
394    /// 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:
395    /// ALLOW_FIELD_ADDITION: allow adding a nullable field to the schema.
396    /// ALLOW_FIELD_RELAXATION: allow relaxing a required field in the origin
397    pub schema_update_options: Option<Vec<SchemaUpdateOption>>,
398    /// Time-based partitioning specification for the destination table.
399    /// Only one of timePartitioning and rangePartitioning should be specified
400    pub time_partitioning: Option<TimePartitioning>,
401    /// Range partitioning specification for the destination table.
402    /// Only one of timePartitioning and rangePartitioning should be specified.
403    pub range_partitioning: Option<RangePartitioning>,
404    /// Clustering specification for the destination table.
405    pub clustering: Option<Clustering>,
406    /// Custom encryption configuration (e.g., Cloud KMS keys)
407    pub destination_encryption_configuration: Option<EncryptionConfiguration>,
408    /// Options controlling the execution of scripts.
409    pub script_options: Option<ScriptOptions>,
410    /// Connection properties which can modify the query behavior.
411    pub connection_properties: Option<Vec<ConnectionProperty>>,
412    /// if this property is true, the job creates a new session using a randomly generated sessionId.
413    /// To continue using a created session with subsequent queries,
414    /// pass the existing session identifier as a ConnectionProperty value.
415    /// The session identifier is returned as part of the SessionInfo message within the query statistics.
416    /// The new session's location will be set to Job.JobReference.location if it is present,
417    /// otherwise it's set to the default location based on existing routing logic.
418    pub create_session: Option<bool>,
419}
420
421#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug)]
422#[serde(rename_all = "camelCase")]
423pub enum JobType {
424    Query(JobConfigurationQuery),
425    Load(JobConfigurationLoad),
426    Copy(JobConfigurationTableCopy),
427    Extract(JobConfigurationExtract),
428}
429
430impl Default for JobType {
431    fn default() -> Self {
432        Self::Query(JobConfigurationQuery::default())
433    }
434}
435
436#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
437#[serde(rename_all = "camelCase")]
438pub struct JobConfiguration {
439    /// Output only. The type of the job. Can be QUERY, LOAD, EXTRACT, COPY or UNKNOWN.
440    pub job_type: String,
441    /// [Pick one] Configures a job.
442    #[serde(flatten)]
443    pub job: JobType,
444    /// Optional. If set, don't actually run this job.
445    /// A valid query will return a mostly empty response with some processing statistics,
446    /// while an invalid query will return the same error it would if it wasn't a dry run.
447    /// Behavior of non-query jobs is undefined.
448    pub dry_run: Option<bool>,
449    /// Optional. Job timeout in milliseconds.
450    /// If this time limit is exceeded, BigQuery might attempt to stop the job.
451    #[serde(deserialize_with = "crate::http::from_str_option")]
452    #[serde(default)]
453    pub job_timeout_ms: Option<i64>,
454    /// The labels associated with this job.
455    /// You can use these to organize and group your jobs.
456    /// 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.
457    /// An object containing a list of "key": value pairs. Example: { "name": "wrench", "mass": "1.3kg", "count": "3" }.
458    pub labels: Option<HashMap<String, String>>,
459}
460
461#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
462#[serde(rename_all = "camelCase")]
463pub struct JobReference {
464    /// Required. The ID of the project containing this job.
465    pub project_id: String,
466    /// 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.
467    /// Not found when the job of query is dry run.
468    #[serde(default)]
469    pub job_id: String,
470    /// Optional. The geographic location of the job. The default value is US.
471    pub location: Option<String>,
472}
473
474#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
475#[serde(rename_all = "camelCase")]
476pub struct Job {
477    /// Output only. The resource type.
478    pub kind: String,
479    /// Output only. A hash of the resource.
480    pub etag: String,
481    /// Output only. Opaque ID field of the job.
482    pub id: String,
483    /// Output only. A URL that can be used to access the resource again.
484    pub self_link: String,
485    /// Output only. Email address of the user who ran the job.
486    #[serde(rename(deserialize = "user_email"))]
487    pub user_email: Option<String>,
488    /// Required. Describes the job configuration.
489    pub configuration: JobConfiguration,
490    /// Reference describing the unique-per-user name of the job.
491    pub job_reference: JobReference,
492    /// Output only. Information about the job, including starting time and ending time of the job.
493    pub statistics: Option<JobStatistics>,
494    /// Output only. The status of this job. Examine this value when polling an asynchronous job to see if the job is complete.
495    pub status: JobStatus,
496}
497
498impl Job {}
499
500#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
501#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
502pub enum JobState {
503    #[default]
504    Done,
505    Pending,
506    Running,
507}
508
509#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
510#[serde(rename_all = "camelCase")]
511pub struct JobStatus {
512    /// Output only. Final error result of the job.
513    /// If present, indicates that the job has completed and was unsuccessful.
514    pub error_result: Option<ErrorProto>,
515    /// Output only. The first errors encountered during the running of the job.
516    /// The final message includes the number of errors that caused the process to stop.
517    /// Errors here do not necessarily mean that the job has not completed or was unsuccessful.
518    pub errors: Option<Vec<ErrorProto>>,
519    /// Output only. Running state of the job. Valid states include 'PENDING', 'RUNNING', and 'DONE'.
520    pub state: JobState,
521}
522
523#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
524#[serde(rename_all = "camelCase")]
525pub struct JobStatistics {
526    /// Output only. Creation time of this job, in milliseconds since the epoch.
527    /// This field will be present on all jobs.
528    #[serde(deserialize_with = "crate::http::from_str")]
529    pub creation_time: i64,
530    /// Output only. Start time of this job, in milliseconds since the epoch.
531    /// This field will be present when the job transitions from the PENDING state to either RUNNING or DONE.
532    #[serde(default, deserialize_with = "crate::http::from_str_option")]
533    pub start_time: Option<i64>,
534    /// Output only. End time of this job, in milliseconds since the epoch.
535    /// This field will be present whenever a job is in the DONE state.
536    #[serde(default, deserialize_with = "crate::http::from_str_option")]
537    pub end_time: Option<i64>,
538    /// Output only. Total bytes processed for the job.
539    #[serde(default, deserialize_with = "crate::http::from_str_option")]
540    pub total_bytes_processed: Option<i64>,
541    /// Output only. [TrustedTester] Job progress (0.0 -> 1.0) for LOAD and EXTRACT jobs.
542    pub completion_ratio: Option<f32>,
543    /// Output only. Quotas which delayed this job's start time.
544    pub quota_deferments: Option<Vec<String>>,
545    /// Output only. Statistics for a query job.
546    pub query: Option<JobStatisticsQuery>,
547    /// Output only. Statistics for a load job.
548    pub load: Option<JobStatisticsLoad>,
549    /// Output only. Statistics for an extract job.
550    pub extract: Option<JobStatisticsExtract>,
551    /// Output only. Slot-milliseconds for the job.
552    #[serde(default, deserialize_with = "crate::http::from_str_option")]
553    pub total_slot_ms: Option<i64>,
554    /// Output only. Name of the primary reservation assigned to this job.
555    /// Note that this could be different than reservations reported in the reservation usage field if parent reservations were used to execute this job.
556    pub reservation_id: Option<String>,
557    /// Output only. Number of child jobs executed.
558    #[serde(default, deserialize_with = "crate::http::from_str_option")]
559    pub num_child_jobs: Option<i64>,
560    /// Output only. If this is a child job, specifies the job ID of the parent.
561    pub parent_job_id: Option<String>,
562    /// Output only. If this a child job of a script, specifies information about the context of this job within the script.
563    pub script_statistics: Option<ScriptStatistics>,
564    /// Output only. Statistics for row-level security. Present only for query and extract jobs.
565    pub row_level_security_statistics: Option<RowLevelSecurityStatistics>,
566    /// Output only. Statistics for data-masking. Present only for query and extract jobs.
567    pub data_masking_statistics: Option<DataMaskingStatistics>,
568    /// Output only. [Alpha] Information of the multi-statement transaction if this job is part of one.
569    /// This property is only expected on a child job or a job that is in a session. A script parent job is not part of the transaction started in the script.
570    pub transaction_info: Option<TransactionInfo>,
571    /// Output only. Information of the session if this job is part of one.
572    pub session_info: Option<SessionInfo>,
573    /// Output only. The duration in milliseconds of the execution of the final attempt of this job,
574    /// as BigQuery may internally re-attempt to execute the job.
575    #[serde(default, deserialize_with = "crate::http::from_str_option")]
576    pub final_execution_duration_ms: Option<i64>,
577}
578#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
579#[serde(rename_all = "camelCase")]
580pub struct SessionInfo {
581    /// Output only. The id of the session.
582    pub session_id: Option<String>,
583}
584
585#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
586#[serde(rename_all = "camelCase")]
587pub struct JobStatisticsLoad {
588    /// Output only. Number of source files in a load job.
589    #[serde(default, deserialize_with = "crate::http::from_str_option")]
590    pub input_files: Option<i64>,
591    /// Output only. Number of bytes of source data in a load job.
592    #[serde(default, deserialize_with = "crate::http::from_str_option")]
593    pub input_file_bytes: Option<i64>,
594    /// Output only. Number of rows imported in a load job.
595    /// Note that while an import job is in the running state, this value may change.
596    #[serde(default, deserialize_with = "crate::http::from_str_option")]
597    pub output_rows: Option<i64>,
598    /// Output only. Size of the loaded data in bytes.
599    /// Note that while a load job is in the running state, this value may change.
600    #[serde(default, deserialize_with = "crate::http::from_str_option")]
601    pub output_bytes: Option<i64>,
602    /// 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.
603    #[serde(default, deserialize_with = "crate::http::from_str_option")]
604    pub bad_records: Option<i64>,
605    /// Output only. Describes a timeline of job execution.
606    pub timeline: Option<Vec<QueryTimelineSample>>,
607}
608
609#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
610#[serde(rename_all = "camelCase")]
611pub struct JobStatisticsExtract {
612    /// 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.
613    #[serde(default, deserialize_with = "crate::http::from_str_vec_option")]
614    pub destination_uri_file_counts: Option<Vec<i64>>,
615    /// Output only. Number of user bytes extracted into the result.
616    /// This is the byte count as computed by BigQuery for billing purposes and doesn't have any relationship with the number of actual result bytes extracted in the desired format.
617    #[serde(default, deserialize_with = "crate::http::from_str_option")]
618    pub input_bytes: Option<i64>,
619    /// Output only. Describes a timeline of job execution.
620    pub timeline: Option<Vec<QueryTimelineSample>>,
621}
622
623#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
624#[serde(rename_all = "camelCase")]
625pub enum EvaluationKind {
626    #[default]
627    EvaluationKindUnspecified,
628    Statement,
629    Expression,
630}
631
632#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
633#[serde(rename_all = "camelCase")]
634pub struct ScriptStackFrame {
635    /// Output only. One-based start line.
636    pub start_line: Option<i64>,
637    /// Output only. One-based start column.
638    pub start_column: Option<i64>,
639    /// Output only. One-based end line.
640    pub end_line: Option<i64>,
641    /// Output only. One-based end column.
642    pub end_column: Option<i64>,
643    /// Output only. Name of the active procedure, empty if in a top-level script.
644    pub procedure_id: Option<String>,
645    /// Output only. Text of the current statement/expression.
646    pub text: Option<String>,
647}
648
649#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
650#[serde(rename_all = "camelCase")]
651pub struct RowLevelSecurityStatistics {
652    /// Whether any accessed data was protected by row access policies.
653    pub row_level_security_applied: Option<bool>,
654}
655
656#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
657#[serde(rename_all = "camelCase")]
658pub struct DataMaskingStatistics {
659    /// Whether any accessed data was protected by the data masking.
660    pub data_masking_applied: Option<bool>,
661}
662
663#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
664#[serde(rename_all = "camelCase")]
665pub struct TransactionInfo {
666    /// Output only. [Alpha] Id of the transaction..
667    pub transaction_id: Option<String>,
668}
669
670#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
671#[serde(rename_all = "camelCase")]
672pub struct ScriptStatistics {
673    /// Whether this child job was a statement or expression.
674    pub evaluation_kind: Option<EvaluationKind>,
675    /// Stack trace showing the line/column/procedure name of each frame on the stack at the point where the current evaluation happened. The leaf frame is first, the primary script is last. Never empty.
676    pub stack_frames: Option<Vec<ScriptStackFrame>>,
677}
678
679#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
680#[serde(rename_all = "camelCase")]
681pub struct JobStatisticsQuery {
682    /// Output only. Describes execution plan for the query.
683    pub query_plan: Option<Vec<ExplainQueryStage>>,
684    /// Output only. The original estimate of bytes processed for the job.
685    #[serde(default, deserialize_with = "crate::http::from_str_option")]
686    pub estimated_bytes_processed: Option<i64>,
687    /// Output only. Describes a timeline of job execution.
688    pub timeline: Option<Vec<QueryTimelineSample>>,
689    /// Output only. Total number of partitions processed from all partitioned tables referenced in the job.
690    #[serde(default, deserialize_with = "crate::http::from_str_option")]
691    pub total_partitions_processed: Option<i64>,
692    /// Output only. Total bytes processed for the job.
693    #[serde(default, deserialize_with = "crate::http::from_str_option")]
694    pub total_bytes_processed: Option<i64>,
695    /// Output only. For dry-run jobs, totalBytesProcessed is an estimate and
696    /// this field specifies the accuracy of the estimate. Possible values can be:
697    /// UNKNOWN: accuracy of the estimate is unknown.
698    /// PRECISE: estimate is precise.
699    /// LOWER_BOUND: estimate is lower bound of what the query would cost.
700    /// UPPER_BOUND: estimate is upper bound of what the query would cost.
701    pub total_bytes_processed_accuracy: Option<String>,
702    /// Output only. If the project is configured to use on-demand pricing,
703    /// then this field contains the total bytes billed for the job. If the project is configured to use flat-rate pricing,
704    /// then you are not billed for bytes and this field is informational only.
705    #[serde(default, deserialize_with = "crate::http::from_str_option")]
706    pub total_bytes_billed: Option<i64>,
707    /// Output only. Billing tier for the job.
708    /// This is a BigQuery-specific concept which is not related to the GCP notion of "free tier".
709    /// The value here is a measure of the query's resource consumption relative to the amount of data scanned. For on-demand queries, the limit is 100, and all queries within this limit are billed at the standard on-demand rates. On-demand queries that exceed this limit will fail with a billingTierLimitExceeded error.
710    pub billing_tier: Option<i32>,
711    /// Output only. Slot-milliseconds for the job.
712    #[serde(default, deserialize_with = "crate::http::from_str_option")]
713    pub total_slot_ms: Option<i64>,
714    /// Output only. Whether the query result was fetched from the query cache.
715    pub cache_hist: Option<bool>,
716    /// Output only. Referenced tables for the job. Queries that reference more than 50 tables will not have a complete list.
717    pub referenced_tables: Option<Vec<TableReference>>,
718    /// Output only. Referenced routines for the job.
719    pub referenced_routines: Option<Vec<RoutineReference>>,
720    /// Output only. The schema of the results. Present only for successful dry run of non-legacy SQL queries.
721    pub schema: Option<TableSchema>,
722    /// Output only. The number of rows affected by a DML statement.
723    /// Present only for DML statements INSERT, UPDATE or DELETE.
724    #[serde(default, deserialize_with = "crate::http::from_str_option")]
725    pub num_dml_affected_rows: Option<i64>,
726    /// Output only. Detailed statistics for DML statements INSERT, UPDATE, DELETE, MERGE or TRUNCATE
727    pub dml_stats: Option<DmlStats>,
728    /// Output only. GoogleSQL only: list of undeclared query parameters detected during a dry run validation
729    pub undeclared_query_parameters: Option<Vec<QueryParameter>>,
730    /// Output only. The type of query statement, if valid. Possible values:
731    /// SELECT: SELECT statement.
732    /// INSERT: INSERT statement.
733    /// UPDATE: UPDATE statement.
734    /// DELETE: DELETE statement.
735    /// MERGE: MERGE statement.
736    /// ALTER_TABLE: ALTER TABLE statement.
737    /// ALTER_VIEW: ALTER VIEW statement.
738    /// ASSERT: ASSERT statement.
739    /// CREATE_FUNCTION: CREATE FUNCTION statement.
740    /// CREATE_MODEL: CREATE MODEL statement.
741    /// CREATE_PROCEDURE: CREATE PROCEDURE statement.
742    /// CREATE_ROW_ACCESS_POLICY: CREATE ROW ACCESS POLICY statement.
743    /// CREATE_TABLE: CREATE TABLE statement, without AS SELECT.
744    /// CREATE_TABLE_AS_SELECT: CREATE TABLE AS SELECT statement.
745    /// CREATE_VIEW: CREATE VIEW statement.
746    /// DROP_FUNCTION : DROP FUNCTION statement.
747    /// DROP_PROCEDURE: DROP PROCEDURE statement.
748    /// DROP_ROW_ACCESS_POLICY: DROP [ALL] ROW ACCESS POLICY|POLICIES statement.
749    /// DROP_TABLE: DROP TABLE statement.
750    /// DROP_VIEW: DROP VIEW statement.
751    /// EXPORT_MODEL: EXPORT MODEL statement.
752    /// LOAD_DATA: LOAD DATA statement.
753    pub statement_type: Option<String>,
754    /// Output only. The DDL operation performed, possibly dependent on the pre-existence of the DDL target.
755    pub ddl_operation_performed: Option<String>,
756    /// Output only. The DDL target table. Present only for CREATE/DROP TABLE/VIEW and DROP ALL ROW ACCESS POLICIES queries.
757    pub ddl_target_table: Option<TableReference>,
758    /// Output only. The DDL target row access policy. Present only for CREATE/DROP ROW ACCESS POLICY queries.
759    pub ddl_target_row_access_policy: Option<RowAccessPolicyReference>,
760    /// Output only. The number of row access policies affected by a DDL statement.
761    /// Present only for DROP ALL ROW ACCESS POLICIES queries.
762    #[serde(default, deserialize_with = "crate::http::from_str_option")]
763    pub ddl_affected_row_access_policy_count: Option<i64>,
764    /// Output only. [Beta] The DDL target routine. Present only for CREATE/DROP FUNCTION/PROCEDURE queries.
765    pub ddl_target_routine: Option<RoutineReference>,
766    /// Output only. Statistics of a BigQuery ML training job.
767    pub ml_statistics: Option<MlStatistics>,
768    /// Output only. Stats for EXPORT DATA statement.
769    pub export_data_statistics: Option<ExportDataStatistics>,
770    /// Output only. Job cost breakdown as bigquery internal cost and external service costs.
771    pub external_service_costs: Option<Vec<ExternalServiceCost>>,
772    /// Output only. BI Engine specific Statistics.
773    pub bi_engine_statistics: Option<BiEngineStatistics>,
774    /// Output only. Statistics for a LOAD query.
775    pub load_query_statistics: Option<LoadQueryStatistics>,
776    /// Output only. Referenced table for DCL statement.
777    pub dcl_target_table: Option<TableReference>,
778    /// Output only. Referenced view for DCL statement.
779    pub dcl_target_view: Option<TableReference>,
780    /// Output only. Search query specific statistics.
781    pub search_statistics: Option<SearchStatistics>,
782    /// Output only. Performance insights.
783    pub performance_insights: Option<PerformanceInsights>,
784    /// Output only. Statistics of a Spark procedure job.
785    pub spark_statistics: Option<SparkStatistics>,
786    /// Output only. Total bytes transferred for cross-cloud queries such as Cross Cloud Transfer and CREATE TABLE AS SELECT (CTAS).
787    #[serde(default, deserialize_with = "crate::http::from_str_option")]
788    pub transferred_bytes: Option<i64>,
789}
790
791#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
792#[serde(rename_all = "camelCase")]
793pub struct SearchStatistics {
794    /// Specifies the index usage mode for the query.
795    pub index_usage_mode: Option<IndexUsageMode>,
796    /// When indexUsageMode is UNUSED or PARTIALLY_USED, this field explains why indexes were not used in all or part of the search query. If indexUsageMode is FULLY_USED, this field is not populated.
797    pub index_unused_reasons: Option<Vec<IndexUnusedReason>>,
798}
799
800#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
801#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
802pub enum IndexUsageMode {
803    #[default]
804    IndexUsageModeUnspecified,
805    Unused,
806    PartiallyUsed,
807    FullyUsed,
808}
809
810#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
811#[serde(rename_all = "camelCase")]
812pub struct IndexUnusedReason {
813    /// Specifies the high-level reason for the scenario when no search index was used.
814    pub code: Option<IndexUnusedCode>,
815    /// Free form human-readable reason for the scenario when no search index was used.
816    pub message: Option<String>,
817    /// Specifies the base table involved in the reason that no search index was used.
818    pub base_table: Option<TableReference>,
819    /// Specifies the name of the unused search index, if available.
820    pub index_name: Option<String>,
821}
822
823#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
824#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
825pub enum IndexUnusedCode {
826    #[default]
827    CodeUnspecified,
828    IndexConfigNotAvailable,
829    PendingIndexCreation,
830    BaseTableTruncated,
831    IndexConfigModified,
832    TimeTravelQuery,
833    NoPruningPower,
834    UnindexedSearchFields,
835    UnsupportedSearchPattern,
836    OptimizedWithMaterializedView,
837    SecuredByDataMasking,
838    MismatchedTextAnalyzer,
839    BaseTableTooSmall,
840    BaseTableTooLarge,
841    EstimatedPerformanceGainTooLow,
842    InternalError,
843    OtherReason,
844}
845
846#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
847#[serde(rename_all = "camelCase")]
848pub struct PerformanceInsights {
849    /// Output only. Average execution ms of previous runs. Indicates the job ran slow compared to previous executions. To find previous executions, use INFORMATION_SCHEMA tables and filter jobs with same query hash.
850    #[serde(default, deserialize_with = "crate::http::from_str_option")]
851    pub avg_previous_execution_ms: Option<i64>,
852    /// Output only. Standalone query stage performance insights, for exploring potential improvements.
853    pub stage_performance_standalone_insights: Option<Vec<StagePerformanceStandaloneInsight>>,
854    /// Output only. Query stage performance insights compared to previous runs,
855    /// for diagnosing performance regression.
856    pub stage_performance_change_insights: Option<Vec<StagePerformanceChangeInsight>>,
857}
858
859#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
860#[serde(rename_all = "camelCase")]
861pub struct StagePerformanceStandaloneInsight {
862    /// Output only. The stage id that the insight mapped to.
863    #[serde(default, deserialize_with = "crate::http::from_str_option")]
864    pub stage_id: Option<i64>,
865    /// Output only. True if the stage has a slot contention issue.
866    pub slot_contention: Option<bool>,
867    /// Output only. True if the stage has insufficient shuffle quota.
868    pub insufficient_shuffle_quota: Option<bool>,
869}
870
871#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
872#[serde(rename_all = "camelCase")]
873pub struct StagePerformanceChangeInsight {
874    /// Output only. The stage id that the insight mapped to.
875    #[serde(default, deserialize_with = "crate::http::from_str_option")]
876    pub stage_id: Option<i64>,
877    /// Output only. Input data change insight of the query stage.
878    pub input_data_change: Option<InputDataChange>,
879}
880
881#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
882#[serde(rename_all = "camelCase")]
883pub struct InputDataChange {
884    /// Output only. Records read difference percentage compared to a previous run
885    pub records_read_diff_percentage: Option<f64>,
886}
887
888#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
889#[serde(rename_all = "camelCase")]
890pub struct SparkStatistics {
891    /// Output only. Endpoints returned from Dataproc.
892    /// Key list: - history_server_endpoint: A link to Spark job UI.
893    /// An object containing a list of "key": value pairs.
894    /// Example: { "name": "wrench", "mass": "1.3kg", "count": "3" }.
895    pub endpoints: Option<HashMap<String, String>>,
896    /// Output only. Spark job ID if a Spark job is created successfully.
897    pub spark_job_id: Option<String>,
898    /// Output only. Location where the Spark job is executed.
899    /// A location is selected by BigQueury for jobs configured to run in a multi-region.
900    pub spark_job_location: Option<String>,
901    /// Output only. Logging info is used to generate a link to Cloud Logging.
902    pub logging_info: Option<LoggingInfo>,
903}
904
905#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
906#[serde(rename_all = "camelCase")]
907pub struct LoggingInfo {
908    /// Output only. Resource type used for logging.
909    pub resource_type: Option<String>,
910    /// Output only. Project ID where the Spark logs were written.
911    pub project_id: Option<String>,
912}
913
914#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
915#[serde(rename_all = "camelCase")]
916pub struct ExportDataStatistics {
917    /// Number of destination files generated in case of EXPORT DATA statement only.
918    #[serde(default, deserialize_with = "crate::http::from_str_option")]
919    pub file_count: Option<i64>,
920    /// [Alpha] Number of destination rows generated in case of EXPORT DATA statement only.
921    #[serde(default, deserialize_with = "crate::http::from_str_option")]
922    pub row_count: Option<i64>,
923}
924
925#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
926#[serde(rename_all = "camelCase")]
927pub struct ExternalServiceCost {
928    /// External service name.
929    pub external_service: String,
930    /// External service cost in terms of bigquery bytes processed.
931    #[serde(default, deserialize_with = "crate::http::from_str_option")]
932    pub bytes_processed: Option<i64>,
933    /// External service cost in terms of bigquery bytes billed.
934    #[serde(default, deserialize_with = "crate::http::from_str_option")]
935    pub bytes_billed: Option<i64>,
936    /// External service cost in terms of bigquery slot milliseconds.
937    #[serde(default, deserialize_with = "crate::http::from_str_option")]
938    pub slot_ms: Option<i64>,
939    /// Non-preemptable reserved slots used for external job.
940    /// For example, reserved slots for Cloua AI Platform job are the VM usages converted to BigQuery slot with equivalent mount of price.
941    #[serde(default, deserialize_with = "crate::http::from_str_option")]
942    pub reserved_slot_count: Option<i64>,
943}
944
945#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
946#[serde(rename_all = "camelCase")]
947pub struct BiEngineStatistics {
948    /// Output only. Specifies which mode of BI Engine acceleration was performed (if any).
949    pub bi_engine_mode: Option<BiEngineMode>,
950    /// Output only. Specifies which mode of BI Engine acceleration was performed (if any).
951    pub acceleration_mode: Option<BiEngineAccelerationMode>,
952    /// In case of DISABLED or PARTIAL biEngineMode, these contain the explanatory reasons as to why BI Engine could not accelerate. In case the full query was accelerated, this field is not populated.
953    pub bi_engine_reasons: Option<Vec<BiEngineReason>>,
954}
955
956#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
957#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
958pub enum BiEngineMode {
959    #[default]
960    AccelerationModeUnspecified,
961    Disabled,
962    Partial,
963    Full,
964}
965
966#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
967#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
968pub enum BiEngineAccelerationMode {
969    #[default]
970    BiEngineAccelerationModeUnspecified,
971    BiEngineDisabled,
972    PartialInput,
973    FullInput,
974    FullQuery,
975}
976
977#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
978#[serde(rename_all = "camelCase")]
979pub struct BiEngineReason {
980    /// Output only. High-level BI Engine reason for partial or disabled acceleration
981    pub code: BiEngineCode,
982    /// Output only. Free form human-readable reason for partial or disabled acceleration.
983    pub message: String,
984}
985#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
986#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
987pub enum BiEngineCode {
988    #[default]
989    CodeUnspecified,
990    NoReservation,
991    InsufficientReservation,
992    UnsupportedSqlText,
993    InputTooLarge,
994    OtherReason,
995    TableExcluded,
996}
997
998#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
999#[serde(rename_all = "camelCase")]
1000pub struct LoadQueryStatistics {
1001    /// Output only. Number of source files in a LOAD query.
1002    #[serde(default, deserialize_with = "crate::http::from_str_option")]
1003    pub input_files: Option<i64>,
1004    /// Output only. Number of bytes of source data in a LOAD query.
1005    #[serde(default, deserialize_with = "crate::http::from_str_option")]
1006    pub input_file_bytes: Option<i64>,
1007    /// Output only. Number of rows imported in a LOAD query. Note that while a LOAD query is in the running state, this value may change.
1008    #[serde(default, deserialize_with = "crate::http::from_str_option")]
1009    pub output_rows: Option<i64>,
1010    /// Output only. Size of the loaded data in bytes.
1011    /// Note that while a LOAD query is in the running state, this value may change.
1012    #[serde(default, deserialize_with = "crate::http::from_str_option")]
1013    pub output_bytes: Option<i64>,
1014    /// Output only. The number of bad records encountered while processing a LOAD query. 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.
1015    #[serde(default, deserialize_with = "crate::http::from_str_option")]
1016    pub bad_records: Option<i64>,
1017}
1018
1019#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
1020#[serde(rename_all = "camelCase")]
1021pub struct ExplainQueryStage {
1022    /// Human-readable name for the stage.
1023    pub name: String,
1024    /// Unique ID for the stage within the plan.
1025    #[serde(deserialize_with = "crate::http::from_str")]
1026    pub id: i64,
1027    /// Stage start time represented as milliseconds since the epoch
1028    #[serde(default, deserialize_with = "crate::http::from_str_option")]
1029    pub start_ms: Option<i64>,
1030    /// Stage end time represented as milliseconds since the epoch.
1031    #[serde(default, deserialize_with = "crate::http::from_str_option")]
1032    pub end_ms: Option<i64>,
1033    /// IDs for stages that are inputs to this stage.
1034    #[serde(default, deserialize_with = "crate::http::from_str_vec_option")]
1035    pub input_stages: Option<Vec<i64>>,
1036    /// Relative amount of time the average shard spent waiting to be scheduled.
1037    pub wait_ratio_avg: Option<f64>,
1038    /// Milliseconds the average shard spent waiting to be scheduled.
1039    #[serde(default, deserialize_with = "crate::http::from_str_option")]
1040    pub wait_ms_avg: Option<i64>,
1041    /// Relative amount of time the slowest shard spent waiting to be scheduled.
1042    pub wait_ratio_max: Option<f64>,
1043    ///Milliseconds the slowest shard spent reading input.
1044    #[serde(default, deserialize_with = "crate::http::from_str_option")]
1045    pub wait_ms_max: Option<i64>,
1046    /// Relative amount of time the average shard spent on CPU-bound tasks.
1047    pub compute_ratio_avg: Option<f64>,
1048    /// Milliseconds the average shard spent on CPU-bound tasks.
1049    #[serde(default, deserialize_with = "crate::http::from_str_option")]
1050    pub compute_ms_avg: Option<i64>,
1051    /// Relative amount of time the slowest shard spent on CPU-bound tasks.
1052    pub compute_ratio_max: Option<f64>,
1053    /// Milliseconds the slowest shard spent on CPU-bound tasks.
1054    #[serde(default, deserialize_with = "crate::http::from_str_option")]
1055    pub compute_ms_max: Option<i64>,
1056    /// Relative amount of time the average shard spent on writing output.
1057    pub write_ratio_avg: Option<f64>,
1058    /// Milliseconds the average shard spent on writing output.
1059    #[serde(default, deserialize_with = "crate::http::from_str_option")]
1060    pub write_ms_avg: Option<i64>,
1061    /// Relative amount of time the slowest shard spent on writing output.
1062    pub write_ratio_max: Option<f64>,
1063    /// Milliseconds the slowest shard spent on writing output.
1064    #[serde(default, deserialize_with = "crate::http::from_str_option")]
1065    pub write_ms_max: Option<i64>,
1066    /// Total number of bytes written to shuffle.
1067    #[serde(default, deserialize_with = "crate::http::from_str_option")]
1068    pub shuffle_output_bytes: Option<i64>,
1069    /// Total number of bytes written to shuffle.
1070    #[serde(default, deserialize_with = "crate::http::from_str_option")]
1071    pub shuffle_output_bytes_spilled: Option<i64>,
1072    /// Number of records read into the stage.
1073    #[serde(default, deserialize_with = "crate::http::from_str_option")]
1074    pub records_read: Option<i64>,
1075    /// Number of records read written by the stage.
1076    #[serde(default, deserialize_with = "crate::http::from_str_option")]
1077    pub records_written: Option<i64>,
1078    /// Number of parallel input segments to be processed
1079    #[serde(default, deserialize_with = "crate::http::from_str_option")]
1080    pub parallel_inputs: Option<i64>,
1081    /// Number of parallel input segments completed.
1082    #[serde(default, deserialize_with = "crate::http::from_str_option")]
1083    pub completed_parallel_inputs: Option<i64>,
1084    /// Current status for this stage.
1085    pub status: String,
1086    /// List of operations within the stage in dependency order (approximately chronological).
1087    pub steps: Option<Vec<ExplainQueryStep>>,
1088    /// Slot-milliseconds used by the stage
1089    #[serde(default, deserialize_with = "crate::http::from_str_option")]
1090    pub slot_ms: Option<i64>,
1091}
1092
1093#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
1094#[serde(rename_all = "camelCase")]
1095pub struct ExplainQueryStep {
1096    /// Machine-readable operation type.
1097    pub kind: String,
1098    /// Human-readable description of the step(s).
1099    pub substeps: Option<Vec<String>>,
1100}
1101
1102#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
1103#[serde(rename_all = "camelCase")]
1104pub struct DmlStats {
1105    /// Output only. Number of inserted Rows. Populated by DML INSERT and MERGE statements
1106    #[serde(default, deserialize_with = "crate::http::from_str_option")]
1107    pub inserted_row_count: Option<i64>,
1108    /// Output only. Number of deleted Rows. populated by DML DELETE, MERGE and TRUNCATE statements.
1109    #[serde(default, deserialize_with = "crate::http::from_str_option")]
1110    pub deleted_row_count: Option<i64>,
1111    /// Output only. Number of updated Rows. Populated by DML UPDATE and MERGE statements.
1112    #[serde(default, deserialize_with = "crate::http::from_str_option")]
1113    pub updated_row_count: Option<i64>,
1114}
1115
1116#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
1117#[serde(rename_all = "camelCase")]
1118pub struct QueryTimelineSample {
1119    /// Milliseconds elapsed since the start of query execution.
1120    #[serde(default, deserialize_with = "crate::http::from_str_option")]
1121    pub elapsed_ms: Option<i64>,
1122    /// Cumulative slot-ms consumed by the query.
1123    #[serde(default, deserialize_with = "crate::http::from_str_option")]
1124    pub total_slot_ms: Option<i64>,
1125    /// Total units of work remaining for the query. This number can be revised (increased or decreased) while the query is running.
1126    #[serde(default, deserialize_with = "crate::http::from_str_option")]
1127    pub pending_units: Option<i64>,
1128    /// Total parallel units of work completed by this query.
1129    #[serde(default, deserialize_with = "crate::http::from_str_option")]
1130    pub completed_units: Option<i64>,
1131    /// Total number of active workers.
1132    /// This does not correspond directly to slot usage.
1133    /// This is the largest value observed since the last sample.
1134    #[serde(default, deserialize_with = "crate::http::from_str_option")]
1135    pub active_units: Option<i64>,
1136    /// Units of work that can be scheduled immediately. Providing additional slots for these units of work will accelerate the query, if no other query in the reservation needs additional slots.
1137    #[serde(default, deserialize_with = "crate::http::from_str_option")]
1138    pub estimated_runnable_units: Option<i64>,
1139}
1140
1141#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
1142#[serde(rename_all = "camelCase")]
1143pub struct MlStatistics {
1144    /// Output only. Maximum number of iterations specified as maxIterations in the 'CREATE MODEL' query.
1145    /// The actual number of iterations may be less than this number due to early stop.
1146    #[serde(default, deserialize_with = "crate::http::from_str_option")]
1147    pub max_iterations: Option<i64>,
1148    /// Results for all completed iterations. Empty for hyperparameter tuning jobs.
1149    pub iteration_results: Option<Vec<IterationResult>>,
1150    /// Output only. The type of the model that is being trained.
1151    pub model_type: ModelType,
1152    /// Output only. Training type of the job.
1153    pub training_type: TrainingType,
1154    /// Output only. Trials of a hyperparameter tuning job sorted by trialId.
1155    pub hparam_trials: Option<Vec<HparamTuningTrial>>,
1156}
1157
1158#[derive(Clone, PartialEq, serde::Deserialize, serde::Serialize, Debug, Default)]
1159#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
1160pub enum TrainingType {
1161    /// Unspecified training type.
1162    #[default]
1163    TrainingTypeUnspecified,
1164    /// Single training with fixed parameter space.
1165    SingleTraining,
1166    /// Hyperparameter tuning training.
1167    HparamTuning,
1168}
1169
1170pub fn is_select_query(statistics: &Option<JobStatistics>, config: &JobConfiguration) -> bool {
1171    has_statement_type(statistics, config, "SELECT")
1172}
1173pub fn is_script(statistics: &Option<JobStatistics>, config: &JobConfiguration) -> bool {
1174    has_statement_type(statistics, config, "SCRIPT")
1175}
1176fn has_statement_type(statistics: &Option<JobStatistics>, config: &JobConfiguration, statement_type: &str) -> bool {
1177    match config.job {
1178        JobType::Query(_) => {}
1179        _ => return false,
1180    }
1181    let statistics = match &statistics {
1182        Some(v) => v,
1183        None => return false,
1184    };
1185    let query = match &statistics.query {
1186        Some(v) => v,
1187        None => return false,
1188    };
1189    let stmt = match &query.statement_type {
1190        Some(v) => v,
1191        None => return false,
1192    };
1193    stmt == statement_type
1194}