This repository was archived by the owner on Jan 17, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathresource_redshift_datashare.go
More file actions
597 lines (529 loc) · 18.1 KB
/
resource_redshift_datashare.go
File metadata and controls
597 lines (529 loc) · 18.1 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
package redshift
import (
"database/sql"
"fmt"
"log"
"strings"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/lib/pq"
)
const (
dataShareNameAttr = "name"
dataShareOwnerAttr = "owner"
dataSharePublicAccessibleAttr = "publicly_accessible"
dataShareProducerAccountAttr = "producer_account"
dataShareProducerNamespaceAttr = "producer_namespace"
dataShareCreatedAttr = "created"
dataShareSchemasAttr = "schemas"
dataShareSchemaTablesAttr = "schema_tables"
)
func redshiftDatashare() *schema.Resource {
return &schema.Resource{
Description: `
Defines a Redshift datashare. Datashares allows a Redshift cluster (the "consumer") to
read data stored in another Redshift cluster (the "producer"). For more information, see
https://docs.aws.amazon.com/redshift/latest/dg/datashare-overview.html
The redshift_datashare resource should be defined on the producer cluster.
Note: Data sharing is only supported on certain Redshift instance families,
such as RA3.
`,
Exists: RedshiftResourceExistsFunc(resourceRedshiftDatashareExists),
Create: RedshiftResourceFunc(resourceRedshiftDatashareCreate),
Read: RedshiftResourceFunc(resourceRedshiftDatashareRead),
Update: RedshiftResourceFunc(resourceRedshiftDatashareUpdate),
Delete: RedshiftResourceFunc(resourceRedshiftDatashareDelete),
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
dataShareNameAttr: {
Type: schema.TypeString,
Description: "The name of the datashare.",
Required: true,
ForceNew: true,
StateFunc: func(val interface{}) string {
return strings.ToLower(val.(string))
},
},
dataShareOwnerAttr: {
Type: schema.TypeString,
Description: "The user who owns the datashare.",
Optional: true,
Computed: true,
StateFunc: func(val interface{}) string {
return strings.ToLower(val.(string))
},
},
dataSharePublicAccessibleAttr: {
Type: schema.TypeBool,
Description: "Specifies whether the datashare can be shared to clusters that are publicly accessible. Default is `false`.",
Optional: true,
Default: false,
},
dataShareProducerAccountAttr: {
Type: schema.TypeString,
Description: "The ID for the datashare producer account.",
Computed: true,
},
dataShareProducerNamespaceAttr: {
Type: schema.TypeString,
Description: "The unique cluster identifier for the datashare producer cluster.",
Computed: true,
},
dataShareCreatedAttr: {
Type: schema.TypeString,
Description: "The date when datashare was created",
Computed: true,
},
dataShareSchemasAttr: {
Type: schema.TypeSet,
Optional: true,
Description: "Defines which schemas are exposed to the data share.",
Set: schema.HashString,
Elem: &schema.Schema{
Type: schema.TypeString,
StateFunc: func(val interface{}) string {
return strings.ToLower(val.(string))
},
},
},
dataShareSchemaTablesAttr: {
Type: schema.TypeSet,
Optional: true,
Description: "Defines which schema tables are exposed to the data share.",
Set: schema.HashString,
Elem: &schema.Schema{
Type: schema.TypeString,
StateFunc: func(val interface{}) string {
return strings.ToLower(val.(string))
},
},
},
},
}
}
func resourceRedshiftDatashareExists(db *DBConnection, d *schema.ResourceData) (bool, error) {
var name string
query := "SELECT share_name FROM svv_datashares WHERE share_type='OUTBOUND' AND share_id=$1"
log.Printf("[DEBUG] check if datashare exists: %s\n", query)
err := db.QueryRow(query, d.Id()).Scan(&name)
switch {
case err == sql.ErrNoRows:
return false, nil
case err != nil:
return false, err
}
return true, nil
}
func resourceRedshiftDatashareCreate(db *DBConnection, d *schema.ResourceData) error {
tx, err := startTransaction(db.client, "")
if err != nil {
return err
}
defer deferredRollback(tx)
shareName := d.Get(dataShareNameAttr).(string)
query := fmt.Sprintf("CREATE DATASHARE %s SET PUBLICACCESSIBLE = %t", pq.QuoteIdentifier(shareName), d.Get(dataSharePublicAccessibleAttr).(bool))
log.Printf("[DEBUG] %s\n", query)
if _, err := tx.Exec(query); err != nil {
return err
}
var shareId string
query = "SELECT share_id FROM SVV_DATASHARES WHERE share_type = 'OUTBOUND' AND share_name = $1"
log.Printf("[DEBUG] %s, $1=%s\n", query, strings.ToLower(shareName))
if err := tx.QueryRow(query, strings.ToLower(shareName)).Scan(&shareId); err != nil {
return err
}
d.SetId(shareId)
if owner, ownerIsSet := d.GetOk(dataShareOwnerAttr); ownerIsSet {
query = fmt.Sprintf("ALTER DATASHARE %s OWNER TO %s", pq.QuoteIdentifier(strings.ToLower(shareName)), pq.QuoteIdentifier(strings.ToLower(owner.(string))))
log.Printf("[DEBUG] %s\n", query)
_, err = tx.Exec(query)
if err != nil {
return err
}
}
for _, schema := range d.Get(dataShareSchemasAttr).(*schema.Set).List() {
err = addSchemaToDatashare(tx, shareName, schema.(string))
if err != nil {
return err
}
}
var schemas []string
var tables []string
for _, schemaTable := range d.Get(dataShareSchemaTablesAttr).(*schema.Set).List() {
schemaName := strings.Split(schemaTable.(string), ".")[0]
appendIfTrue(contains(schemas, schemaName), schemaName, &schemas)
tableName := schemaTable.(string)
appendIfTrue(contains(tables, tableName), tableName, &tables)
}
err = addSchemaTablesToDatashare(tx, shareName, schemas, tables)
if err != nil {
return err
}
if err = tx.Commit(); err != nil {
return fmt.Errorf("could not commit transaction: %w", err)
}
return resourceRedshiftDatashareRead(db, d)
}
func addSchemaToDatashare(tx *sql.Tx, shareName string, schemaName string) error {
err := resourceRedshiftDatashareAddSchema(tx, shareName, schemaName)
if err != nil {
return err
}
err = resourceRedshiftDatashareAddAllTables(tx, shareName, schemaName)
if err != nil {
return err
}
err = resourceRedshiftDatashareAddAllFunctions(tx, shareName, schemaName)
return err
}
func addSchemaTablesToDatashare(tx *sql.Tx, shareName string, schemas []string, tables []string) error {
schemasString := strings.Join(schemas, ",")
tablesString := strings.Join(tables, ",")
err := resourceRedshiftDatashareAddTablesInSchema(tx, shareName, schemasString, tablesString)
return err
}
func removeSchemaTablesFromDatashare(tx *sql.Tx, shareName string, tables []string) error {
tablesString := strings.Join(tables, ",")
err := resourceRedshiftDatashareRemoveTablesInSchema(tx, shareName, tablesString)
return err
}
func resourceRedshiftDatashareAddSchema(tx *sql.Tx, shareName string, schemaName string) error {
query := fmt.Sprintf("ALTER DATASHARE %s ADD SCHEMA %s", pq.QuoteIdentifier(shareName), pq.QuoteIdentifier(schemaName))
log.Printf("[DEBUG] %s\n", query)
_, err := tx.Exec(query)
if err != nil {
// if the schema is already in the datashare we get a "duplicate schema" error code. This is fine.
if pqErr, ok := err.(*pq.Error); ok {
if string(pqErr.Code) == pqErrorCodeDuplicateSchema {
log.Printf("[WARN] Schema %s already exists in datashare %s\n", schemaName, shareName)
} else {
return err
}
} else {
return err
}
}
query = fmt.Sprintf("ALTER DATASHARE %s SET INCLUDENEW = TRUE FOR SCHEMA %s", pq.QuoteIdentifier(shareName), pq.QuoteIdentifier(schemaName))
log.Printf("[DEBUG] %s\n", query)
_, err = tx.Exec(query)
return err
}
func resourceRedshiftDatashareAddAllFunctions(tx *sql.Tx, shareName string, schemaName string) error {
query := fmt.Sprintf("ALTER DATASHARE %s ADD ALL FUNCTIONS IN SCHEMA %s", pq.QuoteIdentifier(shareName), pq.QuoteIdentifier(schemaName))
log.Printf("[DEBUG] %s", query)
_, err := tx.Exec(query)
return err
}
func resourceRedshiftDatashareAddAllTables(tx *sql.Tx, shareName string, schemaName string) error {
query := fmt.Sprintf("ALTER DATASHARE %s ADD ALL TABLES IN SCHEMA %s", pq.QuoteIdentifier(shareName), pq.QuoteIdentifier(schemaName))
log.Printf("[DEBUG] %s\n", query)
_, err := tx.Exec(query)
return err
}
func resourceRedshiftDatashareAddTablesInSchema(tx *sql.Tx, shareName string, schemas string, tables string) error {
query := fmt.Sprintf("ALTER DATASHARE %s ADD SCHEMA %s", pq.QuoteIdentifier(shareName), pq.QuoteIdentifier(schemas))
log.Printf("[DEBUG] %s\n", query)
_, err := tx.Exec(query)
if err != nil {
// if the schema is already in the datashare we get a "duplicate schema" error code. This is fine.
if pqErr, ok := err.(*pq.Error); ok {
if string(pqErr.Code) == pqErrorCodeDuplicateSchema {
log.Printf("[WARN] Schema %s already exists in datashare %s\n", schemas, shareName)
} else {
return err
}
} else {
return err
}
}
query = fmt.Sprintf("ALTER DATASHARE %s ADD TABLE %s", pq.QuoteIdentifier(shareName), pq.QuoteIdentifier(tables))
log.Printf("[DEBUG] %s\n", query)
_, err = tx.Exec(query)
return err
}
func resourceRedshiftDatashareRemoveTablesInSchema(tx *sql.Tx, shareName string, tables string) error {
query := fmt.Sprintf("ALTER DATASHARE %s REMOVE TABLE %s", pq.QuoteIdentifier(shareName), pq.QuoteIdentifier(tables))
log.Printf("[DEBUG] %s\n", query)
_, err := tx.Exec(query)
return err
}
func removeSchemaFromDatashare(tx *sql.Tx, shareName string, schemaName string) error {
err := resourceRedshiftDatashareRemoveAllFunctions(tx, shareName, schemaName)
if err != nil {
return err
}
err = resourceRedshiftDatashareRemoveAllTables(tx, shareName, schemaName)
if err != nil {
return err
}
err = resourceRedshiftDatashareRemoveSchema(tx, shareName, schemaName)
return err
}
func resourceRedshiftDatashareRemoveAllFunctions(tx *sql.Tx, shareName string, schemaName string) error {
query := fmt.Sprintf("ALTER DATASHARE %s REMOVE ALL FUNCTIONS IN SCHEMA %s", pq.QuoteIdentifier(shareName), pq.QuoteIdentifier(schemaName))
log.Printf("[DEBUG] %s\n", query)
_, err := tx.Exec(query)
return err
}
func resourceRedshiftDatashareRemoveAllTables(tx *sql.Tx, shareName string, schemaName string) error {
query := fmt.Sprintf("ALTER DATASHARE %s REMOVE ALL TABLES IN SCHEMA %s", pq.QuoteIdentifier(shareName), pq.QuoteIdentifier(schemaName))
log.Printf("[DEBUG] %s\n", query)
_, err := tx.Exec(query)
return err
}
func resourceRedshiftDatashareRemoveSchema(tx *sql.Tx, shareName string, schemaName string) error {
query := fmt.Sprintf("ALTER DATASHARE %s REMOVE SCHEMA %s", pq.QuoteIdentifier(shareName), pq.QuoteIdentifier(schemaName))
log.Printf("[DEBUG] %s\n", query)
_, err := tx.Exec(query)
if err != nil {
// if the schema is not already in the datashare we get a "datashare does not contain schema" error code. This is fine.
if pqErr, ok := err.(*pq.Error); ok {
if string(pqErr.Code) == pqErrorCodeInvalidSchemaName {
log.Printf("[WARN] Schema %s does not exist in datashare %s\n", schemaName, shareName)
} else {
return err
}
} else {
return err
}
}
return nil
}
func resourceRedshiftDatashareRead(db *DBConnection, d *schema.ResourceData) error {
var shareName, owner, producerAccount, producerNamespace, created string
var publicAccessible bool
tx, err := startTransaction(db.client, "")
if err != nil {
return err
}
defer deferredRollback(tx)
query := `
SELECT
trim(svv_datashares.share_name),
trim(pg_user.usename),
svv_datashares.is_publicaccessible,
TRIM(COALESCE(svv_datashares.producer_account, '')),
TRIM(COALESCE(svv_datashares.producer_namespace, '')),
REPLACE(TO_CHAR(svv_datashares.createdate, 'YYYY-MM-DD HH24:MI:SS'), ' ', 'T') || 'Z'
FROM svv_datashares
LEFT JOIN pg_user ON svv_datashares.share_owner = pg_user.usesysid
WHERE share_type = 'OUTBOUND'
AND share_id = $1`
log.Printf("[DEBUG] %s, $1=%s\n", query, d.Id())
err = tx.QueryRow(query, d.Id()).Scan(&shareName, &owner, &publicAccessible, &producerAccount, &producerNamespace, &created)
if err != nil {
return err
}
d.Set(dataShareNameAttr, shareName)
d.Set(dataShareOwnerAttr, owner)
d.Set(dataSharePublicAccessibleAttr, publicAccessible)
d.Set(dataShareProducerAccountAttr, producerAccount)
d.Set(dataShareProducerNamespaceAttr, producerNamespace)
d.Set(dataShareCreatedAttr, created)
if err = readDatashareSchemas(tx, shareName, d); err != nil {
return err
}
if err = readDatashareSchemaTables(tx, shareName, d); err != nil {
return err
}
if err = tx.Commit(); err != nil {
return err
}
return nil
}
func readDatashareSchemas(tx *sql.Tx, shareName string, d *schema.ResourceData) error {
query := `
SELECT
object_name
FROM svv_datashare_objects
WHERE share_type = 'OUTBOUND'
AND object_type = 'schema'
AND share_name = $1
`
log.Printf("[DEBUG] %s, $1=%s\n", query, shareName)
rows, err := tx.Query(query, shareName)
if err != nil {
return err
}
defer rows.Close()
schemas := schema.NewSet(schema.HashString, nil)
for rows.Next() {
var schemaName string
if err = rows.Scan(&schemaName); err != nil {
return err
}
schemas.Add(schemaName)
}
d.Set(dataShareSchemasAttr, schemas)
return nil
}
func readDatashareSchemaTables(tx *sql.Tx, shareName string, d *schema.ResourceData) error {
query := `
SELECT
object_name
FROM svv_datashare_objects
WHERE share_type = 'OUTBOUND'
AND object_type = 'table'
AND share_name = $1
`
log.Printf("[DEBUG] %s, $1=%s\n", query, shareName)
rows, err := tx.Query(query, shareName)
if err != nil {
return err
}
defer rows.Close()
schemaTables := schema.NewSet(schema.HashString, nil)
for rows.Next() {
var schemaTableName string
if err = rows.Scan(&schemaTableName); err != nil {
return err
}
schemaTables.Add(schemaTableName)
}
d.Set(dataShareSchemaTablesAttr, schemaTables)
return nil
}
func resourceRedshiftDatashareUpdate(db *DBConnection, d *schema.ResourceData) error {
tx, err := startTransaction(db.client, "")
if err != nil {
return err
}
defer deferredRollback(tx)
if err := setDatashareOwner(tx, d); err != nil {
return err
}
if err := setDatasharePubliclyAccessble(tx, d); err != nil {
return err
}
if err := setDatashareSchemas(tx, d); err != nil {
return err
}
if err := setDatashareTableSchemas(tx, d); err != nil {
return err
}
if err = tx.Commit(); err != nil {
return fmt.Errorf("could not commit transaction: %w", err)
}
return resourceRedshiftDatashareRead(db, d)
}
func setDatashareOwner(tx *sql.Tx, d *schema.ResourceData) error {
if !d.HasChange(dataShareOwnerAttr) {
return nil
}
shareName := d.Get(dataShareNameAttr).(string)
_, newRaw := d.GetChange(dataShareOwnerAttr)
newValue := newRaw.(string)
if newValue == "" {
newValue = "CURRENT_USER"
} else {
newValue = pq.QuoteIdentifier(newValue)
}
query := fmt.Sprintf("ALTER DATASHARE %s OWNER TO %s", pq.QuoteIdentifier(shareName), newValue)
log.Printf("[DEBUG] %s\n", query)
if _, err := tx.Exec(query); err != nil {
return fmt.Errorf("Error updating datashare OWNER :%w", err)
}
return nil
}
func setDatasharePubliclyAccessble(tx *sql.Tx, d *schema.ResourceData) error {
if !d.HasChange(dataSharePublicAccessibleAttr) {
return nil
}
shareName := d.Get(dataShareNameAttr).(string)
newValue := d.Get(dataSharePublicAccessibleAttr).(bool)
query := fmt.Sprintf("ALTER DATASHARE %s SET PUBLICACCESSIBLE %t", pq.QuoteIdentifier(shareName), newValue)
log.Printf("[DEBUG] %s\n", query)
if _, err := tx.Exec(query); err != nil {
return fmt.Errorf("Error updating datashare PUBLICACCESSBILE :%w", err)
}
return nil
}
func setDatashareSchemas(tx *sql.Tx, d *schema.ResourceData) error {
if !d.HasChange(dataShareSchemasAttr) {
return nil
}
before, after := d.GetChange(dataShareSchemasAttr)
if before == nil {
before = schema.NewSet(schema.HashString, nil)
}
if after == nil {
after = schema.NewSet(schema.HashString, nil)
}
add := after.(*schema.Set).Difference(before.(*schema.Set))
remove := before.(*schema.Set).Difference(after.(*schema.Set))
shareName := d.Get(dataShareNameAttr).(string)
for _, s := range add.List() {
if err := addSchemaToDatashare(tx, shareName, s.(string)); err != nil {
return err
}
}
for _, s := range remove.List() {
if err := removeSchemaFromDatashare(tx, shareName, s.(string)); err != nil {
return err
}
}
return nil
}
func setDatashareTableSchemas(tx *sql.Tx, d *schema.ResourceData) error {
if !d.HasChange(dataShareSchemaTablesAttr) {
return nil
}
before, after := d.GetChange(dataShareSchemaTablesAttr)
if before == nil {
before = schema.NewSet(schema.HashString, nil)
}
if after == nil {
after = schema.NewSet(schema.HashString, nil)
}
add := after.(*schema.Set).Difference(before.(*schema.Set))
remove := before.(*schema.Set).Difference(after.(*schema.Set))
shareName := d.Get(dataShareSchemaTablesAttr).(string)
var schemas []string
var tables []string
for _, schemaTable := range add.List() {
schemaName := strings.Split(schemaTable.(string), ".")[0]
appendIfTrue(contains(schemas, schemaName), schemaName, &schemas)
tableName := schemaTable.(string)
appendIfTrue(contains(tables, tableName), tableName, &tables)
}
err := addSchemaTablesToDatashare(tx, shareName, schemas, tables)
if err != nil {
return err
}
var tablesToBeRemoved []string
for _, schemaTable := range remove.List() {
tableName := schemaTable.(string)
appendIfTrue(contains(tablesToBeRemoved, tableName), tableName, &tablesToBeRemoved)
}
if err := removeSchemaTablesFromDatashare(tx, shareName, tablesToBeRemoved); err != nil {
return err
}
return nil
}
func resourceRedshiftDatashareDelete(db *DBConnection, d *schema.ResourceData) error {
tx, err := startTransaction(db.client, "")
if err != nil {
return err
}
defer deferredRollback(tx)
var shareName string
query := "SELECT share_name FROM svv_datashares WHERE share_type='OUTBOUND' AND share_id=$1"
if err := tx.QueryRow(query, d.Id()).Scan(&shareName); err != nil {
if err == sql.ErrNoRows {
log.Printf("[WARN] data share with id %s does not exist.\n", d.Id())
return nil
}
return err
}
query = fmt.Sprintf("DROP DATASHARE %s", pq.QuoteIdentifier(shareName))
log.Printf("[DEBUG] %s\n", query)
_, err = tx.Exec(query)
if err != nil {
return err
}
if err = tx.Commit(); err != nil {
return fmt.Errorf("could not commit transaction: %w", err)
}
return nil
}