-
Notifications
You must be signed in to change notification settings - Fork 7
/
datasource_materialized_view.go
102 lines (87 loc) · 2.64 KB
/
datasource_materialized_view.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
package datasources
import (
"context"
"database/sql"
"errors"
"log"
"github.com/MaterializeInc/terraform-provider-materialize/pkg/materialize"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/jmoiron/sqlx"
)
func MaterializedView() *schema.Resource {
return &schema.Resource{
ReadContext: materializedViewRead,
Schema: map[string]*schema.Schema{
"database_name": {
Type: schema.TypeString,
Optional: true,
Description: "Limit materialized views to a specific database",
},
"schema_name": {
Type: schema.TypeString,
Optional: true,
Description: "Limit materialized views to a specific schema within a specific database",
RequiredWith: []string{"database_name"},
},
"materialized_views": {
Type: schema.TypeList,
Computed: true,
Description: "The materialized views in the account",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"schema_name": {
Type: schema.TypeString,
Computed: true,
},
"database_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func materializedViewRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
var diags diag.Diagnostics
conn := meta.(*sqlx.DB)
schemaName := d.Get("schema_name").(string)
databaseName := d.Get("database_name").(string)
q := materialize.ReadMaterializedViewDatasource(databaseName, schemaName)
rows, err := conn.Query(q)
if errors.Is(err, sql.ErrNoRows) {
log.Printf("[DEBUG] no materialized views found in account")
d.SetId("")
return diag.FromErr(err)
} else if err != nil {
log.Println("[DEBUG] failed to list materialized views")
d.SetId("")
return diag.FromErr(err)
}
materizliedViewFormats := []map[string]interface{}{}
for rows.Next() {
var id, name, schema_name, database_name string
rows.Scan(&id, &name, &schema_name, &database_name)
materizliedViewMap := map[string]interface{}{}
materizliedViewMap["id"] = id
materizliedViewMap["name"] = name
materizliedViewMap["schema_name"] = schema_name
materizliedViewMap["database_name"] = database_name
materizliedViewFormats = append(materizliedViewFormats, materizliedViewMap)
}
if err := d.Set("materialized_views", materizliedViewFormats); err != nil {
return diag.FromErr(err)
}
SetId("materialized_views", databaseName, schemaName, d)
return diags
}