forked from GoogleCloudPlatform/magic-modules
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresource_bigquery_table.go.tmpl
More file actions
3864 lines (3343 loc) · 135 KB
/
Copy pathresource_bigquery_table.go.tmpl
File metadata and controls
3864 lines (3343 loc) · 135 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package bigquery
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"time"
"golang.org/x/exp/slices"
"github.com/hashicorp/go-cty/cty"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/hashicorp/terraform-provider-google/google/registry"
"github.com/hashicorp/terraform-provider-google/google/tpgresource"
transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport"
"google.golang.org/api/bigquery/v2"
)
func bigQueryTableSortArrayByName(array []interface{}) {
sort.Slice(array, func(i, k int) bool {
return array[i].(map[string]interface{})["name"].(string) < array[k].(map[string]interface{})["name"].(string)
})
}
func bigQueryArrayToMapIndexedByName(array []interface{}) map[string]interface{} {
out := map[string]interface{}{}
for _, v := range array {
name := v.(map[string]interface{})["name"].(string)
out[name] = v
}
return out
}
func bigQueryTablecheckNameExists(jsonList []interface{}) error {
for _, m := range jsonList {
if _, ok := m.(map[string]interface{})["name"]; !ok {
return fmt.Errorf("No name in schema %+v", m)
}
}
return nil
}
// Compares two json's while optionally taking in a compareMapKeyVal function.
// This function will override any comparison of a given map[string]interface{}
// on a specific key value allowing for a separate equality in specific scenarios
func jsonCompareWithMapKeyOverride(key string, a, b interface{}, compareMapKeyVal func(key string, val1, val2 map[string]interface{}, d *schema.ResourceData) bool, d *schema.ResourceData) (bool, error) {
switch a.(type) {
case []interface{}:
arrayA := a.([]interface{})
arrayB, ok := b.([]interface{})
if !ok {
return false, nil
} else if len(arrayA) != len(arrayB) {
return false, nil
}
// Sort fields by name so reordering them doesn't cause a diff.
if key == "schema" || key == "fields" {
if err := bigQueryTablecheckNameExists(arrayA); err != nil {
return false, err
}
bigQueryTableSortArrayByName(arrayA)
if err := bigQueryTablecheckNameExists(arrayB); err != nil {
return false, err
}
bigQueryTableSortArrayByName(arrayB)
}
for i := range arrayA {
eq, err := jsonCompareWithMapKeyOverride(strconv.Itoa(i), arrayA[i], arrayB[i], compareMapKeyVal, d)
if err != nil {
return false, err
} else if !eq {
return false, nil
}
}
return true, nil
case map[string]interface{}:
objectA := a.(map[string]interface{})
objectB, ok := b.(map[string]interface{})
if !ok {
return false, nil
}
var unionOfKeys map[string]bool = make(map[string]bool)
for subKey := range objectA {
unionOfKeys[subKey] = true
}
for subKey := range objectB {
unionOfKeys[subKey] = true
}
// Disregard "type" and "fields" if "foreignTypeDefinition" is present since they may have been modified by the server.
if _, ok := unionOfKeys["foreignTypeDefinition"]; ok {
delete(unionOfKeys, "type")
delete(unionOfKeys, "fields")
}
for subKey := range unionOfKeys {
eq := compareMapKeyVal(subKey, objectA, objectB, d)
if !eq {
valA, ok1 := objectA[subKey]
valB, ok2 := objectB[subKey]
if !ok1 || !ok2 {
return false, nil
}
eq, err := jsonCompareWithMapKeyOverride(subKey, valA, valB, compareMapKeyVal, d)
if err != nil || !eq {
return false, err
}
}
}
return true, nil
case string, float64, bool, nil:
return a == b, nil
default:
log.Printf("[DEBUG] tried to iterate through json but encountered a non native type to json deserialization... please ensure you are passing a json object from json.Unmarshall")
return false, errors.New("unable to compare values")
}
}
// checks if the value is within the array, only works for generics
// because objects and arrays will take the reference comparison
func valueIsInArray(value interface{}, array []interface{}) bool {
for _, item := range array {
if item == value {
return true
}
}
return false
}
// This function merges the live dataPolicies with the ones defined in tf config
// This will be called only when "ignore_schema_changes" with "dataPolicies" is defined
func mergeDataPolicies(configFields []*bigquery.TableFieldSchema, liveFields []*bigquery.TableFieldSchema, rawSchema []interface{}) {
liveMap := make(map[string]*bigquery.TableFieldSchema)
if liveFields != nil {
for _, f := range liveFields {
liveMap[f.Name] = f
}
}
rawMap := make(map[string]map[string]interface{})
for _, item := range rawSchema {
if m, ok := item.(map[string]interface{}); ok {
if name, ok := m["name"].(string); ok {
rawMap[name] = m
}
}
}
for _, configField := range configFields {
rawField, rawExists := rawMap[configField.Name]
liveField := liveMap[configField.Name]
// Recursively handle nested fields (RECORD/STRUCT types)
if len(configField.Fields) > 0 {
var liveNested []*bigquery.TableFieldSchema
if liveField != nil {
liveNested = liveField.Fields
}
var rawNested []interface{}
if rawExists {
if fields, ok := rawField["fields"].([]interface{}); ok {
rawNested = fields
}
}
mergeDataPolicies(configField.Fields, liveNested, rawNested)
}
// Handle DataPolicies logic
dataPoliciesSpecified := false
if rawExists {
// Check if "dataPolicies" key explicitly exists in the raw config JSON
_, dataPoliciesSpecified = rawField["dataPolicies"]
}
// If the user did NOT specify dataPolicies in the config,
// and they exist on the server, copy them to the config struct.
if !dataPoliciesSpecified && liveField != nil {
if len(liveField.DataPolicies) > 0 {
configField.DataPolicies = liveField.DataPolicies
}
}
}
}
// If the same table column is found in both the TF config and live state,
// and the column in the live state has data policies when the column in the TF config doesn't,
// copy the data policies from live state into the TF config.
func mergeDataPoliciesIntoMap(old, new []interface{}) {
oldMap := make(map[string]map[string]interface{})
for _, v := range old {
if m, ok := v.(map[string]interface{}); ok {
if name, ok := m["name"].(string); ok {
oldMap[name] = m
}
}
}
for _, v := range new {
newField, ok := v.(map[string]interface{})
if !ok {
continue
}
name := newField["name"].(string)
if oldField, exists := oldMap[name]; exists {
// If config doesn't have dataPolicies, but backend does, copy them over
if _, specified := newField["dataPolicies"]; !specified {
if dp, hasDP := oldField["dataPolicies"]; hasDP {
newField["dataPolicies"] = dp
log.Printf("[DEBUG] Added live data policy to schema: %v", dp)
}
}
// Recursively handle nested fields (RECORD types)
if oldNested, ok1 := oldField["fields"].([]interface{}); ok1 {
if newNested, ok2 := newField["fields"].([]interface{}); ok2 {
mergeDataPoliciesIntoMap(oldNested, newNested)
}
}
}
}
}
func bigQueryTableMapKeyOverride(key string, objectA, objectB map[string]interface{}, d *schema.ResourceData) bool {
// we rely on the fallback to nil if the object does not have the key
valA := objectA[key]
valB := objectB[key]
switch key {
case "mode":
eq := bigQueryTableNormalizeMode(valA) == bigQueryTableNormalizeMode(valB)
return eq
case "description":
equivalentSet := []interface{}{nil, ""}
eq := valueIsInArray(valA, equivalentSet) && valueIsInArray(valB, equivalentSet)
return eq
case "type":
if valA == nil || valB == nil {
return false
}
return bigQueryTableTypeEq(valA.(string), valB.(string))
case "collation":
// If the configuration (valB) is nil or missing, it implies "inherit from dataset".
// We suppress the diff by returning true, accepting whatever actual value (valA)
// the server returned (e.g., "und:ci").
if valB == nil {
return true
}
equivalentSet := []interface{}{nil, ""}
eq := valueIsInArray(valA, equivalentSet) && valueIsInArray(valB, equivalentSet)
return eq
case "policyTags":
eq := bigQueryTableNormalizePolicyTags(valA) == nil && bigQueryTableNormalizePolicyTags(valB) == nil
return eq
case "dataPolicies":
if d == nil {
return false
}
// Access the ignore_schema_changes list from the Terraform configuration
var ignoreSchemaChanges []interface{}
if val := d.Get("ignore_schema_changes"); val != nil {
ignoreSchemaChanges = val.([]interface{})
}
// If dataPolicies is ignored...
if slices.Contains(ignoreSchemaChanges, "dataPolicies") {
// Check if the NEW value (valB) is empty or nil.
// If it is empty, we suppress the diff (return true) to keep backend values.
if valB == nil {
return true
}
if s, ok := valB.([]interface{}); ok && len(s) == 0 {
return true
}
// If the user EXPLICITLY provided dataPolicies, we return false.
// This tells Terraform "There is a difference, and I want you to apply it."
return false
}
return false
}
// otherwise rely on default behavior
return false
}
// Compare the JSON strings are equal
func bigQueryTableSchemaDiffSuppress(name, old, new string, d *schema.ResourceData) bool {
// The API can return an empty schema which gets encoded to "null" during read.
if old == "null" {
old = "[]"
}
var a, b interface{}
if err := json.Unmarshal([]byte(old), &a); err != nil {
log.Printf("[DEBUG] unable to unmarshal old json - %v", err)
}
if err := json.Unmarshal([]byte(new), &b); err != nil {
log.Printf("[DEBUG] unable to unmarshal new json - %v", err)
}
eq, err := jsonCompareWithMapKeyOverride(name, a, b, bigQueryTableMapKeyOverride, d)
if err != nil {
log.Printf("[DEBUG] %v", err)
log.Printf("[DEBUG] Error comparing JSON: %v, %v", old, new)
}
return eq
}
func bigQueryTableConnectionIdSuppress(name, old, new string, _ *schema.ResourceData) bool {
// API accepts connectionId in below two formats
// "<project>.<location>.<connection_id>" or
// "projects/<project}>locations/<location>/connections/<connection_id>".
// but always returns "<project>.<location>.<connection_id>"
if tpgresource.IsEmptyValue(reflect.ValueOf(old)) || tpgresource.IsEmptyValue(reflect.ValueOf(new)) {
return false
}
// Old is in the dot format, and new is in the slash format.
// They represent the same connection if the project, locaition, and IDs are
// the same.
// Location should use a case-insenstive comparison.
dotRe := regexp.MustCompile(`(.+)\.(.+)\.(.+)`)
slashRe := regexp.MustCompile("projects/(.+)/(?:locations|regions)/(.+)/connections/(.+)")
dotMatches := dotRe.FindStringSubmatch(old)
slashMatches := slashRe.FindStringSubmatch(new)
if dotMatches != nil && slashMatches != nil {
sameProject := dotMatches[1] == slashMatches[1]
sameLocation := strings.EqualFold(dotMatches[2], slashMatches[2])
sameId := dotMatches[3] == slashMatches[3]
return sameProject && sameLocation && sameId
}
return false
}
func bigQueryTableTypeEq(old, new string) bool {
// Do case-insensitive comparison. https://github.com/hashicorp/terraform-provider-google/issues/9472
oldUpper := strings.ToUpper(old)
newUpper := strings.ToUpper(new)
equivalentSet1 := []interface{}{"INTEGER", "INT64"}
equivalentSet2 := []interface{}{"FLOAT", "FLOAT64"}
equivalentSet3 := []interface{}{"BOOLEAN", "BOOL"}
eq0 := oldUpper == newUpper
eq1 := valueIsInArray(oldUpper, equivalentSet1) && valueIsInArray(newUpper, equivalentSet1)
eq2 := valueIsInArray(oldUpper, equivalentSet2) && valueIsInArray(newUpper, equivalentSet2)
eq3 := valueIsInArray(oldUpper, equivalentSet3) && valueIsInArray(newUpper, equivalentSet3)
eq := eq0 || eq1 || eq2 || eq3
return eq
}
func bigQueryTableNormalizeMode(mode interface{}) string {
if mode == nil {
return "NULLABLE"
}
// Upper-case to get case-insensitive comparisons. https://github.com/hashicorp/terraform-provider-google/issues/9472
return strings.ToUpper(mode.(string))
}
func bigQueryTableModeIsForceNew(old, new string) bool {
eq := old == new
reqToNull := old == "REQUIRED" && new == "NULLABLE"
return !eq && !reqToNull
}
func bigQueryTableNormalizePolicyTags(val interface{}) interface{} {
if val == nil {
return nil
}
if policyTags, ok := val.(map[string]interface{}); ok {
// policyTags = {} is same as nil.
if len(policyTags) == 0 {
return nil
}
// policyTags = {names = []} is same as nil.
if names, ok := policyTags["names"].([]interface{}); ok && len(names) == 0 {
return nil
}
}
return val
}
func bigQueryTableHasRowAccessPolicy(config *transport_tpg.Config, project, datasetId, tableId string) (bool, error) {
url := fmt.Sprintf("https://bigquery.googleapis.com/bigquery/v2/projects/%s/datasets/%s/tables/%s/rowAccessPolicies", project, datasetId, tableId)
res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{
Config: config,
Method: "GET",
RawURL: url,
UserAgent: config.UserAgent,
})
if err != nil {
return false, err
}
if policies, ok := res["rowAccessPolicies"]; ok {
if policiesList, ok := policies.([]interface{}); ok && len(policiesList) > 0 {
log.Printf("[INFO] Table has row access policies, schema change detected dropped columns and will force the table to recreate.")
return true, nil
}
}
return false, nil
}
func bigQueryTableHasRowAccessPolicyFunc(config *transport_tpg.Config, project, datasetId, tableId string) func() (bool, error) {
return func() (bool, error) {
return bigQueryTableHasRowAccessPolicy(config, project, datasetId, tableId)
}
}
// Compares two existing schema implementations and decides if
// it is changeable.. pairs with a force new on not changeable
func resourceBigQueryTableSchemaIsChangeable(old, new interface{}, isExternalTable bool, topLevel bool, hasRowAccessPolicyFunc func() (bool, error)) (bool, error) {
switch old.(type) {
case []interface{}:
arrayOld := old.([]interface{})
arrayNew, ok := new.([]interface{})
sameNameColumns := 0
droppedColumns := 0
if !ok {
// if not both arrays not changeable
return false, nil
}
if err := bigQueryTablecheckNameExists(arrayOld); err != nil {
return false, err
}
mapOld := bigQueryArrayToMapIndexedByName(arrayOld)
if err := bigQueryTablecheckNameExists(arrayNew); err != nil {
return false, err
}
mapNew := bigQueryArrayToMapIndexedByName(arrayNew)
for key := range mapNew {
// making unchangeable if an newly added column is with REQUIRED mode
if _, ok := mapOld[key]; !ok {
items := mapNew[key].(map[string]interface{})
for k := range items {
if k == "mode" && fmt.Sprintf("%v", items[k]) == "REQUIRED" {
return false, nil
}
}
}
}
for key := range mapOld {
// dropping top level columns can happen in-place
// but this doesn't apply to external tables
if _, ok := mapNew[key]; !ok {
if !topLevel || isExternalTable {
return false, nil
}
droppedColumns += 1
continue
}
isChangable, err := resourceBigQueryTableSchemaIsChangeable(mapOld[key], mapNew[key], isExternalTable, false, hasRowAccessPolicyFunc)
if err != nil || !isChangable {
return false, err
} else if isChangable && topLevel {
// top level column that exists in the new schema
sameNameColumns += 1
}
}
// In-place column dropping is not supported when there are row access
// policies on the table.
hasDroppedColumns := droppedColumns > 0
if hasDroppedColumns && topLevel {
hasRowAccessPolicy, err := hasRowAccessPolicyFunc()
if err == nil && hasRowAccessPolicy {
return false, nil
}
}
// In-place column dropping alongside column additions is not allowed
// as of now because user intention can be ambiguous (e.g. column renaming)
newColumns := len(arrayNew) - sameNameColumns
isSchemaChangeable := (droppedColumns == 0) || (newColumns == 0)
return isSchemaChangeable, nil
case map[string]interface{}:
objectOld := old.(map[string]interface{})
objectNew, ok := new.(map[string]interface{})
if !ok {
// if both aren't objects
return false, nil
}
var unionOfKeys map[string]bool = make(map[string]bool)
for key := range objectOld {
unionOfKeys[key] = true
}
for key := range objectNew {
unionOfKeys[key] = true
}
// Disregard "type" and "fields" if "foreignTypeDefinition" is present since they may have been modified by the server.
if _, ok := unionOfKeys["foreignTypeDefinition"]; ok {
delete(unionOfKeys, "type")
delete(unionOfKeys, "fields")
}
for key := range unionOfKeys {
valOld := objectOld[key]
valNew := objectNew[key]
switch key {
case "name":
if valOld != valNew {
return false, nil
}
case "type":
if valOld == nil || valNew == nil {
// This is invalid, so it shouldn't require a ForceNew
return true, nil
}
if !bigQueryTableTypeEq(valOld.(string), valNew.(string)) {
return false, nil
}
case "mode":
if bigQueryTableModeIsForceNew(
bigQueryTableNormalizeMode(valOld),
bigQueryTableNormalizeMode(valNew),
) {
return false, nil
}
case "fields":
return resourceBigQueryTableSchemaIsChangeable(valOld, valNew, isExternalTable, false, hasRowAccessPolicyFunc)
// other parameters: description, policyTags and
// policyTags.names[] are changeable
}
}
return true, nil
case string, float64, bool, nil:
// realistically this shouldn't hit
log.Printf("[DEBUG] comparison of generics hit... not expected")
return old == new, nil
default:
log.Printf("[DEBUG] tried to iterate through json but encountered a non native type to json deserialization... please ensure you are passing a json object from json.Unmarshall")
return false, errors.New("unable to compare values")
}
}
func resourceBigQueryTableSchemaCustomizeDiffFunc(d tpgresource.TerraformResourceDiff, hasRowAccessPolicyFunc func() (bool, error)) error {
if _, hasSchema := d.GetOk("schema"); hasSchema {
oldSchema, newSchema := d.GetChange("schema")
oldSchemaText := oldSchema.(string)
newSchemaText := newSchema.(string)
if oldSchemaText == "null" {
// The API can return an empty schema which gets encoded to "null" during read.
oldSchemaText = "[]"
}
if newSchemaText == "null" {
newSchemaText = "[]"
}
var old, new interface{}
if err := json.Unmarshal([]byte(oldSchemaText), &old); err != nil {
// don't return error, its possible we are going from no schema to schema
// this case will be cover on the conparision regardless.
log.Printf("[DEBUG] unable to unmarshal json customized diff - %v", err)
}
if err := json.Unmarshal([]byte(newSchemaText), &new); err != nil {
// same as above
log.Printf("[DEBUG] unable to unmarshal json customized diff - %v", err)
}
var ignoreSchemaChanges []interface{}
if val := d.Get("ignore_schema_changes"); val != nil {
ignoreSchemaChanges = val.([]interface{})
}
if slices.Contains(ignoreSchemaChanges, "dataPolicies") {
oldList, okOld := old.([]interface{})
newList, okNew := new.([]interface{})
if okOld && okNew {
// Modify the 'new' object in memory to include hidden backend policies
mergeDataPoliciesIntoMap(oldList, newList)
// Marshal the modified 'new' state back to JSON
updatedNewJSON, err := json.Marshal(newList)
if err == nil {
// Update the diff so Terraform's UI sees the policies as "present" in the new state
if err := d.SetNew("schema", string(updatedNewJSON)); err != nil {
return err
}
// Update local variable for subsequent logic in this function
new = newList
}
}
}
if ignore, ok := d.Get("ignore_auto_generated_schema").(bool); ok && ignore {
oldSchemaObj, err1 := expandSchema(oldSchemaText, false)
newSchemaObj, err2 := expandSchema(newSchemaText, false)
if err1 == nil && err2 == nil && oldSchemaObj != nil && newSchemaObj != nil {
filteredOldSchema, autogenFields := filterLiveSchemaByConfig(oldSchemaObj, newSchemaObj)
if len(autogenFields) > 0 {
filteredOldJsonStr, err := flattenSchema(filteredOldSchema)
if err == nil {
if bigQueryTableSchemaDiffSuppress("schema", filteredOldJsonStr, newSchemaText, nil) {
// Suppress diff by setting new to old in diff
if err := d.SetNew("schema", oldSchemaText); err != nil {
return err
}
// Update local variable so reflect.DeepEqual returns true
new = old
}
}
}
}
}
// no is schema changeable check needed, if new schema is old schema
if reflect.DeepEqual(old, new) {
return nil
}
_, isExternalTable := d.GetOk("external_data_configuration")
isChangeable, err := resourceBigQueryTableSchemaIsChangeable(old, new, isExternalTable, true, hasRowAccessPolicyFunc)
if err != nil {
return err
}
if !isChangeable {
if err := d.ForceNew("schema"); err != nil {
return err
}
}
return nil
}
return nil
}
func resourceBigQueryTableSchemaCustomizeDiff(_ context.Context, d *schema.ResourceDiff, meta interface{}) error {
config := meta.(*transport_tpg.Config)
project, err := tpgresource.GetProjectFromDiff(d, config)
if err != nil {
return err
}
datasetId := d.Get("dataset_id").(string)
tableId := d.Get("table_id").(string)
hasRowAccessPolicyFunc := bigQueryTableHasRowAccessPolicyFunc(config, project, datasetId, tableId)
return resourceBigQueryTableSchemaCustomizeDiffFunc(d, hasRowAccessPolicyFunc)
}
func validateBigQueryTableSchema(v interface{}, k string) (warnings []string, errs []error) {
if v == nil {
return
}
if _, e := validation.StringIsJSON(v, k); e != nil {
errs = append(errs, e...)
return
}
var jsonList []interface{}
if err := json.Unmarshal([]byte(v.(string)), &jsonList); err != nil {
errs = append(errs, fmt.Errorf("\"schema\" is not a JSON array: %s", err))
return
}
for _, v := range jsonList {
if v == nil {
errs = append(errs, errors.New("\"schema\" contains a nil element"))
return
}
}
return
}
func ResourceBigQueryTable() *schema.Resource {
return &schema.Resource{
Create: resourceBigQueryTableCreate,
Read: resourceBigQueryTableRead,
Delete: resourceBigQueryTableDelete,
Update: resourceBigQueryTableUpdate,
Importer: &schema.ResourceImporter{
State: resourceBigQueryTableImport,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(20 * time.Minute),
Update: schema.DefaultTimeout(20 * time.Minute),
Delete: schema.DefaultTimeout(20 * time.Minute),
},
CustomizeDiff: customdiff.All(
tpgresource.DefaultProviderProject,
resourceBigQueryTableSchemaCustomizeDiff,
tpgresource.SetLabelsDiff,
),
Schema: map[string]*schema.Schema{
// TableId: [Required] The ID of the table. The ID must contain only
// letters (a-z, A-Z), numbers (0-9), or underscores (_). The maximum
// length is 1,024 characters.
"table_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: `A unique ID for the resource. Changing this forces a new resource to be created.`,
},
// DatasetId: [Required] The ID of the dataset containing this table.
"dataset_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: `The dataset ID to create the table in. Changing this forces a new resource to be created.`,
},
// ProjectId: [Required] The ID of the project containing this table.
"project": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
Description: `The ID of the project in which the resource belongs.`,
},
// Description: [Optional] A user-friendly description of this table.
"description": {
Type: schema.TypeString,
Optional: true,
Description: `The field description.`,
},
// ExpirationTime: [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.
"expiration_time": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Description: `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.`,
},
// ExternalDataConfiguration [Optional] Describes the data format,
// location, and other properties of a table stored outside of BigQuery.
// By defining these properties, the data source can then be queried as
// if it were a standard BigQuery table.
"external_data_configuration": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: `Describes the data format, location, and other properties of a table stored outside of BigQuery. By defining these properties, the data source can then be queried as if it were a standard BigQuery table.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
// Autodetect : [Required] If true, let BigQuery try to autodetect the
// schema and format of the table.
"autodetect": {
Type: schema.TypeBool,
Required: true,
Description: `Let BigQuery try to autodetect the schema and format of the table.`,
},
// SourceFormat [Required] The data format.
"source_format": {
Type: schema.TypeString,
Optional: true,
Description: `Please see sourceFormat under ExternalDataConfiguration in Bigquery's public API documentation (https://cloud.google.com/bigquery/docs/reference/rest/v2/tables#externaldataconfiguration) for supported formats. To use "GOOGLE_SHEETS" the scopes must include "googleapis.com/auth/drive.readonly".`,
ValidateFunc: validation.StringInSlice([]string{
"CSV", "GOOGLE_SHEETS", "NEWLINE_DELIMITED_JSON", "AVRO", "ICEBERG", "DATASTORE_BACKUP", "PARQUET", "ORC", "BIGTABLE", "DELTA_LAKE",
}, false),
},
// SourceURIs [Required] The fully-qualified URIs that point to your data in Google Cloud.
"source_uris": {
Type: schema.TypeList,
Required: true,
Description: `A list of the fully-qualified URIs that point to your data in Google Cloud.`,
Elem: &schema.Schema{Type: schema.TypeString},
},
// FileSetSpecType: [Optional] Specifies how source URIs are interpreted for constructing the file set to load. By default source URIs are expanded against the underlying storage. Other options include specifying manifest files. Only applicable to object storage systems.
"file_set_spec_type": {
Type: schema.TypeString,
Optional: true,
Description: `Specifies how source URIs are interpreted for constructing the file set to load. By default source URIs are expanded against the underlying storage. Other options include specifying manifest files. Only applicable to object storage systems.`,
},
// Compression: [Optional] The compression type of the data source.
"compression": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"NONE", "GZIP"}, false),
Default: "NONE",
Description: `The compression type of the data source. Valid values are "NONE" or "GZIP".`,
},
// Schema: [Optional] The schema for the data.
// Schema is required for CSV and JSON formats if autodetect is not on.
// Schema is disallowed for Google Cloud Bigtable, Cloud Datastore backups, Avro, Iceberg, ORC, and Parquet formats.
"schema": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validateBigQueryTableSchema,
StateFunc: func(v interface{}) string {
json, _ := structure.NormalizeJsonString(v)
return json
},
DiffSuppressFunc: bigQueryTableSchemaDiffSuppress,
Description: `A JSON schema for the external table. Schema is required for CSV and JSON formats and is disallowed for Google Cloud Bigtable, Cloud Datastore backups, and Avro formats when using external tables.`,
},
// CsvOptions: [Optional] Additional properties to set if
// sourceFormat is set to CSV.
"csv_options": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: `Additional properties to set if source_format is set to "CSV".`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
// Quote: [Required] The value that is used to quote data
// sections in a CSV file.
"quote": {
Type: schema.TypeString,
Required: true,
Description: `The value that is used to quote data sections in a CSV file. 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 allow_quoted_newlines property to true. The API-side default is ", specified in Terraform escaped as \". Due to limitations with Terraform default values, this value is required to be explicitly set.`,
},
// AllowJaggedRows: [Optional] Indicates if BigQuery should
// accept rows that are missing trailing optional columns.
"allow_jagged_rows": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: `Indicates if BigQuery should accept rows that are missing trailing optional columns.`,
},
// AllowQuotedNewlines: [Optional] Indicates if BigQuery
// should allow quoted data sections that contain newline
// characters in a CSV file. The default value is false.
"allow_quoted_newlines": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: `Indicates if BigQuery should allow quoted data sections that contain newline characters in a CSV file. The default value is false.`,
},
// Encoding: [Optional] The character encoding of the data.
// The supported values are UTF-8 or ISO-8859-1.
"encoding": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"ISO-8859-1", "UTF-8"}, false),
Default: "UTF-8",
Description: `The character encoding of the data. The supported values are UTF-8 or ISO-8859-1.`,
},
// FieldDelimiter: [Optional] The separator for fields in a CSV file.
"field_delimiter": {
Type: schema.TypeString,
Optional: true,
Default: ",",
Description: `The separator for fields in a CSV file.`,
},
// SkipLeadingRows: [Optional] The number of rows at the top
// of a CSV file that BigQuery will skip when reading the data.
"skip_leading_rows": {
Type: schema.TypeInt,
Optional: true,
Default: 0,
Description: `The number of rows at the top of a CSV file that BigQuery will skip when reading the data.`,
},
"source_column_match": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"POSITION", "NAME"}, false),
Description: `Specifies how source columns are matched to the table schema. Valid values are POSITION (columns matched by position, assuming same ordering) or NAME (columns matched by name, reads header row and reorders columns to align with schema field names).`,
},
},
},
},
// jsonOptions: [Optional] Additional properties to set if sourceFormat is set to JSON.
"json_options": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: `Additional properties to set if sourceFormat is set to JSON.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"encoding": {
Type: schema.TypeString,
Optional: true,
Default: "UTF-8",
ValidateFunc: validation.StringInSlice([]string{"UTF-8", "UTF-16BE", "UTF-16LE", "UTF-32BE", "UTF-32LE"}, false),
Description: `The character encoding of the data. The supported values are UTF-8, UTF-16BE, UTF-16LE, UTF-32BE, and UTF-32LE. The default value is UTF-8.`,
},
},
},
},
"json_extension": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"GEOJSON"}, false),
Description: `Load option to be used together with sourceFormat newline-delimited JSON to indicate that a variant of JSON is being loaded. To load newline-delimited GeoJSON, specify GEOJSON (and sourceFormat must be set to NEWLINE_DELIMITED_JSON).`,
},
"bigtable_options": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: `Additional options if sourceFormat is set to BIGTABLE.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"column_family": {
Type: schema.TypeList,
Optional: true,
Description: `A list of column families to expose in the table schema along with their types. This list restricts the column families that can be referenced in queries and specifies their value types. You can use this list to do type conversions - see the 'type' field for more details. If you leave this list empty, all column families are present in the table schema and their values are read as BYTES. During a query only the column families referenced in that query are read from Bigtable.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"column": {
Type: schema.TypeList,
Optional: true,
Description: `A List of columns that should be exposed as individual fields as opposed to a list of (column name, value) pairs. All columns whose qualifier matches a qualifier in this list can be accessed as Other columns can be accessed as a list through column field`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"qualifier_encoded": {
Type: schema.TypeString,
Optional: true,
Description: `Qualifier of the column. Columns in the parent column family that has this exact qualifier are exposed as . field. If the qualifier is valid UTF-8 string, it can be specified in the qualifierString field. Otherwise, a base-64 encoded value must be set to qualifierEncoded. The column field name is the same as the column qualifier. However, if the qualifier is not a valid BigQuery field identifier i.e. does not match [a-zA-Z][a-zA-Z0-9_]*, a valid identifier must be provided as fieldName.`,
},
"qualifier_string": {
Type: schema.TypeString,
Optional: true,
Description: `Qualifier string.`,
},
"field_name": {
Type: schema.TypeString,
Optional: true,
Description: `If the qualifier is not a valid BigQuery field identifier i.e. does not match [a-zA-Z][a-zA-Z0-9_]*, a valid identifier must be provided as the column field name and is used as field name in queries.`,
},
"type": {
Type: schema.TypeString,
Optional: true,
Description: `The type to convert the value in cells of this column. The values are expected to be encoded using HBase Bytes.toBytes function when using the BINARY encoding value. Following BigQuery types are allowed (case-sensitive): "BYTES", "STRING", "INTEGER", "FLOAT", "BOOLEAN", "JSON", Default type is "BYTES". 'type' can also be set at the column family level. However, the setting at this level takes precedence if 'type' is set at both levels.`,
},
"encoding": {
Type: schema.TypeString,
Optional: true,
Description: `The encoding of the values when the type is not STRING. Acceptable encoding values are: TEXT - indicates values are alphanumeric text strings. BINARY - indicates values are encoded using HBase Bytes.toBytes family of functions. 'encoding' can also be set at the column family level. However, the setting at this level takes precedence if 'encoding' is set at both levels.`,
},
"only_read_latest": {
Type: schema.TypeBool,
Optional: true,
Description: `If this is set, only the latest version of value in this column are exposed. 'onlyReadLatest' can also be set at the column family level. However, the setting at this level takes precedence if 'onlyReadLatest' is set at both levels.`,
},
},
},
},
"family_id": {
Type: schema.TypeString,
Optional: true,
Description: `Identifier of the column family.`,
},
"type": {
Type: schema.TypeString,
Optional: true,
Description: `The type to convert the value in cells of this column family. The values are expected to be encoded using HBase Bytes.toBytes function when using the BINARY encoding value. Following BigQuery types are allowed (case-sensitive): "BYTES", "STRING", "INTEGER", "FLOAT", "BOOLEAN", "JSON". Default type is BYTES. This can be overridden for a specific column by listing that column in 'columns' and specifying a type for it.`,
},
"encoding": {
Type: schema.TypeString,
Optional: true,
Description: `The encoding of the values when the type is not STRING. Acceptable encoding values are: TEXT - indicates values are alphanumeric text strings. BINARY - indicates values are encoded using HBase Bytes.toBytes family of functions. This can be overridden for a specific column by listing that column in 'columns' and specifying an encoding for it.`,
},
"only_read_latest": {
Type: schema.TypeBool,
Optional: true,
Description: `If this is set only the latest version of value are exposed for all columns in this column family. This can be overridden for a specific column by listing that column in 'columns' and specifying a different setting for that column.`,
},
},
},
},
"ignore_unspecified_column_families": {
Type: schema.TypeBool,
Optional: true,
Description: `If field is true, then the column families that are not specified in columnFamilies list are not exposed in the table schema. Otherwise, they are read with BYTES type values. The default value is false.`,
},
"read_rowkey_as_string": {
Type: schema.TypeBool,
Optional: true,
Description: `If field is true, then the rowkey column families will be read and converted to string. Otherwise they are read with BYTES type values and users need to manually cast them with CAST if necessary. The default value is false.`,
},
"output_column_families_as_json": {
Type: schema.TypeBool,
Optional: true,
Description: `If field is true, then each column family will be read as a single JSON column. Otherwise they are read as a repeated cell structure containing timestamp/value tuples. The default value is false.`,
},
},
},
},
"parquet_options": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: `Additional properties to set if sourceFormat is set to PARQUET.`,
Elem: &schema.Resource{