-
Notifications
You must be signed in to change notification settings - Fork 426
/
Copy pathtable_constraint.go
418 lines (374 loc) · 13.3 KB
/
table_constraint.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
package resources
import (
"context"
"fmt"
"strings"
"github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/internal/provider"
"github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/helpers"
"github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk"
"github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/snowflake"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
)
// TODO [SNOW-867235]: refine this resource during redesign:
// - read (from the existing comment it seems that active warehouse is needed (it should be probably added to the resource as required)
// - drop (in tests it's not dropped correctly, probably also because missing warehouse)
// - do we need it?
// - not null cannot be set as a named constraint but it can be set by alter column statement - should it be added back here?
var tableConstraintSchema = map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
Description: "Name of constraint",
},
"type": {
Type: schema.TypeString,
Required: true,
Description: "Type of constraint, one of 'UNIQUE', 'PRIMARY KEY', or 'FOREIGN KEY'",
ForceNew: true,
ValidateFunc: validation.StringInSlice(sdk.AsStringList(sdk.AllColumnConstraintTypes), false),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return strings.EqualFold(old, new)
},
StateFunc: func(val any) string {
return strings.ToUpper(val.(string))
},
},
"table_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: `Identifier for table to create constraint on. Format must follow: "\"<db_name>\".\"<schema_name>\".\"<table_name>\"" or "<db_name>.<schema_name>.<table_name>" (snowflake_table.my_table.id)`,
},
"columns": {
Type: schema.TypeList,
MinItems: 1,
Elem: &schema.Schema{
Type: schema.TypeString,
},
ForceNew: true,
Required: true,
Description: "Columns to use in constraint key",
},
"enforced": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Default: false,
Description: "Whether the constraint is enforced",
},
"deferrable": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Default: true,
Description: "Whether the constraint is deferrable",
},
"initially": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "DEFERRED",
Description: "Whether the constraint is initially deferred or immediate",
ValidateFunc: validation.StringInSlice([]string{"DEFERRED", "IMMEDIATE"}, true),
},
"enable": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Default: true,
Description: "Specifies whether the constraint is enabled or disabled. These properties are provided for compatibility with Oracle.",
},
"validate": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Default: false,
Description: "Specifies whether to validate existing data on the table when a constraint is created. Only used in conjunction with the ENABLE property.",
},
"rely": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Default: true,
Description: "Specifies whether a constraint in NOVALIDATE mode is taken into account during query rewrite.",
},
"comment": {
Type: schema.TypeString,
Optional: true,
Description: "Comment for the table constraint",
Deprecated: "Not used. Will be removed.",
},
"foreign_key_properties": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
MaxItems: 1,
Description: "Additional properties when type is set to foreign key. Not applicable for primary/unique keys",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"references": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
MaxItems: 1,
Description: "The table and columns that the foreign key references. Not applicable for primary/unique keys",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"table_id": {
Type: schema.TypeString,
Required: true,
Description: "Name of constraint",
},
"columns": {
Type: schema.TypeList,
MinItems: 1,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Required: true,
Description: "Columns to use in foreign key reference",
},
},
},
},
"match": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "FULL",
ValidateFunc: validation.StringInSlice(sdk.AsStringList(sdk.AllMatchTypes), true),
Description: "The match type for the foreign key. Not applicable for primary/unique keys",
},
"on_update": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "NO ACTION",
ValidateFunc: validation.StringInSlice(sdk.AsStringList(sdk.AllForeignKeyActions), true),
Description: "Specifies the action performed when the primary/unique key for the foreign key is updated. Not applicable for primary/unique keys",
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return strings.EqualFold(old, new)
},
StateFunc: func(val any) string {
return strings.ToUpper(val.(string))
},
},
"on_delete": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "NO ACTION",
ValidateFunc: validation.StringInSlice(sdk.AsStringList(sdk.AllForeignKeyActions), true),
Description: "Specifies the action performed when the primary/unique key for the foreign key is deleted. Not applicable for primary/unique keys",
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return strings.EqualFold(old, new)
},
StateFunc: func(val any) string {
return strings.ToUpper(val.(string))
},
},
},
},
},
}
func TableConstraint() *schema.Resource {
return &schema.Resource{
Create: CreateTableConstraint,
Read: ReadTableConstraint,
Update: UpdateTableConstraint,
Delete: DeleteTableConstraint,
Schema: tableConstraintSchema,
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},
}
}
type tableConstraintID struct {
name string
constraintType string
tableID string
}
func (v *tableConstraintID) String() string {
return fmt.Sprintf("%s❄️%s❄️%s", v.name, v.constraintType, v.tableID)
}
func (v *tableConstraintID) parse(s string) {
parts := strings.Split(s, "❄️")
v.name = parts[0]
v.constraintType = parts[1]
v.tableID = parts[2]
}
func getTableIdentifier(s string) (*sdk.SchemaObjectIdentifier, error) {
var objectIdentifier sdk.ObjectIdentifier
var err error
// TODO [SNOW-999049]: Fallback for old implementations using table.id instead of table.qualified_name - probably will be removed later.
if strings.Contains(s, "|") {
objectIdentifier = helpers.DecodeSnowflakeID(s)
} else {
objectIdentifier, err = helpers.DecodeSnowflakeParameterID(s)
}
if err != nil {
return nil, fmt.Errorf("table id is incorrect: %s, err: %w", objectIdentifier, err)
}
tableIdentifier, ok := objectIdentifier.(sdk.SchemaObjectIdentifier)
if !ok {
return nil, fmt.Errorf("table id is incorrect: %s", objectIdentifier)
}
return &tableIdentifier, nil
}
// CreateTableConstraint implements schema.CreateFunc.
func CreateTableConstraint(d *schema.ResourceData, meta interface{}) error {
client := meta.(*provider.Context).Client
ctx := context.Background()
name := d.Get("name").(string)
cType := d.Get("type").(string)
tableID := d.Get("table_id").(string)
tableIdentifier, err := getTableIdentifier(tableID)
if err != nil {
return err
}
constraintType, err := sdk.ToColumnConstraintType(cType)
if err != nil {
return err
}
constraintRequest := sdk.NewOutOfLineConstraintRequest(constraintType).WithName(&name)
cc := d.Get("columns").([]interface{})
columns := make([]string, 0, len(cc))
for _, c := range cc {
columns = append(columns, c.(string))
}
constraintRequest.WithColumns(snowflake.QuoteStringList(columns))
if v, ok := d.GetOk("enforced"); ok {
constraintRequest.WithEnforced(sdk.Bool(v.(bool)))
}
if v, ok := d.GetOk("deferrable"); ok {
constraintRequest.WithDeferrable(sdk.Bool(v.(bool)))
}
if v, ok := d.GetOk("initially"); ok {
if v.(string) == "DEFERRED" {
constraintRequest.WithInitiallyDeferred(sdk.Bool(true))
} else {
constraintRequest.WithInitiallyImmediate(sdk.Bool(true))
}
}
if v, ok := d.GetOk("enable"); ok {
constraintRequest.WithEnable(sdk.Bool(v.(bool)))
}
if v, ok := d.GetOk("validate"); ok {
constraintRequest.WithValidate(sdk.Bool(v.(bool)))
}
if v, ok := d.GetOk("rely"); ok {
constraintRequest.WithRely(sdk.Bool(v.(bool)))
}
// set foreign key specific settings
if v, ok := d.GetOk("foreign_key_properties"); ok {
foreignKeyProperties := v.([]interface{})[0].(map[string]interface{})
references := foreignKeyProperties["references"].([]interface{})[0].(map[string]interface{})
fkTableID := references["table_id"].(string)
fkId, err := helpers.DecodeSnowflakeParameterID(fkTableID)
if err != nil {
return fmt.Errorf("table id is incorrect: %s, err: %w", fkTableID, err)
}
referencedTableIdentifier, ok := fkId.(sdk.SchemaObjectIdentifier)
if !ok {
return fmt.Errorf("table id is incorrect: %s", fkId)
}
cols := references["columns"].([]interface{})
var fkColumns []string
for _, c := range cols {
fkColumns = append(fkColumns, c.(string))
}
foreignKeyRequest := sdk.NewOutOfLineForeignKeyRequest(referencedTableIdentifier, snowflake.QuoteStringList(fkColumns))
matchType, err := sdk.ToMatchType(foreignKeyProperties["match"].(string))
if err != nil {
return err
}
foreignKeyRequest.WithMatch(&matchType)
onUpdate, err := sdk.ToForeignKeyAction(foreignKeyProperties["on_update"].(string))
if err != nil {
return err
}
onDelete, err := sdk.ToForeignKeyAction(foreignKeyProperties["on_delete"].(string))
if err != nil {
return err
}
foreignKeyRequest.WithOn(sdk.NewForeignKeyOnAction().
WithOnDelete(&onDelete).
WithOnUpdate(&onUpdate),
)
constraintRequest.WithForeignKey(foreignKeyRequest)
}
alterStatement := sdk.NewAlterTableRequest(*tableIdentifier).WithConstraintAction(sdk.NewTableConstraintActionRequest().WithAdd(constraintRequest))
err = client.Tables.Alter(ctx, alterStatement)
if err != nil {
return fmt.Errorf("error creating table constraint %v err = %w", name, err)
}
tc := tableConstraintID{
name,
cType,
tableID,
}
d.SetId(tc.String())
return ReadTableConstraint(d, meta)
}
// ReadTableConstraint implements schema.ReadFunc.
func ReadTableConstraint(_ *schema.ResourceData, _ interface{}) error {
// commenting this out since it requires an active warehouse to be set which may not be intuitive.
// also it takes a while for the database to reflect changes. Would likely need to add a validation
// step like in tag association. People don't like waiting 40 minutes for Terraform to run.
/*providerContext := meta.(*provider.Context)
tc := tableConstraintID{}
tc.parse(d.Id())
databaseName, schemaName, tableName := snowflakeValidation.ParseFullyQualifiedObjectID(tc.tableID)
// just need to check to make sure it exists
_, err := snowflake.ShowTableConstraint(tc.name, databaseName, schemaName, tableName, db)
if err != nil {
return fmt.Errorf(fmt.Sprintf("error reading table constraint %v", tc.String()))
}*/
return nil
}
// UpdateTableConstraint implements schema.UpdateFunc.
func UpdateTableConstraint(d *schema.ResourceData, meta interface{}) error {
client := meta.(*provider.Context).Client
ctx := context.Background()
tc := tableConstraintID{}
tc.parse(d.Id())
tableIdentifier, err := getTableIdentifier(tc.tableID)
if err != nil {
return err
}
if d.HasChange("name") {
_, n := d.GetChange("name")
constraintRequest := sdk.NewTableConstraintRenameActionRequest().WithOldName(tc.name).WithNewName(n.(string))
alterStatement := sdk.NewAlterTableRequest(*tableIdentifier).WithConstraintAction(sdk.NewTableConstraintActionRequest().WithRename(constraintRequest))
err = client.Tables.Alter(ctx, alterStatement)
if err != nil {
return fmt.Errorf("error renaming table constraint %s err = %w", tc.name, err)
}
}
return ReadTableConstraint(d, meta)
}
// DeleteTableConstraint implements schema.DeleteFunc.
func DeleteTableConstraint(d *schema.ResourceData, meta interface{}) error {
client := meta.(*provider.Context).Client
ctx := context.Background()
tc := tableConstraintID{}
tc.parse(d.Id())
tableIdentifier, err := getTableIdentifier(tc.tableID)
if err != nil {
return err
}
dropRequest := sdk.NewTableConstraintDropActionRequest().WithConstraintName(&tc.name)
alterStatement := sdk.NewAlterTableRequest(*tableIdentifier).WithConstraintAction(sdk.NewTableConstraintActionRequest().WithDrop(dropRequest))
err = client.Tables.Alter(ctx, alterStatement)
if err != nil {
// if the table constraint does not exist, then remove from state file
if strings.Contains(err.Error(), "does not exist") {
d.SetId("")
return nil
}
return fmt.Errorf("error dropping table constraint %v err = %w", tc.name, err)
}
d.SetId("")
return nil
}