forked from GoogleCloudPlatform/magic-modules
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresource_bigquery_table.go
1724 lines (1506 loc) · 57.3 KB
/
resource_bigquery_table.go
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 google
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"regexp"
"sort"
"strconv"
"strings"
"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"
"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{}) bool) (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)
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
}
for subKey := range unionOfKeys {
eq := compareMapKeyVal(subKey, objectA, objectB)
if !eq {
valA, ok1 := objectA[subKey]
valB, ok2 := objectB[subKey]
if !ok1 || !ok2 {
return false, nil
}
eq, err := jsonCompareWithMapKeyOverride(subKey, valA, valB, compareMapKeyVal)
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
}
func bigQueryTableMapKeyOverride(key string, objectA, objectB map[string]interface{}) 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))
}
// otherwise rely on default behavior
return false
}
// Compare the JSON strings are equal
func bigQueryTableSchemaDiffSuppress(name, old, new string, _ *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)
if err != nil {
log.Printf("[DEBUG] %v", err)
log.Printf("[DEBUG] Error comparing JSON: %v, %v", old, new)
}
return eq
}
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
}
// Compares two existing schema implementations and decides if
// it is changeable.. pairs with a force new on not changeable
func resourceBigQueryTableSchemaIsChangeable(old, new interface{}) (bool, error) {
switch old.(type) {
case []interface{}:
arrayOld := old.([]interface{})
arrayNew, ok := new.([]interface{})
if !ok {
// if not both arrays not changeable
return false, nil
}
if len(arrayOld) > len(arrayNew) {
// if not growing 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 {
// all old keys should be represented in the new config
if _, ok := mapNew[key]; !ok {
return false, nil
}
if isChangable, err :=
resourceBigQueryTableSchemaIsChangeable(mapOld[key], mapNew[key]); err != nil || !isChangable {
return false, err
}
}
return true, 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
}
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)
// 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 TerraformResourceDiff) 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)
}
isChangeable, err := resourceBigQueryTableSchemaIsChangeable(old, new)
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 {
return resourceBigQueryTableSchemaCustomizeDiffFunc(d)
}
func resourceBigQueryTable() *schema.Resource {
return &schema.Resource{
Create: resourceBigQueryTableCreate,
Read: resourceBigQueryTableRead,
Delete: resourceBigQueryTableDelete,
Update: resourceBigQueryTableUpdate,
Importer: &schema.ResourceImporter{
State: resourceBigQueryTableImport,
},
CustomizeDiff: customdiff.All(
resourceBigQueryTableSchemaCustomizeDiff,
),
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,
Required: true,
Description: `The data format. Supported values are: "CSV", "GOOGLE_SHEETS", "NEWLINE_DELIMITED_JSON", "AVRO", "PARQUET", "ORC" and "DATASTORE_BACKUP". To use "GOOGLE_SHEETS" the scopes must include "googleapis.com/auth/drive.readonly".`,
ValidateFunc: validation.StringInSlice([]string{
"CSV", "GOOGLE_SHEETS", "NEWLINE_DELIMITED_JSON", "AVRO", "DATASTORE_BACKUP", "PARQUET", "ORC", "BIGTABLE",
}, 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},
},
// 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, ORC and Parquet formats.
"schema": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringIsJSON,
StateFunc: func(v interface{}) string {
json, _ := structure.NormalizeJsonString(v)
return json
},
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.`,
},
},
},
},
// GoogleSheetsOptions: [Optional] Additional options if sourceFormat is set to GOOGLE_SHEETS.
"google_sheets_options": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: `Additional options if source_format is set to "GOOGLE_SHEETS".`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
// Range: [Optional] Range of a sheet to query from. Only used when non-empty.
// Typical format: !:
"range": {
Type: schema.TypeString,
Optional: true,
Description: `Range of a sheet to query from. Only used when non-empty. At least one of range or skip_leading_rows must be set. Typical format: "sheet_name!top_left_cell_id:bottom_right_cell_id" For example: "sheet1!A1:B20"`,
AtLeastOneOf: []string{
"external_data_configuration.0.google_sheets_options.0.skip_leading_rows",
"external_data_configuration.0.google_sheets_options.0.range",
},
},
// SkipLeadingRows: [Optional] The number of rows at the top
// of the sheet that BigQuery will skip when reading the data.
"skip_leading_rows": {
Type: schema.TypeInt,
Optional: true,
Description: `The number of rows at the top of the sheet that BigQuery will skip when reading the data. At least one of range or skip_leading_rows must be set.`,
AtLeastOneOf: []string{
"external_data_configuration.0.google_sheets_options.0.skip_leading_rows",
"external_data_configuration.0.google_sheets_options.0.range",
},
},
},
},
},
// HivePartitioningOptions:: [Optional] Options for configuring hive partitioning detect.
"hive_partitioning_options": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: `When set, configures hive partitioning support. 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.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
// Mode: [Optional] [Experimental] When set, what mode of hive partitioning to use when reading data.
// Two modes are supported.
//* AUTO: automatically infer partition key name(s) and type(s).
//* STRINGS: automatically infer partition key name(s).
"mode": {
Type: schema.TypeString,
Optional: true,
Description: `When set, what mode of hive partitioning to use when reading data.`,
},
// RequirePartitionFilter: [Optional] If set to true, queries over this table
// require a partition filter that can be used for partition elimination to be
// specified.
"require_partition_filter": {
Type: schema.TypeBool,
Optional: true,
Description: `If set to true, queries over this table require a partition filter that can be used for partition elimination to be specified.`,
},
// SourceUriPrefix: [Optional] [Experimental] When hive partition detection is requested, a common for all source uris must be required.
// The prefix must end immediately before the partition key encoding begins.
"source_uri_prefix": {
Type: schema.TypeString,
Optional: true,
Description: `When hive partition detection is requested, a common for all source uris must be required. The prefix must end immediately before the partition key encoding begins.`,
},
},
},
},
// IgnoreUnknownValues: [Optional] Indicates if BigQuery should
// allow extra values that are not represented in the table schema.
// If true, the extra values are ignored. If false, records with
// extra columns are treated as bad records, and if there are too
// many bad records, an invalid error is returned in the job result.
// The default value is false.
"ignore_unknown_values": {
Type: schema.TypeBool,
Optional: true,
Description: `Indicates if BigQuery should allow extra values that are not represented in the table schema. If true, the extra values are ignored. If false, records with extra columns are treated as bad records, and if there are too many bad records, an invalid error is returned in the job result. The default value is false.`,
},
// MaxBadRecords: [Optional] The maximum number of bad records that
// BigQuery can ignore when reading data.
"max_bad_records": {
Type: schema.TypeInt,
Optional: true,
Description: `The maximum number of bad records that BigQuery can ignore when reading data.`,
},
// ConnectionId: [Optional] The connection specifying the credentials
// to be used to read external storage, such as Azure Blob,
// Cloud Storage, or S3. The connectionId can have the form
// "{{project}}.{{location}}.{{connection_id}}" or
// "projects/{{project}}/locations/{{location}}/connections/{{connection_id}}".
"connection_id": {
Type: schema.TypeString,
Optional: true,
Description: `The connection specifying the credentials to be used to read external storage, such as Azure Blob, Cloud Storage, or S3. The connectionId can have the form "{{project}}.{{location}}.{{connection_id}}" or "projects/{{project}}/locations/{{location}}/connections/{{connection_id}}".`,
},
},
},
},
// FriendlyName: [Optional] A descriptive name for this table.
"friendly_name": {
Type: schema.TypeString,
Optional: true,
Description: `A descriptive name for the table.`,
},
// Labels: [Experimental] The labels associated with this table. You can
// use these to organize and group your tables. Label keys and values
// can be no longer than 63 characters, can only contain lowercase
// letters, numeric characters, underscores and dashes. International
// characters are allowed. Label values are optional. Label keys must
// start with a letter and each label in the list must have a different
// key.
"labels": {
Type: schema.TypeMap,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Description: `A mapping of labels to assign to the resource.`,
},
// Schema: [Optional] Describes the schema of this table.
"schema": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringIsJSON,
StateFunc: func(v interface{}) string {
json, _ := structure.NormalizeJsonString(v)
return json
},
DiffSuppressFunc: bigQueryTableSchemaDiffSuppress,
Description: `A JSON schema for the table.`,
},
// View: [Optional] If specified, configures this table as a view.
"view": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: `If specified, configures this table as a view.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
// Query: [Required] A query that BigQuery executes when the view is
// referenced.
"query": {
Type: schema.TypeString,
Required: true,
Description: `A query that BigQuery executes when the view is referenced.`,
},
// UseLegacySQL: [Optional] Specifies whether to use BigQuery's
// legacy SQL for this view. The default value is true. If set to
// false, the view will use BigQuery's standard SQL:
"use_legacy_sql": {
Type: schema.TypeBool,
Optional: true,
Default: true,
Description: `Specifies whether to use BigQuery's legacy SQL for this view. The default value is true. If set to false, the view will use BigQuery's standard SQL`,
},
},
},
},
// Materialized View: [Optional] If specified, configures this table as a materialized view.
"materialized_view": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: `If specified, configures this table as a materialized view.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
// EnableRefresh: [Optional] Enable automatic refresh of
// the materialized view when the base table is updated. The default
// value is "true".
"enable_refresh": {
Type: schema.TypeBool,
Optional: true,
Default: true,
Description: `Specifies if BigQuery should automatically refresh materialized view when the base table is updated. The default is true.`,
},
// RefreshIntervalMs: [Optional] The maximum frequency
// at which this materialized view will be refreshed. The default value
// is 1800000 (30 minutes).
"refresh_interval_ms": {
Type: schema.TypeInt,
Default: 1800000,
Optional: true,
Description: `Specifies maximum frequency at which this materialized view will be refreshed. The default is 1800000`,
},
// Query: [Required] A query whose result is persisted
"query": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: `A query whose result is persisted.`,
},
},
},
},
// TimePartitioning: [Experimental] If specified, configures time-based
// partitioning for this table.
"time_partitioning": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: `If specified, configures time-based partitioning for this table.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
// ExpirationMs: [Optional] Number of milliseconds for which to keep the
// storage for a partition.
"expiration_ms": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Description: `Number of milliseconds for which to keep the storage for a partition.`,
},
// Type: [Required] The supported types are DAY, HOUR, MONTH, and YEAR, which will generate
// one partition per day, hour, month, and year, respectively.
"type": {
Type: schema.TypeString,
Required: true,
Description: `The supported types are DAY, HOUR, MONTH, and YEAR, which will generate one partition per day, hour, month, and year, respectively.`,
ValidateFunc: validation.StringInSlice([]string{"DAY", "HOUR", "MONTH", "YEAR"}, false),
},
// Field: [Optional] The field used to determine how to create a time-based
// partition. If time-based partitioning is enabled without this value, the
// table is partitioned based on the load time.
"field": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: `The field used to determine how to create a time-based partition. If time-based partitioning is enabled without this value, the table is partitioned based on the load time.`,
},
// RequirePartitionFilter: [Optional] If set to true, queries over this table
// require a partition filter that can be used for partition elimination to be
// specified.
"require_partition_filter": {
Type: schema.TypeBool,
Optional: true,
Description: `If set to true, queries over this table require a partition filter that can be used for partition elimination to be specified.`,
},
},
},
},
// RangePartitioning: [Optional] If specified, configures range-based
// partitioning for this table.
"range_partitioning": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: `If specified, configures range-based partitioning for this table.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
// Field: [Required] The field used to determine how to create a range-based
// partition.
"field": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: `The field used to determine how to create a range-based partition.`,
},
// Range: [Required] Information required to partition based on ranges.
"range": {
Type: schema.TypeList,
Required: true,
MaxItems: 1,
Description: `Information required to partition based on ranges. Structure is documented below.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
// Start: [Required] Start of the range partitioning, inclusive.
"start": {
Type: schema.TypeInt,
Required: true,
Description: `Start of the range partitioning, inclusive.`,
},
// End: [Required] End of the range partitioning, exclusive.
"end": {
Type: schema.TypeInt,
Required: true,
Description: `End of the range partitioning, exclusive.`,
},
// Interval: [Required] The width of each range within the partition.
"interval": {
Type: schema.TypeInt,
Required: true,
Description: `The width of each range within the partition.`,
},
},
},
},
},
},
},
// Clustering: [Optional] Specifies column names to use for data clustering. Up to four
// top-level columns are allowed, and should be specified in descending priority order.
"clustering": {
Type: schema.TypeList,
Optional: true,
MaxItems: 4,
Description: `Specifies column names to use for data clustering. Up to four top-level columns are allowed, and should be specified in descending priority order.`,
Elem: &schema.Schema{Type: schema.TypeString},
},
"encryption_configuration": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
MaxItems: 1,
Description: `Specifies how the table should be encrypted. If left blank, the table will be encrypted with a Google-managed key; that process is transparent to the user.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"kms_key_name": {
Type: schema.TypeString,
Required: true,
Description: `The self link or full name of a key which should be used to encrypt this table. Note that the default bigquery service account will need to have encrypt/decrypt permissions on this key - you may want to see the google_bigquery_default_service_account datasource and the google_kms_crypto_key_iam_binding resource.`,
},
"kms_key_version": {
Type: schema.TypeString,
Computed: true,
Description: `The self link or full name of the kms key version used to encrypt this table.`,
},
},
},
},
// CreationTime: [Output-only] The time when this table was created, in
// milliseconds since the epoch.
"creation_time": {
Type: schema.TypeInt,
Computed: true,
Description: `The time when this table was created, in milliseconds since the epoch.`,
},
// Etag: [Output-only] A hash of this resource.
"etag": {
Type: schema.TypeString,
Computed: true,
Description: `A hash of the resource.`,
},
// LastModifiedTime: [Output-only] The time when this table was last
// modified, in milliseconds since the epoch.
"last_modified_time": {
Type: schema.TypeInt,
Computed: true,
Description: `The time when this table was last modified, in milliseconds since the epoch.`,
},
// Location: [Output-only] The geographic location where the table
// resides. This value is inherited from the dataset.
"location": {
Type: schema.TypeString,
Computed: true,
Description: `The geographic location where the table resides. This value is inherited from the dataset.`,
},
// NumBytes: [Output-only] The size of this table in bytes, excluding
// any data in the streaming buffer.
"num_bytes": {
Type: schema.TypeInt,
Computed: true,
Description: `The geographic location where the table resides. This value is inherited from the dataset.`,
},
// NumLongTermBytes: [Output-only] The number of bytes in the table that
// are considered "long-term storage".
"num_long_term_bytes": {
Type: schema.TypeInt,
Computed: true,
Description: `The number of bytes in the table that are considered "long-term storage".`,
},
// NumRows: [Output-only] The number of rows of data in this table,
// excluding any data in the streaming buffer.
"num_rows": {
Type: schema.TypeInt,
Computed: true,
Description: `The number of rows of data in this table, excluding any data in the streaming buffer.`,
},
// SelfLink: [Output-only] A URL that can be used to access this
// resource again.
"self_link": {
Type: schema.TypeString,
Computed: true,
Description: `The URI of the created resource.`,
},
// Type: [Output-only] Describes the table type. The following values
// are supported: TABLE: A normal BigQuery table. VIEW: A virtual table
// defined by a SQL query. EXTERNAL: A table that references data stored
// in an external storage system, such as Google Cloud Storage. The
// default value is TABLE.
"type": {
Type: schema.TypeString,
Computed: true,
Description: `Describes the table type.`,
},
"deletion_protection": {
Type: schema.TypeBool,
Optional: true,
Default: true,
Description: `Whether or not to allow Terraform to destroy the instance. Unless this field is set to false in Terraform state, a terraform destroy or terraform apply that would delete the instance will fail.`,
},
},
UseJSONNumber: true,
}
}
func resourceTable(d *schema.ResourceData, meta interface{}) (*bigquery.Table, error) {
config := meta.(*Config)
project, err := getProject(d, config)
if err != nil {
return nil, err
}
table := &bigquery.Table{
TableReference: &bigquery.TableReference{
DatasetId: d.Get("dataset_id").(string),
TableId: d.Get("table_id").(string),
ProjectId: project,
},
}
if v, ok := d.GetOk("view"); ok {
table.View = expandView(v)
}
if v, ok := d.GetOk("materialized_view"); ok {
table.MaterializedView = expandMaterializedView(v)
}
if v, ok := d.GetOk("description"); ok {
table.Description = v.(string)
}
if v, ok := d.GetOk("expiration_time"); ok {
table.ExpirationTime = int64(v.(int))
}
if v, ok := d.GetOk("external_data_configuration"); ok {
externalDataConfiguration, err := expandExternalDataConfiguration(v)
if err != nil {
return nil, err
}
table.ExternalDataConfiguration = externalDataConfiguration
}
if v, ok := d.GetOk("friendly_name"); ok {
table.FriendlyName = v.(string)
}
if v, ok := d.GetOk("encryption_configuration.0.kms_key_name"); ok {
table.EncryptionConfiguration = &bigquery.EncryptionConfiguration{
KmsKeyName: v.(string),
}
}
if v, ok := d.GetOk("labels"); ok {
labels := map[string]string{}
for k, v := range v.(map[string]interface{}) {
labels[k] = v.(string)
}
table.Labels = labels