Add labels to google_storage_bucket (#652)

* revendor storage

* revendor gensupport

* revendor bigquery

* add support for storage bucket labels

* bucket label docs
This commit is contained in:
Dana Hoffman 2017-10-30 15:48:26 -07:00 committed by GitHub
parent f6c1a236d9
commit 7b69c31f6a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 4551 additions and 428 deletions

View File

@ -39,6 +39,12 @@ func resourceStorageBucket() *schema.Resource {
Default: false,
},
"labels": &schema.Schema{
Type: schema.TypeMap,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"location": &schema.Schema{
Type: schema.TypeString,
Default: "US",
@ -223,7 +229,11 @@ func resourceStorageBucketCreate(d *schema.ResourceData, meta interface{}) error
location := d.Get("location").(string)
// Create a bucket, setting the acl, location and name.
sb := &storage.Bucket{Name: bucket, Location: location}
sb := &storage.Bucket{
Name: bucket,
Labels: expandLabels(d),
Location: location,
}
if v, ok := d.GetOk("storage_class"); ok {
sb.StorageClass = v.(string)
@ -331,6 +341,13 @@ func resourceStorageBucketUpdate(d *schema.ResourceData, meta interface{}) error
sb.Cors = expandCors(v.([]interface{}))
}
if d.HasChange("labels") {
sb.Labels = expandLabels(d)
if len(sb.Labels) == 0 {
sb.NullFields = append(sb.NullFields, "Labels")
}
}
res, err := config.clientStorage.Buckets.Patch(d.Get("name").(string), sb).Do()
if err != nil {
@ -366,6 +383,7 @@ func resourceStorageBucketRead(d *schema.ResourceData, meta interface{}) error {
d.Set("location", res.Location)
d.Set("cors", flattenCors(res.Cors))
d.Set("versioning", flattenBucketVersioning(res.Versioning))
d.Set("labels", res.Labels)
d.SetId(res.Id)
return nil
}
@ -534,7 +552,7 @@ func resourceGCSBucketLifecycleCreateOrUpdate(d *schema.ResourceData, sb *storag
}
if v, ok := condition["is_live"]; ok {
target_lifecycle_rule.Condition.IsLive = v.(bool)
target_lifecycle_rule.Condition.IsLive = googleapi.Bool(v.(bool))
}
if v, ok := condition["matches_storage_class"]; ok {

View File

@ -429,6 +429,46 @@ func TestAccStorageBucket_cors(t *testing.T) {
}
}
func TestAccStorageBucket_labels(t *testing.T) {
t.Parallel()
var bucket storage.Bucket
bucketName := fmt.Sprintf("tf-test-acl-bucket-%d", acctest.RandInt())
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccStorageBucketDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccStorageBucket_labels(bucketName),
Check: resource.ComposeTestCheckFunc(
testAccCheckStorageBucketExists(
"google_storage_bucket.bucket", bucketName, &bucket),
testAccCheckStorageBucketHasLabel(&bucket, "my-label", "my-label-value"),
),
},
resource.TestStep{
Config: testAccStorageBucket_updateLabels(bucketName),
Check: resource.ComposeTestCheckFunc(
testAccCheckStorageBucketExists(
"google_storage_bucket.bucket", bucketName, &bucket),
testAccCheckStorageBucketHasLabel(&bucket, "my-label", "my-updated-label-value"),
testAccCheckStorageBucketHasLabel(&bucket, "a-new-label", "a-new-label-value"),
),
},
resource.TestStep{
Config: testAccStorageBucket_basic(bucketName),
Check: resource.ComposeTestCheckFunc(
testAccCheckStorageBucketExists(
"google_storage_bucket.bucket", bucketName, &bucket),
testAccCheckStorageBucketHasNoLabels(&bucket),
),
},
},
})
}
func testAccCheckStorageBucketExists(n string, bucketName string, bucket *storage.Bucket) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
@ -460,6 +500,29 @@ func testAccCheckStorageBucketExists(n string, bucketName string, bucket *storag
}
}
func testAccCheckStorageBucketHasLabel(bucket *storage.Bucket, key, value string) resource.TestCheckFunc {
return func(s *terraform.State) error {
val, ok := bucket.Labels[key]
if !ok {
return fmt.Errorf("Label with key %s not found", key)
}
if val != value {
return fmt.Errorf("Label value did not match for key %s: expected %s but found %s", key, value, val)
}
return nil
}
}
func testAccCheckStorageBucketHasNoLabels(bucket *storage.Bucket) resource.TestCheckFunc {
return func(s *terraform.State) error {
if len(bucket.Labels) > 0 {
return fmt.Errorf("Expected 0 labels, found %v", bucket.Labels)
}
return nil
}
}
func testAccCheckStorageBucketPutItem(bucketName string) resource.TestCheckFunc {
return func(s *terraform.State) error {
config := testAccProvider.Meta().(*Config)
@ -656,3 +719,26 @@ resource "google_storage_bucket" "bucket" {
}
`, bucketName)
}
func testAccStorageBucket_labels(bucketName string) string {
return fmt.Sprintf(`
resource "google_storage_bucket" "bucket" {
name = "%s"
labels {
my-label = "my-label-value"
}
}
`, bucketName)
}
func testAccStorageBucket_updateLabels(bucketName string) string {
return fmt.Sprintf(`
resource "google_storage_bucket" "bucket" {
name = "%s"
labels {
my-label = "my-updated-label-value"
a-new-label = "a-new-label-value"
}
}
`, bucketName)
}

View File

@ -1,11 +1,11 @@
{
"kind": "discovery#restDescription",
"etag": "\"tbys6C40o18GZwyMen5GMkdK-3s/2pbHVnKgRBtlI769YwDOp1uiQ0w\"",
"etag": "\"YWOzh2SDasdU84ArJnpYek-OMdg/t8hRUXz9L9sAZnVlcSWXL0fUTh4\"",
"discoveryVersion": "v1",
"id": "bigquery:v2",
"name": "bigquery",
"version": "v2",
"revision": "20170224",
"revision": "20171022",
"title": "BigQuery API",
"description": "A data platform for customers to create, manage, share and query data.",
"ownerDomain": "google.com",
@ -20,7 +20,7 @@
"basePath": "/bigquery/v2/",
"rootUrl": "https://www.googleapis.com/",
"servicePath": "bigquery/v2/",
"batchPath": "batch",
"batchPath": "batch/bigquery/v2",
"parameters": {
"alt": {
"type": "string",
@ -281,7 +281,7 @@
},
"labels": {
"type": "object",
"description": "[Experimental] 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 Labeling Datasets for more information.",
"description": "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 Labeling Datasets for more information.",
"additionalProperties": {
"type": "string"
}
@ -293,7 +293,7 @@
},
"location": {
"type": "string",
"description": "[Experimental] The geographic location where the dataset should reside. Possible values include EU and US. The default value is US."
"description": "The geographic location where the dataset should reside. Possible values include EU and US. The default value is US."
},
"selfLink": {
"type": "string",
@ -330,7 +330,7 @@
},
"labels": {
"type": "object",
"description": "[Experimental] The labels associated with this dataset. You can use these to organize and group your datasets.",
"description": "The labels associated with this dataset. You can use these to organize and group your datasets.",
"additionalProperties": {
"type": "string"
}
@ -377,6 +377,16 @@
}
}
},
"EncryptionConfiguration": {
"id": "EncryptionConfiguration",
"type": "object",
"properties": {
"kmsKeyName": {
"type": "string",
"description": "[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."
}
}
},
"ErrorProto": {
"id": "ErrorProto",
"type": "object",
@ -403,6 +413,16 @@
"id": "ExplainQueryStage",
"type": "object",
"properties": {
"computeMsAvg": {
"type": "string",
"description": "Milliseconds the average shard spent on CPU-bound tasks.",
"format": "int64"
},
"computeMsMax": {
"type": "string",
"description": "Milliseconds the slowest shard spent on CPU-bound tasks.",
"format": "int64"
},
"computeRatioAvg": {
"type": "number",
"description": "Relative amount of time the average shard spent on CPU-bound tasks.",
@ -422,6 +442,16 @@
"type": "string",
"description": "Human-readable name for stage."
},
"readMsAvg": {
"type": "string",
"description": "Milliseconds the average shard spent reading input.",
"format": "int64"
},
"readMsMax": {
"type": "string",
"description": "Milliseconds the slowest shard spent reading input.",
"format": "int64"
},
"readRatioAvg": {
"type": "number",
"description": "Relative amount of time the average shard spent reading input.",
@ -442,6 +472,16 @@
"description": "Number of records written by the stage.",
"format": "int64"
},
"shuffleOutputBytes": {
"type": "string",
"description": "Total number of bytes written to shuffle.",
"format": "int64"
},
"shuffleOutputBytesSpilled": {
"type": "string",
"description": "Total number of bytes written to shuffle and spilled to disk.",
"format": "int64"
},
"status": {
"type": "string",
"description": "Current status for the stage."
@ -453,6 +493,16 @@
"$ref": "ExplainQueryStep"
}
},
"waitMsAvg": {
"type": "string",
"description": "Milliseconds the average shard spent waiting to be scheduled.",
"format": "int64"
},
"waitMsMax": {
"type": "string",
"description": "Milliseconds the slowest shard spent waiting to be scheduled.",
"format": "int64"
},
"waitRatioAvg": {
"type": "number",
"description": "Relative amount of time the average shard spent waiting to be scheduled.",
@ -463,6 +513,16 @@
"description": "Relative amount of time the slowest shard spent waiting to be scheduled.",
"format": "double"
},
"writeMsAvg": {
"type": "string",
"description": "Milliseconds the average shard spent on writing output.",
"format": "int64"
},
"writeMsMax": {
"type": "string",
"description": "Milliseconds the slowest shard spent on writing output.",
"format": "int64"
},
"writeRatioAvg": {
"type": "number",
"description": "Relative amount of time the average shard spent on writing output.",
@ -498,7 +558,7 @@
"properties": {
"autodetect": {
"type": "boolean",
"description": "[Experimental] Try to detect schema and format options automatically. Any option specified explicitly will be honored."
"description": "Try to detect schema and format options automatically. Any option specified explicitly will be honored."
},
"bigtableOptions": {
"$ref": "BigtableOptions",
@ -531,11 +591,11 @@
},
"sourceFormat": {
"type": "string",
"description": "[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\". [Experimental] For Google Cloud Bigtable, specify \"BIGTABLE\". Please note that reading from Google Cloud Bigtable is experimental and has to be enabled for your project. Please contact Google Cloud Support to enable this for your project."
"description": "[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\"."
},
"sourceUris": {
"type": "array",
"description": "[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, and it must end with '.backup_info'. Also, the '*' wildcard character is not allowed.",
"description": "[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.",
"items": {
"type": "string"
}
@ -552,7 +612,7 @@
},
"errors": {
"type": "array",
"description": "[Output-only] All errors and warnings encountered during the running of the job. Errors here do not necessarily mean that the job has completed or was unsuccessful.",
"description": "[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.",
"items": {
"$ref": "ErrorProto"
}
@ -576,7 +636,7 @@
},
"numDmlAffectedRows": {
"type": "string",
"description": "[Output-only, Experimental] The number of rows affected by a DML statement. Present only for DML statements INSERT, UPDATE or DELETE.",
"description": "[Output-only] The number of rows affected by a DML statement. Present only for DML statements INSERT, UPDATE or DELETE.",
"format": "int64"
},
"pageToken": {
@ -606,6 +666,21 @@
}
}
},
"GetServiceAccountResponse": {
"id": "GetServiceAccountResponse",
"type": "object",
"properties": {
"email": {
"type": "string",
"description": "The service account email address."
},
"kind": {
"type": "string",
"description": "The resource type of the response.",
"default": "bigquery#getServiceAccountResponse"
}
}
},
"GoogleSheetsOptions": {
"id": "GoogleSheetsOptions",
"type": "object",
@ -760,12 +835,16 @@
},
"autodetect": {
"type": "boolean",
"description": "[Experimental] Indicates if we should automatically infer the options and schema for CSV and JSON sources."
"description": "Indicates if we should automatically infer the options and schema for CSV and JSON sources."
},
"createDisposition": {
"type": "string",
"description": "[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."
},
"destinationEncryptionConfiguration": {
"$ref": "EncryptionConfiguration",
"description": "[Experimental] Custom encryption configuration (e.g., Cloud KMS keys)."
},
"destinationTable": {
"$ref": "TableReference",
"description": "[Required] The destination table to load the data into."
@ -789,11 +868,11 @@
},
"nullMarker": {
"type": "string",
"description": "[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 still interprets the empty string as a null value for all data types except for STRING and BYTE. For STRING and BYTE columns, BigQuery interprets the empty string as an empty value."
"description": "[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."
},
"projectionFields": {
"type": "array",
"description": "[Experimental] 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.",
"description": "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.",
"items": {
"type": "string"
}
@ -818,7 +897,7 @@
},
"schemaUpdateOptions": {
"type": "array",
"description": "[Experimental] Allows the schema of the desitination table to be updated as a side effect of the load 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.",
"description": "Allows the schema of the desitination 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.",
"items": {
"type": "string"
}
@ -834,11 +913,15 @@
},
"sourceUris": {
"type": "array",
"description": "[Required] The fully-qualified URIs that point to your data in Google Cloud Storage. Each URI can contain one '*' wildcard character and it must come after the 'bucket' name.",
"description": "[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.",
"items": {
"type": "string"
}
},
"timePartitioning": {
"$ref": "TimePartitioning",
"description": "If specified, configures time-based partitioning for the destination table."
},
"writeDisposition": {
"type": "string",
"description": "[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."
@ -851,7 +934,8 @@
"properties": {
"allowLargeResults": {
"type": "boolean",
"description": "If true, allows the query to produce arbitrarily large result tables at a slight cost in performance. Requires destinationTable to be set."
"description": "[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.",
"default": "false"
},
"createDisposition": {
"type": "string",
@ -861,13 +945,17 @@
"$ref": "DatasetReference",
"description": "[Optional] Specifies the default dataset to use for unqualified table names in the query."
},
"destinationEncryptionConfiguration": {
"$ref": "EncryptionConfiguration",
"description": "[Experimental] Custom encryption configuration (e.g., Cloud KMS keys)."
},
"destinationTable": {
"$ref": "TableReference",
"description": "[Optional] Describes the table where the query results should be stored. If not present, a new table will be created to store the results."
"description": "[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."
},
"flattenResults": {
"type": "boolean",
"description": "[Optional] Flattens all nested and repeated fields in the query results. The default value is true. allowLargeResults must be true if this is set to false.",
"description": "[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.",
"default": "true"
},
"maximumBillingTier": {
@ -883,7 +971,7 @@
},
"parameterMode": {
"type": "string",
"description": "[Experimental] Standard SQL only. Set to POSITIONAL to use positional (?) query parameters or to NAMED to use named (@myparam) query parameters in this query."
"description": "Standard SQL only. Set to POSITIONAL to use positional (?) query parameters or to NAMED to use named (@myparam) query parameters in this query."
},
"preserveNulls": {
"type": "boolean",
@ -895,7 +983,7 @@
},
"query": {
"type": "string",
"description": "[Required] BigQuery SQL query to execute."
"description": "[Required] SQL query text to execute. The useLegacySql field can be used to indicate whether the query uses legacy SQL or standard SQL."
},
"queryParameters": {
"type": "array",
@ -906,7 +994,7 @@
},
"schemaUpdateOptions": {
"type": "array",
"description": "[Experimental] 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.",
"description": "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.",
"items": {
"type": "string"
}
@ -918,9 +1006,13 @@
"$ref": "ExternalDataConfiguration"
}
},
"timePartitioning": {
"$ref": "TimePartitioning",
"description": "If specified, configures time-based partitioning for the destination table."
},
"useLegacySql": {
"type": "boolean",
"description": "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 values of allowLargeResults and flattenResults are ignored; query will be run as if allowLargeResults is true and flattenResults is false."
"description": "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."
},
"useQueryCache": {
"type": "boolean",
@ -929,14 +1021,14 @@
},
"userDefinedFunctionResources": {
"type": "array",
"description": "[Experimental] Describes user-defined function resources used in the query.",
"description": "Describes user-defined function resources used in the query.",
"items": {
"$ref": "UserDefinedFunctionResource"
}
},
"writeDisposition": {
"type": "string",
"description": "[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."
"description": "[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."
}
}
},
@ -948,6 +1040,10 @@
"type": "string",
"description": "[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."
},
"destinationEncryptionConfiguration": {
"$ref": "EncryptionConfiguration",
"description": "[Experimental] Custom encryption configuration (e.g., Cloud KMS keys)."
},
"destinationTable": {
"$ref": "TableReference",
"description": "[Required] The destination table"
@ -1109,14 +1205,22 @@
"type": "boolean",
"description": "[Output-only] Whether the query result was fetched from the query cache."
},
"ddlOperationPerformed": {
"type": "string",
"description": "[Output-only, Experimental] 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."
},
"ddlTargetTable": {
"$ref": "TableReference",
"description": "[Output-only, Experimental] The DDL target table. Present only for CREATE/DROP TABLE/VIEW queries."
},
"numDmlAffectedRows": {
"type": "string",
"description": "[Output-only, Experimental] The number of rows affected by a DML statement. Present only for DML statements INSERT, UPDATE or DELETE.",
"description": "[Output-only] The number of rows affected by a DML statement. Present only for DML statements INSERT, UPDATE or DELETE.",
"format": "int64"
},
"queryPlan": {
"type": "array",
"description": "[Output-only, Experimental] Describes execution plan for the query.",
"description": "[Output-only] Describes execution plan for the query.",
"items": {
"$ref": "ExplainQueryStage"
}
@ -1146,6 +1250,11 @@
"description": "[Output-only] Total bytes processed for the job.",
"format": "int64"
},
"totalSlotMs": {
"type": "string",
"description": "[Output-only] Slot-milliseconds for the job.",
"format": "int64"
},
"undeclaredQueryParameters": {
"type": "array",
"description": "[Output-only, Experimental] Standard SQL only: list of undeclared query parameters detected during a dry run validation.",
@ -1159,6 +1268,11 @@
"id": "JobStatistics3",
"type": "object",
"properties": {
"badRecords": {
"type": "string",
"description": "[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.",
"format": "int64"
},
"inputFileBytes": {
"type": "string",
"description": "[Output-only] Number of bytes of source data in a load job.",
@ -1205,7 +1319,7 @@
},
"errors": {
"type": "array",
"description": "[Output-only] All errors encountered during the running of the job. Errors here do not necessarily mean that the job has completed or was unsuccessful.",
"description": "[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.",
"items": {
"$ref": "ErrorProto"
}
@ -1394,7 +1508,7 @@
},
"parameterMode": {
"type": "string",
"description": "[Experimental] Standard SQL only. Set to POSITIONAL to use positional (?) query parameters or to NAMED to use named (@myparam) query parameters in this query."
"description": "Standard SQL only. Set to POSITIONAL to use positional (?) query parameters or to NAMED to use named (@myparam) query parameters in this query."
},
"preserveNulls": {
"type": "boolean",
@ -1411,7 +1525,7 @@
},
"queryParameters": {
"type": "array",
"description": "[Experimental] Query parameters for Standard SQL queries.",
"description": "Query parameters for Standard SQL queries.",
"items": {
"$ref": "QueryParameter"
}
@ -1423,7 +1537,7 @@
},
"useLegacySql": {
"type": "boolean",
"description": "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 values of allowLargeResults and flattenResults are ignored; query will be run as if allowLargeResults is true and flattenResults is false.",
"description": "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.",
"default": "true"
},
"useQueryCache": {
@ -1443,7 +1557,7 @@
},
"errors": {
"type": "array",
"description": "[Output-only] All errors and warnings encountered during the running of the job. Errors here do not necessarily mean that the job has completed or was unsuccessful.",
"description": "[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.",
"items": {
"$ref": "ErrorProto"
}
@ -1463,7 +1577,7 @@
},
"numDmlAffectedRows": {
"type": "string",
"description": "[Output-only, Experimental] The number of rows affected by a DML statement. Present only for DML statements INSERT, UPDATE or DELETE.",
"description": "[Output-only] The number of rows affected by a DML statement. Present only for DML statements INSERT, UPDATE or DELETE.",
"format": "int64"
},
"pageToken": {
@ -1527,6 +1641,10 @@
"type": "string",
"description": "[Optional] A user-friendly description of this table."
},
"encryptionConfiguration": {
"$ref": "EncryptionConfiguration",
"description": "[Experimental] Custom encryption configuration (e.g., Cloud KMS keys)."
},
"etag": {
"type": "string",
"description": "[Output-only] A hash of this resource."
@ -1602,7 +1720,7 @@
},
"timePartitioning": {
"$ref": "TimePartitioning",
"description": "[Experimental] If specified, configures time-based partitioning for this table."
"description": "If specified, configures time-based partitioning for this table."
},
"type": {
"type": "string",
@ -1732,7 +1850,7 @@
"properties": {
"description": {
"type": "string",
"description": "[Optional] The field description. The maximum length is 16K characters."
"description": "[Optional] The field description. The maximum length is 1,024 characters."
},
"fields": {
"type": "array",
@ -1778,6 +1896,16 @@
"items": {
"type": "object",
"properties": {
"creationTime": {
"type": "string",
"description": "The time when this table was created, in milliseconds since the epoch.",
"format": "int64"
},
"expirationTime": {
"type": "string",
"description": "[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.",
"format": "int64"
},
"friendlyName": {
"type": "string",
"description": "The user-friendly name for this table."
@ -1802,6 +1930,10 @@
"$ref": "TableReference",
"description": "A reference uniquely identifying the table."
},
"timePartitioning": {
"$ref": "TimePartitioning",
"description": "The time-based partitioning for this table."
},
"type": {
"type": "string",
"description": "The type of table. Possible values are: TABLE, VIEW."
@ -1894,9 +2026,13 @@
"description": "[Optional] Number of milliseconds for which to keep the storage for a partition.",
"format": "int64"
},
"field": {
"type": "string",
"description": "[Experimental] [Optional] If not set, the table is partitioned by pseudo column '_PARTITIONTIME'; if set, the table is partitioned by this field. The field must be a top-level TIMESTAMP or DATE field. Its mode must be NULLABLE or REQUIRED."
},
"type": {
"type": "string",
"description": "[Required] The only type supported is DAY, which will generate one partition per day based on data loading time."
"description": "[Required] The only type supported is DAY, which will generate one partition per day."
}
}
},
@ -1928,7 +2064,7 @@
},
"userDefinedFunctionResources": {
"type": "array",
"description": "[Experimental] Describes user-defined function resources used in the query.",
"description": "Describes user-defined function resources used in the query.",
"items": {
"$ref": "UserDefinedFunctionResource"
}
@ -2415,6 +2551,31 @@
},
"projects": {
"methods": {
"getServiceAccount": {
"id": "bigquery.projects.getServiceAccount",
"path": "projects/{projectId}/serviceAccount",
"httpMethod": "GET",
"description": "Returns the email address of the service account for your project used for interactions with Google Cloud KMS.",
"parameters": {
"projectId": {
"type": "string",
"description": "Project ID for which the service account is requested.",
"required": true,
"location": "path"
}
},
"parameterOrder": [
"projectId"
],
"response": {
"$ref": "GetServiceAccountResponse"
},
"scopes": [
"https://www.googleapis.com/auth/bigquery",
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only"
]
},
"list": {
"id": "bigquery.projects.list",
"path": "projects",
@ -2517,6 +2678,11 @@
"required": true,
"location": "path"
},
"selectedFields": {
"type": "string",
"description": "List of fields to return (comma-separated). If unspecified, all fields are returned",
"location": "query"
},
"startIndex": {
"type": "string",
"description": "Zero-based index of the starting row to read",
@ -2601,6 +2767,11 @@
"required": true,
"location": "path"
},
"selectedFields": {
"type": "string",
"description": "List of fields to return (comma-separated). If unspecified, all fields are returned",
"location": "query"
},
"tableId": {
"type": "string",
"description": "Table ID of the requested table",

File diff suppressed because it is too large Load Diff

View File

@ -22,23 +22,33 @@ func MarshalJSON(schema interface{}, forceSendFields, nullFields []string) ([]by
return json.Marshal(schema)
}
mustInclude := make(map[string]struct{})
mustInclude := make(map[string]bool)
for _, f := range forceSendFields {
mustInclude[f] = struct{}{}
mustInclude[f] = true
}
useNull := make(map[string]struct{})
for _, f := range nullFields {
useNull[f] = struct{}{}
useNull := make(map[string]bool)
useNullMaps := make(map[string]map[string]bool)
for _, nf := range nullFields {
parts := strings.SplitN(nf, ".", 2)
field := parts[0]
if len(parts) == 1 {
useNull[field] = true
} else {
if useNullMaps[field] == nil {
useNullMaps[field] = map[string]bool{}
}
useNullMaps[field][parts[1]] = true
}
}
dataMap, err := schemaToMap(schema, mustInclude, useNull)
dataMap, err := schemaToMap(schema, mustInclude, useNull, useNullMaps)
if err != nil {
return nil, err
}
return json.Marshal(dataMap)
}
func schemaToMap(schema interface{}, mustInclude, useNull map[string]struct{}) (map[string]interface{}, error) {
func schemaToMap(schema interface{}, mustInclude, useNull map[string]bool, useNullMaps map[string]map[string]bool) (map[string]interface{}, error) {
m := make(map[string]interface{})
s := reflect.ValueOf(schema)
st := s.Type()
@ -59,17 +69,35 @@ func schemaToMap(schema interface{}, mustInclude, useNull map[string]struct{}) (
v := s.Field(i)
f := st.Field(i)
if _, ok := useNull[f.Name]; ok {
if useNull[f.Name] {
if !isEmptyValue(v) {
return nil, fmt.Errorf("field %q in NullFields has non-empty value", f.Name)
}
m[tag.apiName] = nil
continue
}
if !includeField(v, f, mustInclude) {
continue
}
// If map fields are explicitly set to null, use a map[string]interface{}.
if f.Type.Kind() == reflect.Map && useNullMaps[f.Name] != nil {
ms, ok := v.Interface().(map[string]string)
if !ok {
return nil, fmt.Errorf("field %q has keys in NullFields but is not a map[string]string", f.Name)
}
mi := map[string]interface{}{}
for k, v := range ms {
mi[k] = v
}
for k := range useNullMaps[f.Name] {
mi[k] = nil
}
m[tag.apiName] = mi
continue
}
// nil maps are treated as empty maps.
if f.Type.Kind() == reflect.Map && v.IsNil() {
m[tag.apiName] = map[string]string{}
@ -139,7 +167,7 @@ func parseJSONTag(val string) (jsonTag, error) {
}
// Reports whether the struct field "f" with value "v" should be included in JSON output.
func includeField(v reflect.Value, f reflect.StructField, mustInclude map[string]struct{}) bool {
func includeField(v reflect.Value, f reflect.StructField, mustInclude map[string]bool) bool {
// The regular JSON encoding of a nil pointer is "null", which means "delete this field".
// Therefore, we could enable field deletion by honoring pointer fields' presence in the mustInclude set.
// However, many fields are not pointers, so there would be no way to delete these fields.
@ -156,8 +184,7 @@ func includeField(v reflect.Value, f reflect.StructField, mustInclude map[string
return false
}
_, ok := mustInclude[f.Name]
return ok || !isEmptyValue(v)
return mustInclude[f.Name] || !isEmptyValue(v)
}
// isEmptyValue reports whether v is the empty value for its type. This

View File

@ -174,26 +174,126 @@ func typeHeader(contentType string) textproto.MIMEHeader {
// PrepareUpload determines whether the data in the supplied reader should be
// uploaded in a single request, or in sequential chunks.
// chunkSize is the size of the chunk that media should be split into.
// If chunkSize is non-zero and the contents of media do not fit in a single
// chunk (or there is an error reading media), then media will be returned as a
// MediaBuffer. Otherwise, media will be returned as a Reader.
//
// If chunkSize is zero, media is returned as the first value, and the other
// two return values are nil, true.
//
// Otherwise, a MediaBuffer is returned, along with a bool indicating whether the
// contents of media fit in a single chunk.
//
// After PrepareUpload has been called, media should no longer be used: the
// media content should be accessed via one of the return values.
func PrepareUpload(media io.Reader, chunkSize int) (io.Reader, *MediaBuffer) {
func PrepareUpload(media io.Reader, chunkSize int) (r io.Reader, mb *MediaBuffer, singleChunk bool) {
if chunkSize == 0 { // do not chunk
return media, nil
return media, nil, true
}
mb = NewMediaBuffer(media, chunkSize)
_, _, _, err := mb.Chunk()
// If err is io.EOF, we can upload this in a single request. Otherwise, err is
// either nil or a non-EOF error. If it is the latter, then the next call to
// mb.Chunk will return the same error. Returning a MediaBuffer ensures that this
// error will be handled at some point.
return nil, mb, err == io.EOF
}
// MediaInfo holds information for media uploads. It is intended for use by generated
// code only.
type MediaInfo struct {
// At most one of Media and MediaBuffer will be set.
media io.Reader
buffer *MediaBuffer
singleChunk bool
mType string
size int64 // mediaSize, if known. Used only for calls to progressUpdater_.
progressUpdater googleapi.ProgressUpdater
}
// NewInfoFromMedia should be invoked from the Media method of a call. It returns a
// MediaInfo populated with chunk size and content type, and a reader or MediaBuffer
// if needed.
func NewInfoFromMedia(r io.Reader, options []googleapi.MediaOption) *MediaInfo {
mi := &MediaInfo{}
opts := googleapi.ProcessMediaOptions(options)
if !opts.ForceEmptyContentType {
r, mi.mType = DetermineContentType(r, opts.ContentType)
}
mi.media, mi.buffer, mi.singleChunk = PrepareUpload(r, opts.ChunkSize)
return mi
}
// NewInfoFromResumableMedia should be invoked from the ResumableMedia method of a
// call. It returns a MediaInfo using the given reader, size and media type.
func NewInfoFromResumableMedia(r io.ReaderAt, size int64, mediaType string) *MediaInfo {
rdr := ReaderAtToReader(r, size)
rdr, mType := DetermineContentType(rdr, mediaType)
return &MediaInfo{
size: size,
mType: mType,
buffer: NewMediaBuffer(rdr, googleapi.DefaultUploadChunkSize),
media: nil,
singleChunk: false,
}
}
func (mi *MediaInfo) SetProgressUpdater(pu googleapi.ProgressUpdater) {
if mi != nil {
mi.progressUpdater = pu
}
}
// UploadType determines the type of upload: a single request, or a resumable
// series of requests.
func (mi *MediaInfo) UploadType() string {
if mi.singleChunk {
return "multipart"
}
return "resumable"
}
// UploadRequest sets up an HTTP request for media upload. It adds headers
// as necessary, and returns a replacement for the body.
func (mi *MediaInfo) UploadRequest(reqHeaders http.Header, body io.Reader) (newBody io.Reader, cleanup func()) {
cleanup = func() {}
if mi == nil {
return body, cleanup
}
var media io.Reader
if mi.media != nil {
// This only happens when the caller has turned off chunking. In that
// case, we write all of media in a single non-retryable request.
media = mi.media
} else if mi.singleChunk {
// The data fits in a single chunk, which has now been read into the MediaBuffer.
// We obtain that chunk so we can write it in a single request. The request can
// be retried because the data is stored in the MediaBuffer.
media, _, _, _ = mi.buffer.Chunk()
}
if media != nil {
combined, ctype := CombineBodyMedia(body, "application/json", media, mi.mType)
cleanup = func() { combined.Close() }
reqHeaders.Set("Content-Type", ctype)
body = combined
}
if mi.buffer != nil && mi.mType != "" && !mi.singleChunk {
reqHeaders.Set("X-Upload-Content-Type", mi.mType)
}
return body, cleanup
}
// ResumableUpload returns an appropriately configured ResumableUpload value if the
// upload is resumable, or nil otherwise.
func (mi *MediaInfo) ResumableUpload(locURI string) *ResumableUpload {
if mi == nil || mi.singleChunk {
return nil
}
return &ResumableUpload{
URI: locURI,
Media: mi.buffer,
MediaType: mi.mType,
Callback: func(curr int64) {
if mi.progressUpdater != nil {
mi.progressUpdater(curr, mi.size)
}
},
}
mb := NewMediaBuffer(media, chunkSize)
rdr, _, _, err := mb.Chunk()
if err == io.EOF { // we can upload this in a single request
return rdr, nil
}
// err might be a non-EOF error. If it is, the next call to mb.Chunk will
// return the same error. Returning a MediaBuffer ensures that this error
// will be handled at some point.
return nil, mb
}

View File

@ -5,6 +5,7 @@
package gensupport
import (
"errors"
"net/http"
"golang.org/x/net/context"
@ -32,6 +33,11 @@ func RegisterHook(h Hook) {
// If ctx is non-nil, it calls all hooks, then sends the request with
// ctxhttp.Do, then calls any functions returned by the hooks in reverse order.
func SendRequest(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) {
// Disallow Accept-Encoding because it interferes with the automatic gzip handling
// done by the default http.Transport. See https://github.com/google/google-api-go-client/issues/219.
if _, ok := req.Header["Accept-Encoding"]; ok {
return nil, errors.New("google api: custom Accept-Encoding headers not allowed")
}
if ctx == nil {
return client.Do(req)
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

18
vendor/vendor.json vendored
View File

@ -964,10 +964,10 @@
"revisionTime": "2016-12-14T09:25:55Z"
},
{
"checksumSHA1": "FEzQdhqmb6aqGL1lKnjOcUHIGSY=",
"checksumSHA1": "jhyv7qysp0NZbWzAaUCsKATDGuk=",
"path": "google.golang.org/api/bigquery/v2",
"revision": "16ab375f94503bfa0d19db78e96bffbe1a34354f",
"revisionTime": "2017-03-20T22:51:23Z"
"revision": "672d215daf0631fcae4c08c2a4324a763aaaf789",
"revisionTime": "2017-10-29T00:03:09Z"
},
{
"checksumSHA1": "I9nlJJGeNBvWlH7FLtRscT6NJhw=",
@ -1024,10 +1024,10 @@
"revisionTime": "2016-11-27T23:54:21Z"
},
{
"checksumSHA1": "C7k1pbU/WU4CBoBwA4EBUnV/iek=",
"checksumSHA1": "/y0saWnM+kTnSvZrNlvoNOgj0Uo=",
"path": "google.golang.org/api/gensupport",
"revision": "64485db7e8c8be51e572801d06cdbcfadd3546c1",
"revisionTime": "2017-02-23T23:41:36Z"
"revision": "672d215daf0631fcae4c08c2a4324a763aaaf789",
"revisionTime": "2017-10-29T00:03:09Z"
},
{
"checksumSHA1": "BWKmb7kGYbfbvXO6E7tCpTh9zKE=",
@ -1114,10 +1114,10 @@
"revisionTime": "2016-11-27T23:54:21Z"
},
{
"checksumSHA1": "xygm9BwoCg7vc0PPgAPdxNKJ38c=",
"checksumSHA1": "Zd7ojgrWPn3j7fLx9HB6/Oub8lE=",
"path": "google.golang.org/api/storage/v1",
"revision": "3cc2e591b550923a2c5f0ab5a803feda924d5823",
"revisionTime": "2016-11-27T23:54:21Z"
"revision": "672d215daf0631fcae4c08c2a4324a763aaaf789",
"revisionTime": "2017-10-29T00:03:09Z"
},
{
"checksumSHA1": "W24V3U8s386thzZOK6g+EjlKeu0=",

View File

@ -47,7 +47,6 @@ The following arguments are supported:
* `location` - (Optional, Default: 'US') The [GCS location](https://cloud.google.com/storage/docs/bucket-locations)
* `project` - (Optional) The project in which the resource belongs. If it
is not provided, the provider project is used.
@ -61,6 +60,8 @@ The following arguments are supported:
* `cors` - (Optional) The bucket's [Cross-Origin Resource Sharing (CORS)](https://www.w3.org/TR/cors/) configuration. Multiple blocks of this type are permitted. Structure is documented below.
* `labels` - (Optional) A set of key/value label pairs to assign to the bucket.
The `lifecycle_rule` block supports:
* `action` - (Required) The Lifecycle Rule's action configuration. A single block of this type is supported. Structure is documented below.