feat: implement database resource management and error handling for SQL Server Flex
This commit is contained in:
parent
e21fe64326
commit
4383300103
4 changed files with 619 additions and 26 deletions
|
|
@ -2,9 +2,12 @@ package sqlserverflexalpha
|
|||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/diag"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/pkg_gen/sqlserverflexalpha"
|
||||
|
|
@ -12,6 +15,7 @@ import (
|
|||
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/core"
|
||||
sqlserverflexalphaGen "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/services/sqlserverflexalpha/database/datasources_gen"
|
||||
sqlserverflexUtils "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/services/sqlserverflexalpha/utils"
|
||||
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/utils"
|
||||
)
|
||||
|
||||
// dataSourceModel maps the data source schema data.
|
||||
|
|
@ -22,6 +26,7 @@ type dataSourceModel struct {
|
|||
|
||||
var _ datasource.DataSource = (*databaseDataSource)(nil)
|
||||
|
||||
// NewDatabaseDataSource creates a new database data source.
|
||||
func NewDatabaseDataSource() datasource.DataSource {
|
||||
return &databaseDataSource{}
|
||||
}
|
||||
|
|
@ -31,6 +36,7 @@ type databaseDataSource struct {
|
|||
providerData core.ProviderData
|
||||
}
|
||||
|
||||
// Metadata returns the data source type name.
|
||||
func (d *databaseDataSource) Metadata(
|
||||
_ context.Context,
|
||||
req datasource.MetadataRequest,
|
||||
|
|
@ -39,6 +45,7 @@ func (d *databaseDataSource) Metadata(
|
|||
resp.TypeName = req.ProviderTypeName + "_sqlserverflexalpha_database"
|
||||
}
|
||||
|
||||
// Schema defines the data source schema.
|
||||
func (d *databaseDataSource) Schema(ctx context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
s := sqlserverflexalphaGen.DatabaseDataSourceSchema(ctx)
|
||||
s.Attributes["id"] = schema.StringAttribute{
|
||||
|
|
@ -70,21 +77,89 @@ func (d *databaseDataSource) Configure(
|
|||
tflog.Info(ctx, "SQL SERVER Flex database client configured")
|
||||
}
|
||||
|
||||
// Read retrieves the resource's state from the API.
|
||||
func (d *databaseDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
|
||||
var data dataSourceModel
|
||||
|
||||
// Read Terraform configuration data into the model
|
||||
resp.Diagnostics.Append(req.Config.Get(ctx, &data)...)
|
||||
|
||||
var model dataSourceModel
|
||||
diags := req.Config.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
// Todo: Read API call logic
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
|
||||
// Example data value setting
|
||||
// data.Id = types.StringValue("example-id")
|
||||
// Extract identifiers from the plan
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
region := d.providerData.GetRegionWithOverride(model.Region)
|
||||
databaseName := model.DatabaseName.ValueString()
|
||||
|
||||
// Save data into Terraform state
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "region", region)
|
||||
ctx = tflog.SetField(ctx, "database_name", databaseName)
|
||||
|
||||
// Fetch database from the API
|
||||
databaseResp, err := d.client.GetDatabaseRequest(ctx, projectId, region, instanceId, databaseName).Execute()
|
||||
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
handleReadError(ctx, &resp.Diagnostics, err, projectId, instanceId)
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.LogResponse(ctx)
|
||||
|
||||
// Map response body to schema and populate Computed attribute values
|
||||
err = mapFields(databaseResp, &model, region)
|
||||
if err != nil {
|
||||
core.LogAndAddError(
|
||||
ctx,
|
||||
&resp.Diagnostics,
|
||||
"Error reading database",
|
||||
fmt.Sprintf("Processing API payload: %v", err),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
tflog.Info(ctx, "SQL Server Flex alpha database read")
|
||||
}
|
||||
|
||||
// handleReadError centralizes API error handling for the Read operation.
|
||||
func handleReadError(ctx context.Context, diags *diag.Diagnostics, err error, projectId, instanceId string) {
|
||||
utils.LogError(
|
||||
ctx,
|
||||
diags,
|
||||
err,
|
||||
"Reading database",
|
||||
fmt.Sprintf(
|
||||
"Could not retrieve database for instance %q in project %q.",
|
||||
instanceId,
|
||||
projectId,
|
||||
),
|
||||
map[int]string{
|
||||
http.StatusBadRequest: fmt.Sprintf(
|
||||
"Invalid request parameters for project %q and instance %q.",
|
||||
projectId,
|
||||
instanceId,
|
||||
),
|
||||
http.StatusNotFound: fmt.Sprintf(
|
||||
"Database, instance %q, or project %q not found.",
|
||||
instanceId,
|
||||
projectId,
|
||||
),
|
||||
http.StatusForbidden: fmt.Sprintf("Forbidden access to project %q.", projectId),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,97 @@
|
|||
package sqlserverflexalpha
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/pkg_gen/sqlserverflexalpha"
|
||||
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/utils"
|
||||
)
|
||||
|
||||
// mapFields maps fields from a ListDatabase API response to a resourceModel for the data source.
|
||||
func mapFields(source *sqlserverflexalpha.GetDatabaseResponse, model *dataSourceModel, region string) error {
|
||||
if source == nil {
|
||||
return fmt.Errorf("response is nil")
|
||||
}
|
||||
if source.Id == nil || *source.Id == 0 {
|
||||
return fmt.Errorf("id not present")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model given is nil")
|
||||
}
|
||||
|
||||
var databaseId int64
|
||||
if model.Id.ValueInt64() != 0 {
|
||||
databaseId = model.Id.ValueInt64()
|
||||
} else if source.Id != nil {
|
||||
databaseId = *source.Id
|
||||
} else {
|
||||
return fmt.Errorf("database id not present")
|
||||
}
|
||||
|
||||
model.Id = types.Int64Value(databaseId)
|
||||
model.DatabaseName = types.StringValue(source.GetName())
|
||||
model.Name = types.StringValue(source.GetName())
|
||||
model.Owner = types.StringValue(strings.Trim(source.GetOwner(), "\""))
|
||||
model.Region = types.StringValue(region)
|
||||
model.ProjectId = types.StringValue(model.ProjectId.ValueString())
|
||||
model.InstanceId = types.StringValue(model.InstanceId.ValueString())
|
||||
model.CompatibilityLevel = types.Int64Value(source.GetCompatibilityLevel())
|
||||
model.CollationName = types.StringValue(source.GetCollationName())
|
||||
|
||||
model.TerraformID = utils.BuildInternalTerraformId(
|
||||
model.ProjectId.ValueString(),
|
||||
region,
|
||||
model.InstanceId.ValueString(),
|
||||
model.DatabaseName.ValueString(),
|
||||
)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// mapResourceFields maps fields from a ListDatabase API response to a resourceModel for the resource.
|
||||
func mapResourceFields(source *sqlserverflexalpha.GetDatabaseResponse, model *resourceModel, region string) error {
|
||||
if source == nil {
|
||||
return fmt.Errorf("response is nil")
|
||||
}
|
||||
if source.Id == nil || *source.Id == 0 {
|
||||
return fmt.Errorf("id not present")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
|
||||
var databaseId int64
|
||||
if model.Id.ValueInt64() != 0 {
|
||||
databaseId = model.Id.ValueInt64()
|
||||
} else if source.Id != nil {
|
||||
databaseId = *source.Id
|
||||
} else {
|
||||
return fmt.Errorf("database id not present")
|
||||
}
|
||||
|
||||
model.Id = types.Int64Value(databaseId)
|
||||
model.DatabaseName = types.StringValue(source.GetName())
|
||||
model.Name = types.StringValue(source.GetName())
|
||||
model.Owner = types.StringValue(strings.Trim(source.GetOwner(), "\""))
|
||||
model.Region = types.StringValue(region)
|
||||
model.ProjectId = types.StringValue(model.ProjectId.ValueString())
|
||||
model.InstanceId = types.StringValue(model.InstanceId.ValueString())
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// toCreatePayload converts the resource model to an API create payload.
|
||||
func toCreatePayload(model *resourceModel) (*sqlserverflexalpha.CreateDatabaseRequestPayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
|
||||
return &sqlserverflexalpha.CreateDatabaseRequestPayload{
|
||||
Name: model.Name.ValueStringPointer(),
|
||||
Owner: model.Owner.ValueStringPointer(),
|
||||
Collation: model.Collation.ValueStringPointer(),
|
||||
Compatibility: model.Compatibility.ValueInt64Pointer(),
|
||||
}, nil
|
||||
}
|
||||
|
|
@ -0,0 +1,227 @@
|
|||
package sqlserverflexalpha
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/pkg_gen/sqlserverflexalpha"
|
||||
datasource "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/services/sqlserverflexalpha/database/datasources_gen"
|
||||
)
|
||||
|
||||
func TestMapFields(t *testing.T) {
|
||||
type given struct {
|
||||
source *sqlserverflexalpha.GetDatabaseResponse
|
||||
model *dataSourceModel
|
||||
region string
|
||||
}
|
||||
type expected struct {
|
||||
model *dataSourceModel
|
||||
err bool
|
||||
}
|
||||
|
||||
testcases := []struct {
|
||||
name string
|
||||
given given
|
||||
expected expected
|
||||
}{
|
||||
{
|
||||
name: "should map fields correctly",
|
||||
given: given{
|
||||
source: &sqlserverflexalpha.GetDatabaseResponse{
|
||||
Id: utils.Ptr(int64(1)),
|
||||
Name: utils.Ptr("my-db"),
|
||||
CollationName: utils.Ptr("collation"),
|
||||
CompatibilityLevel: utils.Ptr(int64(150)),
|
||||
Owner: utils.Ptr("\"my-owner\""),
|
||||
},
|
||||
model: &dataSourceModel{
|
||||
DatabaseModel: datasource.DatabaseModel{
|
||||
ProjectId: types.StringValue("my-project"),
|
||||
InstanceId: types.StringValue("my-instance"),
|
||||
},
|
||||
},
|
||||
region: "eu01",
|
||||
},
|
||||
expected: expected{
|
||||
model: &dataSourceModel{
|
||||
DatabaseModel: datasource.DatabaseModel{
|
||||
Id: types.Int64Value(1),
|
||||
Name: types.StringValue("my-db"),
|
||||
DatabaseName: types.StringValue("my-db"),
|
||||
Owner: types.StringValue("my-owner"),
|
||||
Region: types.StringValue("eu01"),
|
||||
InstanceId: types.StringValue("my-instance"),
|
||||
ProjectId: types.StringValue("my-project"),
|
||||
CompatibilityLevel: types.Int64Value(150),
|
||||
CollationName: types.StringValue("collation"),
|
||||
},
|
||||
TerraformID: types.StringValue("my-project,eu01,my-instance,my-db"),
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "should fail on nil source",
|
||||
given: given{
|
||||
source: nil,
|
||||
model: &dataSourceModel{},
|
||||
},
|
||||
expected: expected{err: true},
|
||||
},
|
||||
{
|
||||
name: "should fail on nil source ID",
|
||||
given: given{
|
||||
source: &sqlserverflexalpha.GetDatabaseResponse{Id: nil},
|
||||
model: &dataSourceModel{},
|
||||
},
|
||||
expected: expected{err: true},
|
||||
},
|
||||
{
|
||||
name: "should fail on nil model",
|
||||
given: given{
|
||||
source: &sqlserverflexalpha.GetDatabaseResponse{Id: utils.Ptr(int64(1))},
|
||||
model: nil,
|
||||
},
|
||||
expected: expected{err: true},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testcases {
|
||||
t.Run(
|
||||
tc.name, func(t *testing.T) {
|
||||
err := mapFields(tc.given.source, tc.given.model, tc.given.region)
|
||||
if (err != nil) != tc.expected.err {
|
||||
t.Fatalf("expected error: %v, got: %v", tc.expected.err, err)
|
||||
}
|
||||
if err == nil {
|
||||
if diff := cmp.Diff(tc.expected.model, tc.given.model); diff != "" {
|
||||
t.Errorf("model mismatch (-want +got):\n%s", diff)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMapResourceFields(t *testing.T) {
|
||||
type given struct {
|
||||
source *sqlserverflexalpha.ListDatabase
|
||||
model *resourceModel
|
||||
region string
|
||||
}
|
||||
type expected struct {
|
||||
model *resourceModel
|
||||
err bool
|
||||
}
|
||||
|
||||
testcases := []struct {
|
||||
name string
|
||||
given given
|
||||
expected expected
|
||||
}{
|
||||
{
|
||||
name: "should map fields correctly",
|
||||
given: given{
|
||||
source: &sqlserverflexalpha.ListDatabase{
|
||||
Id: utils.Ptr(int64(1)),
|
||||
Name: utils.Ptr("my-db"),
|
||||
Owner: utils.Ptr("\"my-owner\""),
|
||||
},
|
||||
model: &resourceModel{
|
||||
ProjectId: types.StringValue("my-project"),
|
||||
InstanceId: types.StringValue("my-instance"),
|
||||
},
|
||||
region: "eu01",
|
||||
},
|
||||
expected: expected{
|
||||
model: &resourceModel{
|
||||
Id: types.Int64Value(1),
|
||||
Name: types.StringValue("my-db"),
|
||||
DatabaseName: types.StringValue("my-db"),
|
||||
InstanceId: types.StringValue("my-instance"),
|
||||
ProjectId: types.StringValue("my-project"),
|
||||
Region: types.StringValue("eu01"),
|
||||
Owner: types.StringValue("my-owner"),
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "should fail on nil source",
|
||||
given: given{
|
||||
source: nil,
|
||||
model: &resourceModel{},
|
||||
},
|
||||
expected: expected{err: true},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testcases {
|
||||
t.Run(
|
||||
tc.name, func(t *testing.T) {
|
||||
err := mapResourceFields(tc.given.source, tc.given.model, tc.given.region)
|
||||
if (err != nil) != tc.expected.err {
|
||||
t.Fatalf("expected error: %v, got: %v", tc.expected.err, err)
|
||||
}
|
||||
if err == nil {
|
||||
if diff := cmp.Diff(tc.expected.model, tc.given.model); diff != "" {
|
||||
t.Errorf("model mismatch (-want +got):\n%s", diff)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestToCreatePayload(t *testing.T) {
|
||||
type given struct {
|
||||
model *resourceModel
|
||||
}
|
||||
type expected struct {
|
||||
payload *sqlserverflexalpha.CreateDatabaseRequestPayload
|
||||
err bool
|
||||
}
|
||||
|
||||
testcases := []struct {
|
||||
name string
|
||||
given given
|
||||
expected expected
|
||||
}{
|
||||
{
|
||||
name: "should convert model to payload",
|
||||
given: given{
|
||||
model: &resourceModel{
|
||||
Name: types.StringValue("my-db"),
|
||||
Owner: types.StringValue("my-owner"),
|
||||
},
|
||||
},
|
||||
expected: expected{
|
||||
payload: &sqlserverflexalpha.CreateDatabaseRequestPayload{
|
||||
Name: utils.Ptr("my-db"),
|
||||
Owner: utils.Ptr("my-owner"),
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "should fail on nil model",
|
||||
given: given{model: nil},
|
||||
expected: expected{err: true},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testcases {
|
||||
t.Run(
|
||||
tc.name, func(t *testing.T) {
|
||||
actual, err := toCreatePayload(tc.given.model)
|
||||
if (err != nil) != tc.expected.err {
|
||||
t.Fatalf("expected error: %v, got: %v", tc.expected.err, err)
|
||||
}
|
||||
if err == nil {
|
||||
if diff := cmp.Diff(tc.expected.payload, actual); diff != "" {
|
||||
t.Errorf("payload mismatch (-want +got):\n%s", diff)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
@ -3,7 +3,9 @@ package sqlserverflexalpha
|
|||
import (
|
||||
"context"
|
||||
_ "embed"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
|
|
@ -13,6 +15,7 @@ import (
|
|||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/oapierror"
|
||||
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/pkg_gen/sqlserverflexalpha"
|
||||
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/conversion"
|
||||
|
||||
|
|
@ -28,6 +31,13 @@ var (
|
|||
_ resource.ResourceWithImportState = &databaseResource{}
|
||||
_ resource.ResourceWithModifyPlan = &databaseResource{}
|
||||
_ resource.ResourceWithIdentity = &databaseResource{}
|
||||
|
||||
// Define errors
|
||||
errDatabaseNotFound = errors.New("database not found")
|
||||
|
||||
// Error message constants
|
||||
extractErrorSummary = "extracting failed"
|
||||
extractErrorMessage = "Extracting identity data: %v"
|
||||
)
|
||||
|
||||
func NewDatabaseResource() resource.Resource {
|
||||
|
|
@ -137,40 +147,181 @@ func (r *databaseResource) Configure(
|
|||
}
|
||||
|
||||
func (r *databaseResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
|
||||
var data sqlserverflexalphaGen.DatabaseModel
|
||||
|
||||
// Read Terraform plan data into the model
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...)
|
||||
var model resourceModel
|
||||
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
// TODO: Create API call logic
|
||||
// Read identity data
|
||||
var identityData DatabaseResourceIdentityModel
|
||||
resp.Diagnostics.Append(req.Identity.Get(ctx, &identityData)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
// Example data value setting
|
||||
// data.DatabaseId = types.StringValue("id-from-response")
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
|
||||
// Save data into Terraform state
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
|
||||
projectId := identityData.ProjectID.ValueString()
|
||||
region := identityData.ProjectID.ValueString()
|
||||
instanceId := identityData.InstanceID.ValueString()
|
||||
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "region", region)
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toCreatePayload(&model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(
|
||||
ctx,
|
||||
&resp.Diagnostics,
|
||||
"Error creating database",
|
||||
fmt.Sprintf("Creating API payload: %v", err),
|
||||
)
|
||||
return
|
||||
}
|
||||
// Create new database
|
||||
databaseResp, err := r.client.CreateDatabaseRequest(
|
||||
ctx,
|
||||
projectId,
|
||||
region,
|
||||
instanceId,
|
||||
).CreateDatabaseRequestPayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating database", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.LogResponse(ctx)
|
||||
|
||||
if databaseResp == nil || databaseResp.Id == nil {
|
||||
core.LogAndAddError(
|
||||
ctx,
|
||||
&resp.Diagnostics,
|
||||
"Error creating database",
|
||||
"API didn't return database Id. A database might have been created",
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
databaseId := *databaseResp.Id
|
||||
databaseName := model.DatabaseName.String()
|
||||
|
||||
ctx = tflog.SetField(ctx, "database_id", databaseId)
|
||||
ctx = tflog.SetField(ctx, "database_name", databaseName)
|
||||
|
||||
ctx = core.LogResponse(ctx)
|
||||
|
||||
database, err := r.client.GetDatabaseRequest(ctx, projectId, region, instanceId, databaseName).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(
|
||||
ctx,
|
||||
&resp.Diagnostics,
|
||||
"Error creating database",
|
||||
fmt.Sprintf("Getting database details after creation: %v", err),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapResourceFields(database, &model, region)
|
||||
if err != nil {
|
||||
core.LogAndAddError(
|
||||
ctx,
|
||||
&resp.Diagnostics,
|
||||
"Error creating database",
|
||||
fmt.Sprintf("Processing API payload: %v", err),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// Set data returned by API in identity
|
||||
identity := DatabaseResourceIdentityModel{
|
||||
ProjectID: types.StringValue(projectId),
|
||||
Region: types.StringValue(region),
|
||||
InstanceID: types.StringValue(instanceId),
|
||||
DatabaseName: types.StringValue(databaseName),
|
||||
}
|
||||
resp.Diagnostics.Append(resp.Identity.Set(ctx, identity)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
// Set state to fully populated data
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, model)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
tflog.Info(ctx, "sqlserverflexalpha.Database created")
|
||||
}
|
||||
|
||||
func (r *databaseResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
|
||||
var data resourceModel
|
||||
|
||||
// Read Terraform prior state data into the model
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &data)...)
|
||||
|
||||
var model resourceModel
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
// Todo: Read API call logic
|
||||
// Read identity data
|
||||
var identityData DatabaseResourceIdentityModel
|
||||
resp.Diagnostics.Append(req.Identity.Get(ctx, &identityData)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
// Save updated data into Terraform state
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
|
||||
projectId, instanceId, region, databaseName, errExt := r.extractIdentityData(model, identityData)
|
||||
if errExt != nil {
|
||||
core.LogAndAddError(
|
||||
ctx,
|
||||
&resp.Diagnostics,
|
||||
extractErrorSummary,
|
||||
fmt.Sprintf(extractErrorMessage, errExt),
|
||||
)
|
||||
}
|
||||
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "region", region)
|
||||
ctx = tflog.SetField(ctx, "database_name", databaseName)
|
||||
|
||||
databaseResp, err := r.client.GetDatabaseRequest(ctx, projectId, region, instanceId, databaseName).Execute()
|
||||
if err != nil {
|
||||
oapiErr, ok := err.(*oapierror.GenericOpenAPIError) //nolint:errorlint //complaining that error.As should be used to catch wrapped errors, but this error should not be wrapped
|
||||
if (ok && oapiErr.StatusCode == http.StatusNotFound) || errors.Is(err, errDatabaseNotFound) {
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading database", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.LogResponse(ctx)
|
||||
|
||||
// Map response body to schema
|
||||
err = mapResourceFields(databaseResp, &model, region)
|
||||
if err != nil {
|
||||
core.LogAndAddError(
|
||||
ctx,
|
||||
&resp.Diagnostics,
|
||||
"Error reading database",
|
||||
fmt.Sprintf("Processing API payload: %v", err),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
tflog.Info(ctx, "sqlserverflexalpha.Database read")
|
||||
}
|
||||
|
|
@ -312,3 +463,46 @@ func (r *databaseResource) ImportState(
|
|||
|
||||
tflog.Info(ctx, "Sqlserverflexalpha database state imported")
|
||||
}
|
||||
|
||||
// extractIdentityData extracts essential identifiers from the resource model, falling back to the identity model.
|
||||
func (r *databaseResource) extractIdentityData(
|
||||
model resourceModel,
|
||||
identity DatabaseResourceIdentityModel,
|
||||
) (projectId, region, instanceId, databaseName string, err error) {
|
||||
if !model.DatabaseName.IsNull() && !model.DatabaseName.IsUnknown() {
|
||||
databaseName = model.DatabaseName.ValueString()
|
||||
} else {
|
||||
if identity.DatabaseName.IsNull() || identity.DatabaseName.IsUnknown() {
|
||||
return "", "", "", "", fmt.Errorf("database_name not found in config")
|
||||
}
|
||||
databaseName = identity.DatabaseName.ValueString()
|
||||
}
|
||||
|
||||
if !model.ProjectId.IsNull() && !model.ProjectId.IsUnknown() {
|
||||
projectId = model.ProjectId.ValueString()
|
||||
} else {
|
||||
if identity.ProjectID.IsNull() || identity.ProjectID.IsUnknown() {
|
||||
return "", "", "", "", fmt.Errorf("project_id not found in config")
|
||||
}
|
||||
projectId = identity.ProjectID.ValueString()
|
||||
}
|
||||
|
||||
if !model.Region.IsNull() && !model.Region.IsUnknown() {
|
||||
region = r.providerData.GetRegionWithOverride(model.Region)
|
||||
} else {
|
||||
if identity.Region.IsNull() || identity.Region.IsUnknown() {
|
||||
return "", "", "", "", fmt.Errorf("region not found in config")
|
||||
}
|
||||
region = r.providerData.GetRegionWithOverride(identity.Region)
|
||||
}
|
||||
|
||||
if !model.InstanceId.IsNull() && !model.InstanceId.IsUnknown() {
|
||||
instanceId = model.InstanceId.ValueString()
|
||||
} else {
|
||||
if identity.InstanceID.IsNull() || identity.InstanceID.IsUnknown() {
|
||||
return "", "", "", "", fmt.Errorf("instance_id not found in config")
|
||||
}
|
||||
instanceId = identity.InstanceID.ValueString()
|
||||
}
|
||||
return projectId, region, instanceId, databaseName, nil
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue