github.com/sacloud/libsacloud/v2@v2.32.3/helper/service/enhanceddb/builder.go (about) 1 // Copyright 2016-2022 The Libsacloud Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package enhanceddb 16 17 import ( 18 "context" 19 "errors" 20 21 "github.com/sacloud/libsacloud/v2/sacloud" 22 "github.com/sacloud/libsacloud/v2/sacloud/types" 23 ) 24 25 // Builder エンハンスドデータベースのビルダー 26 type Builder struct { 27 ID types.ID 28 29 Name string 30 Description string 31 Tags types.Tags 32 IconID types.ID 33 DatabaseName string 34 Password string 35 SettingsHash string 36 Client sacloud.EnhancedDBAPI 37 } 38 39 func (b *Builder) Build(ctx context.Context) (*sacloud.EnhancedDB, error) { 40 if b.ID.IsEmpty() { 41 return b.create(ctx) 42 } 43 return b.update(ctx) 44 } 45 46 func (b *Builder) create(ctx context.Context) (*sacloud.EnhancedDB, error) { 47 created, err := b.Client.Create(ctx, &sacloud.EnhancedDBCreateRequest{ 48 Name: b.Name, 49 Description: b.Description, 50 Tags: b.Tags, 51 IconID: b.IconID, 52 DatabaseName: b.DatabaseName, 53 }) 54 if err != nil { 55 return nil, err 56 } 57 58 return created, b.Client.SetPassword(ctx, created.ID, &sacloud.EnhancedDBSetPasswordRequest{ 59 Password: b.Password, 60 }) 61 } 62 63 func (b *Builder) update(ctx context.Context) (*sacloud.EnhancedDB, error) { 64 current, err := b.Client.Read(ctx, b.ID) 65 if err != nil { 66 return nil, err 67 } 68 if current.DatabaseName != b.DatabaseName { 69 return nil, errors.New("DatabaseName cannot be changed") 70 } 71 72 updated, err := b.Client.Update(ctx, b.ID, &sacloud.EnhancedDBUpdateRequest{ 73 Name: b.Name, 74 Description: b.Description, 75 Tags: b.Tags, 76 IconID: b.IconID, 77 SettingsHash: b.SettingsHash, 78 }) 79 if err != nil { 80 return nil, err 81 } 82 83 if b.Password != "" { 84 err := b.Client.SetPassword(ctx, updated.ID, &sacloud.EnhancedDBSetPasswordRequest{ 85 Password: b.Password, 86 }) 87 if err != nil { 88 return nil, err 89 } 90 } 91 92 return updated, nil 93 }