feat: refactor data source models and update mapping functions for improved consistency

This commit is contained in:
Andre_Harms 2026-02-09 21:28:49 +01:00
parent f0e7c19cdf
commit 184e133a2a
34 changed files with 980 additions and 1017 deletions

View file

@ -19,12 +19,6 @@ import (
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/pkg_gen/postgresflexalpha"
)
// DataSourceModel maps the data source schema data.
type DataSourceModel struct {
postgresflexalpha2.DatabaseModel
TerraformID types.String `tfsdk:"id"`
}
// Ensure the implementation satisfies the expected interfaces.
var (
_ datasource.DataSource = &databaseDataSource{}
@ -35,6 +29,12 @@ func NewDatabaseDataSource() datasource.DataSource {
return &databaseDataSource{}
}
// dataSourceModel maps the data source schema data.
type dataSourceModel struct {
postgresflexalpha2.DatabaseModel
TerraformID types.String `tfsdk:"id"`
}
// databaseDataSource is the data source implementation.
type databaseDataSource struct {
client *postgresflexalpha.APIClient
@ -89,7 +89,7 @@ func (r *databaseDataSource) Read(
req datasource.ReadRequest,
resp *datasource.ReadResponse,
) { // nolint:gocritic // function signature required by Terraform
var model DataSourceModel
var model dataSourceModel
diags := req.Config.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
@ -141,7 +141,7 @@ func (r *databaseDataSource) Read(
// getDatabaseByNameOrID retrieves a single database by ensuring either a unique ID or name is provided.
func (r *databaseDataSource) getDatabaseByNameOrID(
ctx context.Context,
model *DataSourceModel,
model *dataSourceModel,
projectId, region, instanceId string,
diags *diag.Diagnostics,
) (*postgresflexalpha.ListDatabase, error) {

View file

@ -9,10 +9,10 @@ import (
"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.
// mapFields maps fields from a ListDatabase API response to a resourceModel for the data source.
func mapFields(
source *postgresflexalpha.ListDatabase,
model *DataSourceModel,
model *dataSourceModel,
region string,
) error {
if source == nil {
@ -51,8 +51,8 @@ func mapFields(
return nil
}
// mapResourceFields maps fields from a ListDatabase API response to a ResourceModel for the resource.
func mapResourceFields(source *postgresflexalpha.ListDatabase, model *ResourceModel) error {
// mapResourceFields maps fields from a ListDatabase API response to a resourceModel for the resource.
func mapResourceFields(source *postgresflexalpha.ListDatabase, model *resourceModel) error {
if source == nil {
return fmt.Errorf("response is nil")
}
@ -80,7 +80,7 @@ func mapResourceFields(source *postgresflexalpha.ListDatabase, model *ResourceMo
}
// toCreatePayload converts the resource model to an API create payload.
func toCreatePayload(model *ResourceModel) (*postgresflexalpha.CreateDatabaseRequestPayload, error) {
func toCreatePayload(model *resourceModel) (*postgresflexalpha.CreateDatabaseRequestPayload, error) {
if model == nil {
return nil, fmt.Errorf("nil model")
}

View file

@ -13,11 +13,11 @@ import (
func TestMapFields(t *testing.T) {
type given struct {
source *postgresflexalpha.ListDatabase
model *DataSourceModel
model *dataSourceModel
region string
}
type expected struct {
model *DataSourceModel
model *dataSourceModel
err bool
}
@ -34,11 +34,11 @@ func TestMapFields(t *testing.T) {
Name: utils.Ptr("my-db"),
Owner: utils.Ptr("\"my-owner\""),
},
model: &DataSourceModel{},
model: &dataSourceModel{},
region: "eu01",
},
expected: expected{
model: &DataSourceModel{
model: &dataSourceModel{
DatabaseModel: datasource.DatabaseModel{
Id: types.Int64Value(1),
Name: types.StringValue("my-db"),
@ -59,7 +59,7 @@ func TestMapFields(t *testing.T) {
Id: utils.Ptr(int64(1)),
Name: utils.Ptr("my-db"),
},
model: &DataSourceModel{
model: &dataSourceModel{
DatabaseModel: datasource.DatabaseModel{
Id: types.Int64Value(1),
ProjectId: types.StringValue("my-project"),
@ -69,7 +69,7 @@ func TestMapFields(t *testing.T) {
region: "eu01",
},
expected: expected{
model: &DataSourceModel{
model: &dataSourceModel{
DatabaseModel: datasource.DatabaseModel{
Id: types.Int64Value(1),
Name: types.StringValue("my-db"),
@ -86,7 +86,7 @@ func TestMapFields(t *testing.T) {
name: "should fail on nil source",
given: given{
source: nil,
model: &DataSourceModel{},
model: &dataSourceModel{},
},
expected: expected{err: true},
},
@ -94,7 +94,7 @@ func TestMapFields(t *testing.T) {
name: "should fail on nil source ID",
given: given{
source: &postgresflexalpha.ListDatabase{Id: nil},
model: &DataSourceModel{},
model: &dataSourceModel{},
},
expected: expected{err: true},
},
@ -128,10 +128,10 @@ func TestMapFields(t *testing.T) {
func TestMapResourceFields(t *testing.T) {
type given struct {
source *postgresflexalpha.ListDatabase
model *ResourceModel
model *resourceModel
}
type expected struct {
model *ResourceModel
model *resourceModel
err bool
}
@ -148,10 +148,10 @@ func TestMapResourceFields(t *testing.T) {
Name: utils.Ptr("my-db"),
Owner: utils.Ptr("\"my-owner\""),
},
model: &ResourceModel{},
model: &resourceModel{},
},
expected: expected{
model: &ResourceModel{
model: &resourceModel{
Id: types.Int64Value(1),
Name: types.StringValue("my-db"),
Owner: types.StringValue("my-owner"),
@ -163,7 +163,7 @@ func TestMapResourceFields(t *testing.T) {
name: "should fail on nil source",
given: given{
source: nil,
model: &ResourceModel{},
model: &resourceModel{},
},
expected: expected{err: true},
},
@ -188,7 +188,7 @@ func TestMapResourceFields(t *testing.T) {
func TestToCreatePayload(t *testing.T) {
type given struct {
model *ResourceModel
model *resourceModel
}
type expected struct {
payload *postgresflexalpha.CreateDatabaseRequestPayload
@ -203,7 +203,7 @@ func TestToCreatePayload(t *testing.T) {
{
name: "should convert model to payload",
given: given{
model: &ResourceModel{
model: &resourceModel{
Name: types.StringValue("my-db"),
Owner: types.StringValue("my-owner"),
},

View file

@ -41,8 +41,13 @@ var (
extractErrorMessage = "Extracting identity data: %v"
)
// ResourceModel describes the resource data model.
type ResourceModel = postgresflexalpha2.DatabaseModel
// NewDatabaseResource is a helper function to simplify the provider implementation.
func NewDatabaseResource() resource.Resource {
return &databaseResource{}
}
// resourceModel describes the resource data model.
type resourceModel = postgresflexalpha2.DatabaseModel
// DatabaseResourceIdentityModel describes the resource's identity attributes.
type DatabaseResourceIdentityModel struct {
@ -52,11 +57,6 @@ type DatabaseResourceIdentityModel struct {
DatabaseID types.Int64 `tfsdk:"database_id"`
}
// NewDatabaseResource is a helper function to simplify the provider implementation.
func NewDatabaseResource() resource.Resource {
return &databaseResource{}
}
// databaseResource is the resource implementation.
type databaseResource struct {
client *postgresflexalpha.APIClient
@ -69,7 +69,7 @@ func (r *databaseResource) ModifyPlan(
req resource.ModifyPlanRequest,
resp *resource.ModifyPlanResponse,
) { // nolint:gocritic // function signature required by Terraform
var configModel ResourceModel
var configModel resourceModel
// skip initial empty configuration to avoid follow-up errors
if req.Config.Raw.IsNull() {
return
@ -79,7 +79,7 @@ func (r *databaseResource) ModifyPlan(
return
}
var planModel ResourceModel
var planModel resourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &planModel)...)
if resp.Diagnostics.HasError() {
return
@ -199,7 +199,7 @@ func (r *databaseResource) Create(
req resource.CreateRequest,
resp *resource.CreateResponse,
) { // nolint:gocritic // function signature required by Terraform
var model ResourceModel
var model resourceModel
diags := req.Plan.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
@ -309,7 +309,7 @@ func (r *databaseResource) Read(
req resource.ReadRequest,
resp *resource.ReadResponse,
) { // nolint:gocritic // function signature required by Terraform
var model ResourceModel
var model resourceModel
diags := req.State.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
@ -380,7 +380,7 @@ func (r *databaseResource) Update(
req resource.UpdateRequest,
resp *resource.UpdateResponse,
) {
var model ResourceModel
var model resourceModel
diags := req.Plan.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
@ -418,7 +418,7 @@ func (r *databaseResource) Update(
ctx = tflog.SetField(ctx, "database_id", databaseId)
// Retrieve values from state
var stateModel ResourceModel
var stateModel resourceModel
diags = req.State.Get(ctx, &stateModel)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
@ -483,7 +483,7 @@ func (r *databaseResource) Delete(
req resource.DeleteRequest,
resp *resource.DeleteResponse,
) { // nolint:gocritic // function signature required by Terraform
var model ResourceModel
var model resourceModel
diags := req.State.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
@ -591,7 +591,7 @@ func (r *databaseResource) ImportState(
// extractIdentityData extracts essential identifiers from the resource model, falling back to the identity model.
func (r *databaseResource) extractIdentityData(
model ResourceModel,
model resourceModel,
identity DatabaseResourceIdentityModel,
) (projectId, region, instanceId string, databaseId int64, err error) {
if !model.DatabaseId.IsNull() && !model.DatabaseId.IsUnknown() {

View file

@ -12,8 +12,8 @@ type mockRequest struct {
executeFunc func() (*postgresflex.GetFlavorsResponse, error)
}
func (m *mockRequest) Page(_ int64) postgresflex.ApiGetFlavorsRequestRequest { return m }
func (m *mockRequest) Size(_ int64) postgresflex.ApiGetFlavorsRequestRequest { return m }
func (m *mockRequest) Page(_ int32) postgresflex.ApiGetFlavorsRequestRequest { return m }
func (m *mockRequest) Size(_ int32) postgresflex.ApiGetFlavorsRequestRequest { return m }
func (m *mockRequest) Sort(_ postgresflex.FlavorSort) postgresflex.ApiGetFlavorsRequestRequest {
return m
}

View file

@ -21,12 +21,19 @@ func NewFlavorsDataSource() datasource.DataSource {
return &flavorsDataSource{}
}
// dataSourceModel maps the data source schema data.
type dataSourceModel = postgresflexalphaGen.FlavorsModel
type flavorsDataSource struct {
client *postgresflexalpha.APIClient
providerData core.ProviderData
}
func (d *flavorsDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
func (d *flavorsDataSource) Metadata(
_ context.Context,
req datasource.MetadataRequest,
resp *datasource.MetadataResponse,
) {
resp.TypeName = req.ProviderTypeName + "_postgresflexalpha_flavors"
}
@ -35,7 +42,11 @@ func (d *flavorsDataSource) Schema(ctx context.Context, _ datasource.SchemaReque
}
// Configure adds the provider configured client to the data source.
func (d *flavorsDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
func (d *flavorsDataSource) Configure(
ctx context.Context,
req datasource.ConfigureRequest,
resp *datasource.ConfigureResponse,
) {
var ok bool
d.providerData, ok = conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
if !ok {
@ -51,7 +62,7 @@ func (d *flavorsDataSource) Configure(ctx context.Context, req datasource.Config
}
func (d *flavorsDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
var data postgresflexalphaGen.FlavorsModel
var data dataSourceModel
// Read Terraform configuration data into the model
resp.Diagnostics.Append(req.Config.Get(ctx, &data)...)

View file

@ -5,6 +5,7 @@ import (
"fmt"
"net/http"
"github.com/hashicorp/terraform-plugin-framework/types"
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/pkg_gen/postgresflexalpha"
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/conversion"
postgresflexalpha2 "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/services/postgresflexalpha/instance/datasources_gen"
@ -26,6 +27,12 @@ func NewInstanceDataSource() datasource.DataSource {
return &instanceDataSource{}
}
// dataSourceModel maps the data source schema data.
type dataSourceModel struct {
postgresflexalpha2.InstanceModel
TerraformID types.String `tfsdk:"id"`
}
// instanceDataSource is the data source implementation.
type instanceDataSource struct {
client *postgresflexalpha.APIClient
@ -33,12 +40,20 @@ type instanceDataSource struct {
}
// Metadata returns the data source type name.
func (r *instanceDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
func (r *instanceDataSource) Metadata(
_ context.Context,
req datasource.MetadataRequest,
resp *datasource.MetadataResponse,
) {
resp.TypeName = req.ProviderTypeName + "_postgresflexalpha_instance"
}
// Configure adds the provider configured client to the data source.
func (r *instanceDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
func (r *instanceDataSource) Configure(
ctx context.Context,
req datasource.ConfigureRequest,
resp *datasource.ConfigureResponse,
) {
var ok bool
r.providerData, ok = conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
if !ok {
@ -59,8 +74,12 @@ func (r *instanceDataSource) Schema(ctx context.Context, _ datasource.SchemaRequ
}
// Read refreshes the Terraform state with the latest data.
func (r *instanceDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
var model postgresflexalpha2.InstanceModel
func (r *instanceDataSource) Read(
ctx context.Context,
req datasource.ReadRequest,
resp *datasource.ReadResponse,
) { // nolint:gocritic // function signature required by Terraform
var model dataSourceModel
diags := req.Config.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {

View file

@ -14,26 +14,32 @@ import (
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/utils"
)
func mapGetInstanceResponseToModel(ctx context.Context, m *postgresflexalpharesource.InstanceModel, resp *postgresflex.GetInstanceResponse) error {
tflog.Debug(ctx, ">>>> MSH DEBUG <<<<", map[string]interface{}{
"id": m.Id.ValueString(),
"instance_id": m.InstanceId.ValueString(),
"backup_schedule": m.BackupSchedule.ValueString(),
"flavor_id": m.FlavorId.ValueString(),
"encryption.kek_key_id": m.Encryption.KekKeyId.ValueString(),
"encryption.kek_key_ring_id": m.Encryption.KekKeyRingId.ValueString(),
"encryption.kek_key_version": m.Encryption.KekKeyVersion.ValueString(),
"encryption.service_account": m.Encryption.ServiceAccount.ValueString(),
"is_deletable": m.IsDeletable.ValueBool(),
"name": m.Name.ValueString(),
"status": m.Status.ValueString(),
"retention_days": m.RetentionDays.ValueInt64(),
"replicas": m.Replicas.ValueInt64(),
"network.instance_address": m.Network.InstanceAddress.ValueString(),
"network.router_address": m.Network.RouterAddress.ValueString(),
"version": m.Version.ValueString(),
"network.acl": m.Network.Acl.String(),
})
func mapGetInstanceResponseToModel(
ctx context.Context,
m *postgresflexalpharesource.InstanceModel,
resp *postgresflex.GetInstanceResponse,
) error {
tflog.Debug(
ctx, ">>>> MSH DEBUG <<<<", map[string]interface{}{
"id": m.Id.ValueString(),
"instance_id": m.InstanceId.ValueString(),
"backup_schedule": m.BackupSchedule.ValueString(),
"flavor_id": m.FlavorId.ValueString(),
"encryption.kek_key_id": m.Encryption.KekKeyId.ValueString(),
"encryption.kek_key_ring_id": m.Encryption.KekKeyRingId.ValueString(),
"encryption.kek_key_version": m.Encryption.KekKeyVersion.ValueString(),
"encryption.service_account": m.Encryption.ServiceAccount.ValueString(),
"is_deletable": m.IsDeletable.ValueBool(),
"name": m.Name.ValueString(),
"status": m.Status.ValueString(),
"retention_days": m.RetentionDays.ValueInt64(),
"replicas": m.Replicas.ValueInt64(),
"network.instance_address": m.Network.InstanceAddress.ValueString(),
"network.router_address": m.Network.RouterAddress.ValueString(),
"version": m.Version.ValueString(),
"network.acl": m.Network.Acl.String(),
},
)
m.BackupSchedule = types.StringValue(resp.GetBackupSchedule())
m.Encryption = postgresflexalpharesource.NewEncryptionValueNull()
@ -61,7 +67,11 @@ func mapGetInstanceResponseToModel(ctx context.Context, m *postgresflexalphareso
m.FlavorId = types.StringValue(resp.GetFlavorId())
if m.Id.IsNull() || m.Id.IsUnknown() {
m.Id = utils.BuildInternalTerraformId(m.ProjectId.ValueString(), m.Region.ValueString(), m.InstanceId.ValueString())
m.Id = utils.BuildInternalTerraformId(
m.ProjectId.ValueString(),
m.Region.ValueString(),
m.InstanceId.ValueString(),
)
}
m.InstanceId = types.StringPointerValue(resp.Id)
@ -121,7 +131,11 @@ func mapGetInstanceResponseToModel(ctx context.Context, m *postgresflexalphareso
return nil
}
func mapGetDataInstanceResponseToModel(ctx context.Context, m *postgresflexalphadatasource.InstanceModel, resp *postgresflex.GetInstanceResponse) error {
func mapGetDataInstanceResponseToModel(
ctx context.Context,
m *dataSourceModel,
resp *postgresflex.GetInstanceResponse,
) error {
m.BackupSchedule = types.StringValue(resp.GetBackupSchedule())
handleEncryption(m, resp)
m.ConnectionInfo.Host = types.StringValue(resp.ConnectionInfo.GetHost())
@ -155,7 +169,7 @@ func mapGetDataInstanceResponseToModel(ctx context.Context, m *postgresflexalpha
return nil
}
func handleNetwork(ctx context.Context, m *postgresflexalphadatasource.InstanceModel, resp *postgresflex.GetInstanceResponse) error {
func handleNetwork(ctx context.Context, m *dataSourceModel, resp *postgresflex.GetInstanceResponse) error {
netAcl, diags := types.ListValueFrom(ctx, types.StringType, resp.Network.GetAcl())
if diags.HasError() {
return fmt.Errorf("failed converting network acl from response")
@ -187,7 +201,7 @@ func handleNetwork(ctx context.Context, m *postgresflexalphadatasource.InstanceM
return nil
}
func handleEncryption(m *postgresflexalphadatasource.InstanceModel, resp *postgresflex.GetInstanceResponse) {
func handleEncryption(m *dataSourceModel, resp *postgresflex.GetInstanceResponse) {
keyId := ""
if keyIdVal, ok := resp.Encryption.GetKekKeyIdOk(); ok {
keyId = keyIdVal

View file

@ -23,8 +23,6 @@ import (
wait "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/wait/postgresflexalpha"
)
const packageName = "postgresflexalpha"
// Ensure the implementation satisfies the expected interfaces.
var (
_ resource.Resource = &instanceResource{}
@ -40,11 +38,8 @@ func NewInstanceResource() resource.Resource {
return &instanceResource{}
}
// instanceResource is the resource implementation.
type instanceResource struct {
client *postgresflex.APIClient
providerData core.ProviderData
}
// resourceModel describes the resource data model.
type resourceModel = postgresflexalpha.InstanceModel
type InstanceResourceIdentityModel struct {
ProjectID types.String `tfsdk:"project_id"`
@ -52,8 +47,18 @@ type InstanceResourceIdentityModel struct {
InstanceID types.String `tfsdk:"instance_id"`
}
func (r *instanceResource) ValidateConfig(ctx context.Context, req resource.ValidateConfigRequest, resp *resource.ValidateConfigResponse) {
var data postgresflexalpha.InstanceModel
// instanceResource is the resource implementation.
type instanceResource struct {
client *postgresflex.APIClient
providerData core.ProviderData
}
func (r *instanceResource) ValidateConfig(
ctx context.Context,
req resource.ValidateConfigRequest,
resp *resource.ValidateConfigResponse,
) {
var data resourceModel
resp.Diagnostics.Append(req.Config.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
@ -72,7 +77,11 @@ func (r *instanceResource) ValidateConfig(ctx context.Context, req resource.Vali
// ModifyPlan implements resource.ResourceWithModifyPlan.
// Use the modifier to set the effective region in the current plan.
func (r *instanceResource) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse) { // nolint:gocritic // function signature required by Terraform
func (r *instanceResource) ModifyPlan(
ctx context.Context,
req resource.ModifyPlanRequest,
resp *resource.ModifyPlanResponse,
) { // nolint:gocritic // function signature required by Terraform
var configModel postgresflexalpha.InstanceModel
// skip initial empty configuration to avoid follow-up errors
if req.Config.Raw.IsNull() {
@ -149,7 +158,11 @@ func (r *instanceResource) Schema(ctx context.Context, _ resource.SchemaRequest,
resp.Schema = schema
}
func (r *instanceResource) IdentitySchema(_ context.Context, _ resource.IdentitySchemaRequest, resp *resource.IdentitySchemaResponse) {
func (r *instanceResource) IdentitySchema(
_ context.Context,
_ resource.IdentitySchemaRequest,
resp *resource.IdentitySchemaResponse,
) {
resp.IdentitySchema = identityschema.Schema{
Attributes: map[string]identityschema.Attribute{
"project_id": identityschema.StringAttribute{
@ -171,7 +184,7 @@ func (r *instanceResource) Create(
req resource.CreateRequest,
resp *resource.CreateResponse,
) { // nolint:gocritic // function signature required by Terraform
var model postgresflexalpha.InstanceModel
var model resourceModel
diags := req.Plan.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
@ -201,7 +214,11 @@ func (r *instanceResource) Create(
payload := modelToCreateInstancePayload(netAcl, model, replVal)
// Create new instance
createResp, err := r.client.CreateInstanceRequest(ctx, projectId, region).CreateInstanceRequestPayload(payload).Execute()
createResp, err := r.client.CreateInstanceRequest(
ctx,
projectId,
region,
).CreateInstanceRequestPayload(payload).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "error creating instance", fmt.Sprintf("Calling API: %v", err))
return
@ -227,13 +244,23 @@ func (r *instanceResource) Create(
waitResp, err := wait.CreateInstanceWaitHandler(ctx, r.client, projectId, region, instanceId).WaitWithContext(ctx)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Wait handler error: %v", err))
core.LogAndAddError(
ctx,
&resp.Diagnostics,
"Error creating instance",
fmt.Sprintf("Wait handler error: %v", err),
)
return
}
err = mapGetInstanceResponseToModel(ctx, &model, waitResp)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Error creating model: %v", err))
core.LogAndAddError(
ctx,
&resp.Diagnostics,
"Error creating instance",
fmt.Sprintf("Error creating model: %v", err),
)
return
}
@ -246,7 +273,11 @@ func (r *instanceResource) Create(
tflog.Info(ctx, "Postgres Flex instance created")
}
func modelToCreateInstancePayload(netAcl []string, model postgresflexalpha.InstanceModel, replVal int32) postgresflex.CreateInstanceRequestPayload {
func modelToCreateInstancePayload(
netAcl []string,
model postgresflexalpha.InstanceModel,
replVal int32,
) postgresflex.CreateInstanceRequestPayload {
var enc *postgresflex.InstanceEncryption
if !model.Encryption.IsNull() && !model.Encryption.IsUnknown() {
enc = &postgresflex.InstanceEncryption{
@ -279,10 +310,14 @@ func modelToCreateInstancePayload(netAcl []string, model postgresflexalpha.Insta
}
// Read refreshes the Terraform state with the latest data.
func (r *instanceResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
func (r *instanceResource) Read(
ctx context.Context,
req resource.ReadRequest,
resp *resource.ReadResponse,
) { // nolint:gocritic // function signature required by Terraform
functionErrorSummary := "read instance failed"
var model postgresflexalpha.InstanceModel
var model resourceModel
diags := req.State.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
@ -371,7 +406,12 @@ func (r *instanceResource) Read(ctx context.Context, req resource.ReadRequest, r
err = mapGetInstanceResponseToModel(ctx, &model, instanceResp)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, functionErrorSummary, fmt.Sprintf("Processing API payload: %v", err))
core.LogAndAddError(
ctx,
&resp.Diagnostics,
functionErrorSummary,
fmt.Sprintf("Processing API payload: %v", err),
)
return
}
@ -396,8 +436,12 @@ func (r *instanceResource) Read(ctx context.Context, req resource.ReadRequest, r
}
// Update updates the resource and sets the updated Terraform state on success.
func (r *instanceResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
var model postgresflexalpha.InstanceModel
func (r *instanceResource) Update(
ctx context.Context,
req resource.UpdateRequest,
resp *resource.UpdateResponse,
) { // nolint:gocritic // function signature required by Terraform
var model resourceModel
diags := req.Plan.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
@ -475,15 +519,31 @@ func (r *instanceResource) Update(ctx context.Context, req resource.UpdateReques
ctx = core.LogResponse(ctx)
waitResp, err := wait.PartialUpdateInstanceWaitHandler(ctx, r.client, projectId, region, instanceId).WaitWithContext(ctx)
waitResp, err := wait.PartialUpdateInstanceWaitHandler(
ctx,
r.client,
projectId,
region,
instanceId,
).WaitWithContext(ctx)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Instance update waiting: %v", err))
core.LogAndAddError(
ctx,
&resp.Diagnostics,
"Error updating instance",
fmt.Sprintf("Instance update waiting: %v", err),
)
return
}
err = mapGetInstanceResponseToModel(ctx, &model, waitResp)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Processing API payload: %v", err))
core.LogAndAddError(
ctx,
&resp.Diagnostics,
"Error updating instance",
fmt.Sprintf("Processing API payload: %v", err),
)
return
}
@ -496,8 +556,12 @@ func (r *instanceResource) Update(ctx context.Context, req resource.UpdateReques
}
// Delete deletes the resource and removes the Terraform state on success.
func (r *instanceResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
var model postgresflexalpha.InstanceModel
func (r *instanceResource) Delete(
ctx context.Context,
req resource.DeleteRequest,
resp *resource.DeleteResponse,
) { // nolint:gocritic // function signature required by Terraform
var model resourceModel
diags := req.State.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
@ -538,16 +602,24 @@ func (r *instanceResource) Delete(ctx context.Context, req resource.DeleteReques
// ImportState imports a resource into the Terraform state on success.
// The expected format of the resource import identifier is: project_id,region,instance_id
func (r *instanceResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
func (r *instanceResource) ImportState(
ctx context.Context,
req resource.ImportStateRequest,
resp *resource.ImportStateResponse,
) {
ctx = core.InitProviderContext(ctx)
if req.ID != "" {
idParts := strings.Split(req.ID, core.Separator)
if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" {
core.LogAndAddError(ctx, &resp.Diagnostics,
core.LogAndAddError(
ctx, &resp.Diagnostics,
"Error importing instance",
fmt.Sprintf("Expected import identifier with format: [project_id],[region],[instance_id] Got: %q", req.ID),
fmt.Sprintf(
"Expected import identifier with format: [project_id],[region],[instance_id] Got: %q",
req.ID,
),
)
return
}
@ -573,10 +645,23 @@ func (r *instanceResource) ImportState(ctx context.Context, req resource.ImportS
identityData.Region.ValueString(),
identityData.InstanceID.ValueString(),
),
)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), identityData.ProjectID.ValueString())...)
)...,
)
resp.Diagnostics.Append(
resp.State.SetAttribute(
ctx,
path.Root("project_id"),
identityData.ProjectID.ValueString(),
)...,
)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), identityData.Region.ValueString())...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), identityData.InstanceID.ValueString())...)
resp.Diagnostics.Append(
resp.State.SetAttribute(
ctx,
path.Root("instance_id"),
identityData.InstanceID.ValueString(),
)...,
)
tflog.Info(ctx, "Postgres Flex instance state imported")
}

View file

@ -25,17 +25,17 @@ var (
_ datasource.DataSource = &userDataSource{}
)
// DataSourceModel maps the data source schema data.
type DataSourceModel struct {
postgresflexalpha.UserModel
TerraformID types.String `tfsdk:"id"`
}
// NewUserDataSource is a helper function to simplify the provider implementation.
func NewUserDataSource() datasource.DataSource {
return &userDataSource{}
}
// dataSourceModel maps the data source schema data.
type dataSourceModel struct {
postgresflexalpha.UserModel
TerraformID types.String `tfsdk:"id"`
}
// userDataSource is the data source implementation.
type userDataSource struct {
client *postgresflex.APIClient
@ -90,7 +90,7 @@ func (r *userDataSource) Read(
req datasource.ReadRequest,
resp *datasource.ReadResponse,
) { // nolint:gocritic // function signature required by Terraform
var model DataSourceModel
var model dataSourceModel
diags := req.Config.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {

View file

@ -13,7 +13,7 @@ import (
)
// mapDataSourceFields maps API response to data source model, preserving existing ID.
func mapDataSourceFields(userResp *postgresflex.GetUserResponse, model *DataSourceModel, region string) error {
func mapDataSourceFields(userResp *postgresflex.GetUserResponse, model *dataSourceModel, region string) error {
if userResp == nil {
return fmt.Errorf("response is nil")
}
@ -68,7 +68,7 @@ func toPayloadRoles(roles *[]string) *[]postgresflex.UserRole {
}
// toUpdatePayload creates an API update payload from the resource model.
func toUpdatePayload(model *ResourceModel, roles *[]string) (
func toUpdatePayload(model *resourceModel, roles *[]string) (
*postgresflex.UpdateUserRequestPayload,
error,
) {
@ -86,7 +86,7 @@ func toUpdatePayload(model *ResourceModel, roles *[]string) (
}
// toCreatePayload creates an API create payload from the resource model.
func toCreatePayload(model *ResourceModel, roles *[]string) (*postgresflex.CreateUserRequestPayload, error) {
func toCreatePayload(model *resourceModel, roles *[]string) (*postgresflex.CreateUserRequestPayload, error) {
if model == nil {
return nil, fmt.Errorf("nil model")
}
@ -101,7 +101,7 @@ func toCreatePayload(model *ResourceModel, roles *[]string) (*postgresflex.Creat
}
// mapResourceFields maps API response to the resource model, preserving existing ID.
func mapResourceFields(userResp *postgresflex.GetUserResponse, model *ResourceModel, region string) error {
func mapResourceFields(userResp *postgresflex.GetUserResponse, model *resourceModel, region string) error {
if userResp == nil {
return fmt.Errorf("response is nil")
}
@ -118,9 +118,7 @@ func mapResourceFields(userResp *postgresflex.GetUserResponse, model *ResourceMo
} else {
return fmt.Errorf("user id not present")
}
model.TerraformID = utils.BuildInternalTerraformId(
model.ProjectId.ValueString(), region, model.InstanceId.ValueString(), strconv.FormatInt(userId, 10),
)
model.Id = types.Int64Value(userId)
model.UserId = types.Int64Value(userId)
model.Name = types.StringPointerValue(user.Name)

View file

@ -9,7 +9,6 @@ import (
"github.com/stackitcloud/stackit-sdk-go/core/utils"
postgresflex "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/pkg_gen/postgresflexalpha"
data "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/services/postgresflexalpha/user/datasources_gen"
resource "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/services/postgresflexalpha/user/resources_gen"
)
func TestMapDataSourceFields(t *testing.T) {
@ -18,14 +17,14 @@ func TestMapDataSourceFields(t *testing.T) {
description string
input *postgresflex.GetUserResponse
region string
expected DataSourceModel
expected dataSourceModel
isValid bool
}{
{
"default_values",
&postgresflex.GetUserResponse{},
testRegion,
DataSourceModel{
dataSourceModel{
UserModel: data.UserModel{
Id: types.Int64Value(1),
UserId: types.Int64Value(1),
@ -51,7 +50,7 @@ func TestMapDataSourceFields(t *testing.T) {
Name: utils.Ptr("username"),
},
testRegion,
DataSourceModel{
dataSourceModel{
UserModel: data.UserModel{
Id: types.Int64Value(1),
@ -84,7 +83,7 @@ func TestMapDataSourceFields(t *testing.T) {
Status: utils.Ptr("status"),
},
testRegion,
DataSourceModel{
dataSourceModel{
UserModel: data.UserModel{
Id: types.Int64Value(1),
UserId: types.Int64Value(1),
@ -103,28 +102,28 @@ func TestMapDataSourceFields(t *testing.T) {
"nil_response",
nil,
testRegion,
DataSourceModel{},
dataSourceModel{},
false,
},
{
"nil_response_2",
&postgresflex.GetUserResponse{},
testRegion,
DataSourceModel{},
dataSourceModel{},
false,
},
{
"no_resource_id",
&postgresflex.GetUserResponse{},
testRegion,
DataSourceModel{},
dataSourceModel{},
false,
},
}
for _, tt := range tests {
t.Run(
tt.description, func(t *testing.T) {
state := &DataSourceModel{
state := &dataSourceModel{
UserModel: data.UserModel{
ProjectId: tt.expected.ProjectId,
InstanceId: tt.expected.InstanceId,
@ -155,7 +154,7 @@ func TestMapFieldsCreate(t *testing.T) {
description string
input *postgresflex.GetUserResponse
region string
expected ResourceModel
expected resourceModel
isValid bool
}{
{
@ -164,19 +163,16 @@ func TestMapFieldsCreate(t *testing.T) {
Id: utils.Ptr(int64(1)),
},
testRegion,
ResourceModel{
UserModel: resource.UserModel{
UserId: types.Int64Value(1),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Name: types.StringNull(),
Roles: types.List(types.SetNull(types.StringType)),
Password: types.StringNull(),
Region: types.StringValue(testRegion),
Status: types.StringNull(),
ConnectionString: types.StringNull(),
},
TerraformID: types.StringValue("pid,region,iid,1"),
resourceModel{
UserId: types.Int64Value(1),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Name: types.StringNull(),
Roles: types.List(types.SetNull(types.StringType)),
Password: types.StringNull(),
Region: types.StringValue(testRegion),
Status: types.StringNull(),
ConnectionString: types.StringNull(),
},
true,
},
@ -188,19 +184,16 @@ func TestMapFieldsCreate(t *testing.T) {
Status: utils.Ptr("status"),
},
testRegion,
ResourceModel{
UserModel: resource.UserModel{
UserId: types.Int64Value(1),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Name: types.StringValue("username"),
Roles: types.List(types.SetNull(types.StringType)),
Password: types.StringNull(),
Region: types.StringValue(testRegion),
Status: types.StringValue("status"),
ConnectionString: types.StringValue("connection_string"),
},
TerraformID: types.StringValue("pid,region,iid,1"),
resourceModel{
UserId: types.Int64Value(1),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Name: types.StringValue("username"),
Roles: types.List(types.SetNull(types.StringType)),
Password: types.StringNull(),
Region: types.StringValue(testRegion),
Status: types.StringValue("status"),
ConnectionString: types.StringValue("connection_string"),
},
true,
},
@ -212,19 +205,16 @@ func TestMapFieldsCreate(t *testing.T) {
Status: nil,
},
testRegion,
ResourceModel{
UserModel: resource.UserModel{
UserId: types.Int64Value(1),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Name: types.StringNull(),
Roles: types.List(types.SetNull(types.StringType)),
Password: types.StringNull(),
Region: types.StringValue(testRegion),
Status: types.StringNull(),
ConnectionString: types.StringNull(),
},
TerraformID: types.StringValue("pid,region,iid,1"),
resourceModel{
UserId: types.Int64Value(1),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Name: types.StringNull(),
Roles: types.List(types.SetNull(types.StringType)),
Password: types.StringNull(),
Region: types.StringValue(testRegion),
Status: types.StringNull(),
ConnectionString: types.StringNull(),
},
true,
},
@ -232,32 +222,30 @@ func TestMapFieldsCreate(t *testing.T) {
"nil_response",
nil,
testRegion,
ResourceModel{},
resourceModel{},
false,
},
{
"nil_response_2",
&postgresflex.GetUserResponse{},
testRegion,
ResourceModel{},
resourceModel{},
false,
},
{
"no_resource_id",
&postgresflex.GetUserResponse{},
testRegion,
ResourceModel{},
resourceModel{},
false,
},
}
for _, tt := range tests {
t.Run(
tt.description, func(t *testing.T) {
state := &ResourceModel{
UserModel: resource.UserModel{
ProjectId: tt.expected.ProjectId,
InstanceId: tt.expected.InstanceId,
},
state := &resourceModel{
ProjectId: tt.expected.ProjectId,
InstanceId: tt.expected.InstanceId,
}
err := mapResourceFields(tt.input, state, tt.region)
@ -284,7 +272,7 @@ func TestMapFields(t *testing.T) {
description string
input *postgresflex.GetUserResponse
region string
expected ResourceModel
expected resourceModel
isValid bool
}{
{
@ -293,19 +281,16 @@ func TestMapFields(t *testing.T) {
Id: utils.Ptr(int64(1)),
},
testRegion,
ResourceModel{
UserModel: resource.UserModel{
Id: types.Int64Value(1),
UserId: types.Int64Value(int64(1)),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Name: types.StringNull(),
Roles: types.List(types.SetNull(types.StringType)),
Region: types.StringValue(testRegion),
Status: types.StringNull(),
ConnectionString: types.StringNull(),
},
TerraformID: types.StringValue("pid,region,iid,1"),
resourceModel{
Id: types.Int64Value(1),
UserId: types.Int64Value(int64(1)),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Name: types.StringNull(),
Roles: types.List(types.SetNull(types.StringType)),
Region: types.StringValue(testRegion),
Status: types.StringNull(),
ConnectionString: types.StringNull(),
},
true,
},
@ -321,27 +306,24 @@ func TestMapFields(t *testing.T) {
Name: utils.Ptr("username"),
},
testRegion,
ResourceModel{
UserModel: resource.UserModel{
Id: types.Int64Value(1),
UserId: types.Int64Value(1),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Name: types.StringValue("username"),
Roles: types.List(
types.SetValueMust(
types.StringType, []attr.Value{
types.StringValue("role_1"),
types.StringValue("role_2"),
types.StringValue(""),
},
),
resourceModel{
Id: types.Int64Value(1),
UserId: types.Int64Value(1),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Name: types.StringValue("username"),
Roles: types.List(
types.SetValueMust(
types.StringType, []attr.Value{
types.StringValue("role_1"),
types.StringValue("role_2"),
types.StringValue(""),
},
),
Region: types.StringValue(testRegion),
Status: types.StringNull(),
ConnectionString: types.StringNull(),
},
TerraformID: types.StringValue("pid,region,iid,1"),
),
Region: types.StringValue(testRegion),
Status: types.StringNull(),
ConnectionString: types.StringNull(),
},
true,
},
@ -352,19 +334,16 @@ func TestMapFields(t *testing.T) {
Name: nil,
},
testRegion,
ResourceModel{
UserModel: resource.UserModel{
Id: types.Int64Value(1),
UserId: types.Int64Value(1),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Name: types.StringNull(),
Roles: types.List(types.SetNull(types.StringType)),
Region: types.StringValue(testRegion),
Status: types.StringNull(),
ConnectionString: types.StringNull(),
},
TerraformID: types.StringValue("pid,region,iid,1"),
resourceModel{
Id: types.Int64Value(1),
UserId: types.Int64Value(1),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Name: types.StringNull(),
Roles: types.List(types.SetNull(types.StringType)),
Region: types.StringValue(testRegion),
Status: types.StringNull(),
ConnectionString: types.StringNull(),
},
true,
},
@ -372,32 +351,30 @@ func TestMapFields(t *testing.T) {
"nil_response",
nil,
testRegion,
ResourceModel{},
resourceModel{},
false,
},
{
"nil_response_2",
&postgresflex.GetUserResponse{},
testRegion,
ResourceModel{},
resourceModel{},
false,
},
{
"no_resource_id",
&postgresflex.GetUserResponse{},
testRegion,
ResourceModel{},
resourceModel{},
false,
},
}
for _, tt := range tests {
t.Run(
tt.description, func(t *testing.T) {
state := &ResourceModel{
UserModel: resource.UserModel{
ProjectId: tt.expected.ProjectId,
InstanceId: tt.expected.InstanceId,
},
state := &resourceModel{
ProjectId: tt.expected.ProjectId,
InstanceId: tt.expected.InstanceId,
}
err := mapResourceFields(tt.input, state, tt.region)
if !tt.isValid && err == nil {
@ -420,14 +397,14 @@ func TestMapFields(t *testing.T) {
func TestToCreatePayload(t *testing.T) {
tests := []struct {
description string
input *ResourceModel
input *resourceModel
inputRoles *[]string
expected *postgresflex.CreateUserRequestPayload
isValid bool
}{
{
"default_values",
&ResourceModel{},
&resourceModel{},
&[]string{},
&postgresflex.CreateUserRequestPayload{
Name: nil,
@ -437,10 +414,8 @@ func TestToCreatePayload(t *testing.T) {
},
{
"simple_values",
&ResourceModel{
UserModel: resource.UserModel{
Name: types.StringValue("username"),
},
&resourceModel{
Name: types.StringValue("username"),
},
&[]string{
"role_1",
@ -457,10 +432,8 @@ func TestToCreatePayload(t *testing.T) {
},
{
"null_fields_and_int_conversions",
&ResourceModel{
UserModel: resource.UserModel{
Name: types.StringNull(),
},
&resourceModel{
Name: types.StringNull(),
},
&[]string{
"",
@ -482,7 +455,7 @@ func TestToCreatePayload(t *testing.T) {
},
{
"nil_roles",
&ResourceModel{},
&resourceModel{},
nil,
nil,
false,
@ -512,14 +485,14 @@ func TestToCreatePayload(t *testing.T) {
func TestToUpdatePayload(t *testing.T) {
tests := []struct {
description string
input *ResourceModel
input *resourceModel
inputRoles *[]string
expected *postgresflex.UpdateUserRequestPayload
isValid bool
}{
{
"default_values",
&ResourceModel{},
&resourceModel{},
&[]string{},
&postgresflex.UpdateUserRequestPayload{
Roles: &[]postgresflex.UserRole{},
@ -528,10 +501,8 @@ func TestToUpdatePayload(t *testing.T) {
},
{
"default_values",
&ResourceModel{
UserModel: resource.UserModel{
Name: types.StringValue("username"),
},
&resourceModel{
Name: types.StringValue("username"),
},
&[]string{
"role_1",
@ -548,10 +519,8 @@ func TestToUpdatePayload(t *testing.T) {
},
{
"null_fields_and_int_conversions",
&ResourceModel{
UserModel: resource.UserModel{
Name: types.StringNull(),
},
&resourceModel{
Name: types.StringNull(),
},
&[]string{
"",
@ -572,7 +541,7 @@ func TestToUpdatePayload(t *testing.T) {
},
{
"nil_roles",
&ResourceModel{},
&resourceModel{},
nil,
nil,
false,

View file

@ -41,12 +41,14 @@ var (
extractErrorMessage = "Extracting identity data: %v"
)
// ResourceModel represents the Terraform resource state for a PostgreSQL Flex user.
type ResourceModel struct {
postgresflexalpha.UserModel
TerraformID types.String `tfsdk:"id"`
// NewUserResource is a helper function to simplify the provider implementation.
func NewUserResource() resource.Resource {
return &userResource{}
}
// resourceModel represents the Terraform resource state for a PostgreSQL Flex user.
type resourceModel = postgresflexalpha.UserModel
// UserResourceIdentityModel describes the resource's identity attributes.
type UserResourceIdentityModel struct {
ProjectID types.String `tfsdk:"project_id"`
@ -55,11 +57,6 @@ type UserResourceIdentityModel struct {
UserID types.Int64 `tfsdk:"database_id"`
}
// NewUserResource is a helper function to simplify the provider implementation.
func NewUserResource() resource.Resource {
return &userResource{}
}
// userResource implements the resource handling for a PostgreSQL Flex user.
type userResource struct {
client *postgresflex.APIClient
@ -73,7 +70,7 @@ func (r *userResource) ModifyPlan(
req resource.ModifyPlanRequest,
resp *resource.ModifyPlanResponse,
) { // nolint:gocritic // function signature required by Terraform
var configModel ResourceModel
var configModel resourceModel
// skip initial empty configuration to avoid follow-up errors
if req.Config.Raw.IsNull() {
return
@ -83,7 +80,7 @@ func (r *userResource) ModifyPlan(
return
}
var planModel ResourceModel
var planModel resourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &planModel)...)
if resp.Diagnostics.HasError() {
return
@ -153,7 +150,7 @@ func (r *userResource) Create(
req resource.CreateRequest,
resp *resource.CreateResponse,
) { // nolint:gocritic // function signature required by Terraform
var model ResourceModel
var model resourceModel
diags := req.Plan.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
@ -252,7 +249,7 @@ func (r *userResource) Read(
req resource.ReadRequest,
resp *resource.ReadResponse,
) { // nolint:gocritic // function signature required by Terraform
var model ResourceModel
var model resourceModel
diags := req.State.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
@ -312,7 +309,7 @@ func (r *userResource) Update(
req resource.UpdateRequest,
resp *resource.UpdateResponse,
) { // nolint:gocritic // function signature required by Terraform
var model ResourceModel
var model resourceModel
diags := req.Plan.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
@ -342,7 +339,7 @@ func (r *userResource) Update(
ctx = core.InitProviderContext(ctx)
// Retrieve values from state
var stateModel ResourceModel
var stateModel resourceModel
diags = req.State.Get(ctx, &stateModel)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
@ -414,7 +411,7 @@ func (r *userResource) Delete(
req resource.DeleteRequest,
resp *resource.DeleteResponse,
) { // nolint:gocritic // function signature required by Terraform
var model ResourceModel
var model resourceModel
diags := req.State.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
@ -559,7 +556,7 @@ func (r *userResource) ImportState(
tflog.Info(ctx, "postgresflexalpha user state imported")
}
func mapFields(userResp *postgresflex.GetUserResponse, model *ResourceModel, region string) error {
func mapFields(userResp *postgresflex.GetUserResponse, model *resourceModel, region string) error {
if userResp == nil {
return fmt.Errorf("response is nil")
}
@ -576,9 +573,7 @@ func mapFields(userResp *postgresflex.GetUserResponse, model *ResourceModel, reg
} else {
return fmt.Errorf("user id not present")
}
model.TerraformID = utils.BuildInternalTerraformId(
model.ProjectId.ValueString(), region, model.InstanceId.ValueString(), strconv.FormatInt(userId, 10),
)
model.UserId = types.Int64Value(userId)
model.Name = types.StringPointerValue(user.Name)
@ -602,7 +597,7 @@ func mapFields(userResp *postgresflex.GetUserResponse, model *ResourceModel, reg
// getUserResource refreshes the resource state by calling the API and mapping the response to the model.
// Returns true if the resource state was successfully refreshed, false if the resource does not exist.
func (r *userResource) getUserResource(ctx context.Context, model *ResourceModel, arg *clientArg) (bool, error) {
func (r *userResource) getUserResource(ctx context.Context, model *resourceModel, arg *clientArg) (bool, error) {
if arg.userId > math.MaxInt32 {
return false, errors.New("error in type conversion: int value too large (userId)")
@ -638,7 +633,7 @@ type clientArg struct {
// extractIdentityData extracts essential identifiers from the resource model, falling back to the identity model.
func (r *userResource) extractIdentityData(
model ResourceModel,
model resourceModel,
identity UserResourceIdentityModel,
) (*clientArg, error) {