forked from hashicorp/terraform-provider-google
-
Notifications
You must be signed in to change notification settings - Fork 1
/
resource_spanner_database.go
244 lines (203 loc) · 6.46 KB
/
resource_spanner_database.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
package google
import (
"fmt"
"log"
"net/http"
"regexp"
"strings"
"github.com/hashicorp/terraform/helper/schema"
"google.golang.org/api/googleapi"
"google.golang.org/api/spanner/v1"
)
func resourceSpannerDatabase() *schema.Resource {
return &schema.Resource{
Create: resourceSpannerDatabaseCreate,
Read: resourceSpannerDatabaseRead,
Delete: resourceSpannerDatabaseDelete,
Importer: &schema.ResourceImporter{
State: resourceSpannerDatabaseImportState,
},
Schema: map[string]*schema.Schema{
"instance": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
value := v.(string)
if len(value) < 2 && len(value) > 30 {
errors = append(errors, fmt.Errorf(
"%q must be between 2 and 30 characters in length", k))
}
if !regexp.MustCompile("^[a-z0-9-]+$").MatchString(value) {
errors = append(errors, fmt.Errorf(
"%q can only contain lowercase letters, numbers and hyphens", k))
}
if !regexp.MustCompile("^[a-z]").MatchString(value) {
errors = append(errors, fmt.Errorf(
"%q must start with a letter", k))
}
if !regexp.MustCompile("[a-z0-9]$").MatchString(value) {
errors = append(errors, fmt.Errorf(
"%q must end with a number or a letter", k))
}
return
},
},
"project": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ddl": &schema.Schema{
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"state": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceSpannerDatabaseCreate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
id, err := buildSpannerDatabaseId(d, config)
if err != nil {
return err
}
cdr := &spanner.CreateDatabaseRequest{}
cdr.CreateStatement = fmt.Sprintf("CREATE DATABASE `%s`", id.Database)
if v, ok := d.GetOk("ddl"); ok {
cdr.ExtraStatements = convertStringArr(v.([]interface{}))
}
op, err := config.clientSpanner.Projects.Instances.Databases.Create(
id.parentInstanceUri(), cdr).Do()
if err != nil {
if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == http.StatusConflict {
return fmt.Errorf("Error, A database with name %s already exists in this instance", id.Database)
}
return fmt.Errorf("Error, failed to create database %s: %s", id.Database, err)
}
d.SetId(id.terraformId())
// Wait until it's created
timeoutMins := int(d.Timeout(schema.TimeoutCreate).Minutes())
waitErr := spannerDatabaseOperationWait(config, op, "Creating Spanner database", timeoutMins)
if waitErr != nil {
// The resource didn't actually create
d.SetId("")
return waitErr
}
log.Printf("[INFO] Spanner database %s has been created", id.terraformId())
return resourceSpannerDatabaseRead(d, meta)
}
func resourceSpannerDatabaseRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
id, err := buildSpannerDatabaseId(d, config)
if err != nil {
return err
}
db, err := config.clientSpanner.Projects.Instances.Databases.Get(
id.databaseUri()).Do()
if err != nil {
return handleNotFoundError(err, d, fmt.Sprintf("Spanner database %q", id.databaseUri()))
}
d.Set("state", db.State)
return nil
}
func resourceSpannerDatabaseDelete(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
id, err := buildSpannerDatabaseId(d, config)
if err != nil {
return err
}
_, err = config.clientSpanner.Projects.Instances.Databases.DropDatabase(
id.databaseUri()).Do()
if err != nil {
return fmt.Errorf("Error, failed to delete Spanner Database %s: %s", id.databaseUri(), err)
}
d.SetId("")
return nil
}
func resourceSpannerDatabaseImportState(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
config := meta.(*Config)
id, err := importSpannerDatabaseId(d.Id())
if err != nil {
return nil, err
}
if id.Project != "" {
d.Set("project", id.Project)
} else {
project, err := getProject(d, config)
if err != nil {
return nil, err
}
id.Project = project
}
d.Set("instance", id.Instance)
d.Set("name", id.Database)
d.SetId(id.terraformId())
return []*schema.ResourceData{d}, nil
}
func buildSpannerDatabaseId(d *schema.ResourceData, config *Config) (*spannerDatabaseId, error) {
project, err := getProject(d, config)
if err != nil {
return nil, err
}
dbName := d.Get("name").(string)
instanceName := d.Get("instance").(string)
return &spannerDatabaseId{
Project: project,
Instance: instanceName,
Database: dbName,
}, nil
}
type spannerDatabaseId struct {
Project string
Instance string
Database string
}
func (s spannerDatabaseId) terraformId() string {
return fmt.Sprintf("%s/%s/%s", s.Project, s.Instance, s.Database)
}
func (s spannerDatabaseId) parentProjectUri() string {
return fmt.Sprintf("projects/%s", s.Project)
}
func (s spannerDatabaseId) parentInstanceUri() string {
return fmt.Sprintf("%s/instances/%s", s.parentProjectUri(), s.Instance)
}
func (s spannerDatabaseId) databaseUri() string {
return fmt.Sprintf("%s/databases/%s", s.parentInstanceUri(), s.Database)
}
func importSpannerDatabaseId(id string) (*spannerDatabaseId, error) {
if !regexp.MustCompile("^[a-z0-9-]+/[a-z0-9-]+$").Match([]byte(id)) &&
!regexp.MustCompile("^[a-z0-9-]+/[a-z0-9-]+/[a-z0-9-]+$").Match([]byte(id)) {
return nil, fmt.Errorf("Invalid spanner database specifier. " +
"Expecting either {projectId}/{instanceId}/{dbId} OR " +
"{instanceId}/{dbId} (where project will be derived from the provider)")
}
parts := strings.Split(id, "/")
if len(parts) == 2 {
log.Printf("[INFO] Spanner database import format of {instanceId}/{dbId} specified: %s", id)
return &spannerDatabaseId{Instance: parts[0], Database: parts[1]}, nil
}
log.Printf("[INFO] Spanner database import format of {projectId}/{instanceId}/{dbId} specified: %s", id)
return extractSpannerDatabaseId(id)
}
func extractSpannerDatabaseId(id string) (*spannerDatabaseId, error) {
if !regexp.MustCompile("^[a-z0-9-]+/[a-z0-9-]+/[a-z0-9-]+$").Match([]byte(id)) {
return nil, fmt.Errorf("Invalid spanner id format, expecting {projectId}/{instanceId}/{databaseId}")
}
parts := strings.Split(id, "/")
return &spannerDatabaseId{
Project: parts[0],
Instance: parts[1],
Database: parts[2],
}, nil
}