Skip to content

Commit

Permalink
add diff suppress for big query table schema (#3751) (#6803)
Browse files Browse the repository at this point in the history
* add diff suppress for big query table schema

* update comments

Signed-off-by: Modular Magician <[email protected]>
  • Loading branch information
modular-magician authored Jul 16, 2020
1 parent e09554d commit ef4bb49
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
3 changes: 3 additions & 0 deletions .changelog/3751.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
```release-note:bug
bigquery: fixed bug where a permadiff would show up when adding a column to the middle of a `bigquery_table.schema`
```
39 changes: 38 additions & 1 deletion google/resource_bigquery_table.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,49 @@ import (
"errors"
"fmt"
"log"
"reflect"
"sort"

"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/structure"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"google.golang.org/api/bigquery/v2"
)

// JSONBytesEqual compares the JSON in two byte slices.
// Reference: https://stackoverflow.com/questions/32408890/how-to-compare-two-json-requests
func JSONBytesEqual(a, b []byte) (bool, error) {
var j, j2 interface{}
if err := json.Unmarshal(a, &j); err != nil {
return false, err
}
jList := j.([]interface{})
sort.Slice(jList, func(i, k int) bool {
return jList[i].(map[string]interface{})["name"].(string) < jList[k].(map[string]interface{})["name"].(string)
})
if err := json.Unmarshal(b, &j2); err != nil {
return false, err
}
j2List := j2.([]interface{})
sort.Slice(j2List, func(i, k int) bool {
return j2List[i].(map[string]interface{})["name"].(string) < j2List[k].(map[string]interface{})["name"].(string)
})
return reflect.DeepEqual(j2List, jList), nil
}

// Compare the JSON strings are equal
func bigQueryTableSchemaDiffSuppress(_, old, new string, _ *schema.ResourceData) bool {
oldBytes := []byte(old)
newBytes := []byte(new)

eq, err := JSONBytesEqual(oldBytes, newBytes)
if err != nil {
log.Printf("[DEBUG] Error comparing JSON bytes: %v, %v", old, new)
}

return eq
}

func resourceBigQueryTable() *schema.Resource {
return &schema.Resource{
Create: resourceBigQueryTableCreate,
Expand Down Expand Up @@ -299,7 +335,8 @@ func resourceBigQueryTable() *schema.Resource {
json, _ := structure.NormalizeJsonString(v)
return json
},
Description: `A JSON schema for the table.`,
DiffSuppressFunc: bigQueryTableSchemaDiffSuppress,
Description: `A JSON schema for the table.`,
},

// View: [Optional] If specified, configures this table as a view.
Expand Down

0 comments on commit ef4bb49

Please sign in to comment.