chore: changed and refactored providers (#36)
## Description
<!-- **Please link some issue here describing what you are trying to achieve.**
In case there is no issue present for your PR, please consider creating one.
At least please give us some description what you are trying to achieve and why your change is needed. -->
relates to #1234
## Checklist
- [ ] Issue was linked above
- [ ] Code format was applied: `make fmt`
- [ ] Examples were added / adjusted (see `examples/` directory)
- [x] Docs are up-to-date: `make generate-docs` (will be checked by CI)
- [ ] Unit tests got implemented or updated
- [ ] Acceptance tests got implemented or updated (see e.g. [here](f5f99d1709/stackit/internal/services/dns/dns_acc_test.go))
- [x] Unit tests are passing: `make test` (will be checked by CI)
- [x] No linter issues: `make lint` (will be checked by CI)
Co-authored-by: Marcel S. Henselin <marcel.henselin@stackit.cloud>
Reviewed-on: #36
Reviewed-by: Marcel_Henselin <marcel.henselin@stackit.cloud>
Co-authored-by: Andre Harms <andre.harms@stackit.cloud>
Co-committed-by: Andre Harms <andre.harms@stackit.cloud>
This commit is contained in:
parent
b1b359f436
commit
de019908d2
70 changed files with 6250 additions and 2608 deletions
|
|
@ -5,18 +5,17 @@ import (
|
|||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
|
||||
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/conversion"
|
||||
postgresflexUtils "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/services/postgresflexalpha/utils"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/core"
|
||||
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/utils"
|
||||
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/validate"
|
||||
|
||||
"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/stackit/internal/conversion"
|
||||
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/core"
|
||||
postgresflexalpha2 "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/services/postgresflexalpha/database/datasources_gen"
|
||||
postgresflexUtils "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/services/postgresflexalpha/utils"
|
||||
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/utils"
|
||||
|
||||
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/pkg_gen/postgresflexalpha"
|
||||
)
|
||||
|
||||
|
|
@ -30,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
|
||||
|
|
@ -66,132 +71,46 @@ func (r *databaseDataSource) Configure(
|
|||
}
|
||||
|
||||
// Schema defines the schema for the data source.
|
||||
func (r *databaseDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "Postgres Flex database resource schema. Must have a `region` specified in the provider configuration.",
|
||||
"id": "Terraform's internal resource ID. It is structured as \"`project_id`,`region`,`instance_id`,`database_id`\".",
|
||||
"database_id": "Database ID.",
|
||||
"instance_id": "ID of the Postgres Flex instance.",
|
||||
"project_id": "STACKIT project ID to which the instance is associated.",
|
||||
"name": "Database name.",
|
||||
"owner": "Username of the database owner.",
|
||||
"region": "The resource region. If not defined, the provider region is used.",
|
||||
func (r *databaseDataSource) Schema(ctx context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
|
||||
s := postgresflexalpha2.DatabaseDataSourceSchema(ctx)
|
||||
s.Attributes["id"] = schema.StringAttribute{
|
||||
Description: "Terraform's internal resource ID. It is structured as \\\"`project_id`,`region`,`instance_id`," +
|
||||
"`database_id`\\\".\",",
|
||||
Computed: true,
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
},
|
||||
"database_id": schema.Int64Attribute{
|
||||
Description: descriptions["database_id"],
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: descriptions["name"],
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthAtLeast(1),
|
||||
},
|
||||
},
|
||||
"owner": schema.StringAttribute{
|
||||
Description: descriptions["owner"],
|
||||
Computed: true,
|
||||
},
|
||||
"region": schema.StringAttribute{
|
||||
// the region cannot be found, so it has to be passed
|
||||
Optional: true,
|
||||
Description: descriptions["region"],
|
||||
},
|
||||
},
|
||||
}
|
||||
resp.Schema = s
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
// Read fetches the data for the data source.
|
||||
func (r *databaseDataSource) Read(
|
||||
ctx context.Context,
|
||||
req datasource.ReadRequest,
|
||||
resp *datasource.ReadResponse,
|
||||
) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
var model dataSourceModel
|
||||
diags := req.Config.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
// validation for exactly one of database_id or name
|
||||
isIdSet := !model.DatabaseId.IsNull() && !model.DatabaseId.IsUnknown()
|
||||
isNameSet := !model.Name.IsNull() && !model.Name.IsUnknown()
|
||||
|
||||
if (isIdSet && isNameSet) || (!isIdSet && !isNameSet) {
|
||||
core.LogAndAddError(
|
||||
ctx, &resp.Diagnostics,
|
||||
"Invalid configuration", "Exactly one of 'database_id' or 'name' must be specified.",
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
databaseId := model.DatabaseId.ValueInt64()
|
||||
region := r.providerData.GetRegionWithOverride(model.Region)
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "database_id", databaseId)
|
||||
ctx = tflog.SetField(ctx, "region", region)
|
||||
|
||||
var databaseResp *postgresflexalpha.ListDatabase
|
||||
var err error
|
||||
|
||||
if isIdSet {
|
||||
databaseId := model.DatabaseId.ValueInt64()
|
||||
ctx = tflog.SetField(ctx, "database_id", databaseId)
|
||||
databaseResp, err = getDatabaseById(ctx, r.client, projectId, region, instanceId, databaseId)
|
||||
} else {
|
||||
databaseName := model.Name.ValueString()
|
||||
ctx = tflog.SetField(ctx, "name", databaseName)
|
||||
databaseResp, err = getDatabaseByName(ctx, r.client, projectId, region, instanceId, databaseName)
|
||||
databaseResp, err := r.getDatabaseByNameOrID(ctx, &model, projectId, region, instanceId, &resp.Diagnostics)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
utils.LogError(
|
||||
ctx,
|
||||
&resp.Diagnostics,
|
||||
err,
|
||||
"Reading database",
|
||||
fmt.Sprintf(
|
||||
"Database with ID %q or instance with ID %q does not exist in project %q.",
|
||||
databaseId,
|
||||
instanceId,
|
||||
projectId,
|
||||
),
|
||||
map[int]string{
|
||||
http.StatusForbidden: fmt.Sprintf("Project with ID %q not found or forbidden access", projectId),
|
||||
},
|
||||
)
|
||||
handleReadError(ctx, &resp.Diagnostics, err, projectId, instanceId)
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
|
|
@ -218,3 +137,60 @@ func (r *databaseDataSource) Read(
|
|||
}
|
||||
tflog.Info(ctx, "Postgres Flex database 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,
|
||||
projectId, region, instanceId string,
|
||||
diags *diag.Diagnostics,
|
||||
) (*postgresflexalpha.ListDatabase, error) {
|
||||
isIdSet := !model.DatabaseId.IsNull() && !model.DatabaseId.IsUnknown()
|
||||
isNameSet := !model.Name.IsNull() && !model.Name.IsUnknown()
|
||||
|
||||
if (isIdSet && isNameSet) || (!isIdSet && !isNameSet) {
|
||||
diags.AddError(
|
||||
"Invalid configuration",
|
||||
"Exactly one of 'id' or 'name' must be specified.",
|
||||
)
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if isIdSet {
|
||||
databaseId := model.DatabaseId.ValueInt64()
|
||||
ctx = tflog.SetField(ctx, "database_id", databaseId)
|
||||
return getDatabaseById(ctx, r.client, projectId, region, instanceId, databaseId)
|
||||
}
|
||||
|
||||
databaseName := model.Name.ValueString()
|
||||
ctx = tflog.SetField(ctx, "name", databaseName)
|
||||
return getDatabaseByName(ctx, r.client, projectId, region, instanceId, databaseName)
|
||||
}
|
||||
|
||||
// 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,69 @@
|
|||
// Code generated by terraform-plugin-framework-generator DO NOT EDIT.
|
||||
|
||||
package postgresflexalpha
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
|
||||
)
|
||||
|
||||
func DatabaseDataSourceSchema(ctx context.Context) schema.Schema {
|
||||
return schema.Schema{
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"database_id": schema.Int64Attribute{
|
||||
Required: true,
|
||||
Description: "The ID of the database.",
|
||||
MarkdownDescription: "The ID of the database.",
|
||||
},
|
||||
"tf_original_api_id": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
Description: "The id of the database.",
|
||||
MarkdownDescription: "The id of the database.",
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Required: true,
|
||||
Description: "The ID of the instance.",
|
||||
MarkdownDescription: "The ID of the instance.",
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Description: "The name of the database.",
|
||||
MarkdownDescription: "The name of the database.",
|
||||
},
|
||||
"owner": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Description: "The owner of the database.",
|
||||
MarkdownDescription: "The owner of the database.",
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Required: true,
|
||||
Description: "The STACKIT project ID.",
|
||||
MarkdownDescription: "The STACKIT project ID.",
|
||||
},
|
||||
"region": schema.StringAttribute{
|
||||
Required: true,
|
||||
Description: "The region which should be addressed",
|
||||
MarkdownDescription: "The region which should be addressed",
|
||||
Validators: []validator.String{
|
||||
stringvalidator.OneOf(
|
||||
"eu01",
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
type DatabaseModel struct {
|
||||
DatabaseId types.Int64 `tfsdk:"database_id"`
|
||||
Id types.Int64 `tfsdk:"tf_original_api_id"`
|
||||
InstanceId types.String `tfsdk:"instance_id"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
Owner types.String `tfsdk:"owner"`
|
||||
ProjectId types.String `tfsdk:"project_id"`
|
||||
Region types.String `tfsdk:"region"`
|
||||
}
|
||||
|
|
@ -3,6 +3,7 @@ package postgresflexalpha
|
|||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
postgresflex "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/pkg_gen/postgresflexalpha"
|
||||
)
|
||||
|
|
@ -79,3 +80,12 @@ func getDatabase(
|
|||
|
||||
return nil, fmt.Errorf("database not found for instance %s", instanceId)
|
||||
}
|
||||
|
||||
// cleanString removes leading and trailing quotes which are sometimes returned by the API.
|
||||
func cleanString(s *string) *string {
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
res := strings.Trim(*s, "\"")
|
||||
return &res
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import (
|
|||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
postgresflex "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/pkg_gen/postgresflexalpha"
|
||||
)
|
||||
|
|
@ -12,8 +13,8 @@ type mockRequest struct {
|
|||
executeFunc func() (*postgresflex.ListDatabasesResponse, error)
|
||||
}
|
||||
|
||||
func (m *mockRequest) Page(_ int64) postgresflex.ApiListDatabasesRequestRequest { return m }
|
||||
func (m *mockRequest) Size(_ int64) postgresflex.ApiListDatabasesRequestRequest { return m }
|
||||
func (m *mockRequest) Page(_ int32) postgresflex.ApiListDatabasesRequestRequest { return m }
|
||||
func (m *mockRequest) Size(_ int32) postgresflex.ApiListDatabasesRequestRequest { return m }
|
||||
func (m *mockRequest) Sort(_ postgresflex.DatabaseSort) postgresflex.ApiListDatabasesRequestRequest {
|
||||
return m
|
||||
}
|
||||
|
|
@ -176,21 +177,56 @@ func TestGetDatabase(t *testing.T) {
|
|||
}
|
||||
|
||||
if (errDB != nil) != tt.wantErr {
|
||||
t.Errorf("getDatabase() error = %v, wantErr %v", errDB, tt.wantErr)
|
||||
t.Errorf("getDatabaseByNameOrID() error = %v, wantErr %v", errDB, tt.wantErr)
|
||||
return
|
||||
}
|
||||
if !tt.wantErr && tt.wantDbName != "" && actual != nil {
|
||||
if *actual.Name != tt.wantDbName {
|
||||
t.Errorf("getDatabase() got name = %v, want %v", *actual.Name, tt.wantDbName)
|
||||
t.Errorf("getDatabaseByNameOrID() got name = %v, want %v", *actual.Name, tt.wantDbName)
|
||||
}
|
||||
}
|
||||
|
||||
if !tt.wantErr && tt.wantDbId != 0 && actual != nil {
|
||||
if *actual.Id != tt.wantDbId {
|
||||
t.Errorf("getDatabase() got id = %v, want %v", *actual.Id, tt.wantDbId)
|
||||
t.Errorf("getDatabaseByNameOrID() got id = %v, want %v", *actual.Id, tt.wantDbId)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanString(t *testing.T) {
|
||||
testcases := []struct {
|
||||
name string
|
||||
given *string
|
||||
expected *string
|
||||
}{
|
||||
{
|
||||
name: "should remove quotes",
|
||||
given: utils.Ptr("\"quoted\""),
|
||||
expected: utils.Ptr("quoted"),
|
||||
},
|
||||
{
|
||||
name: "should handle nil",
|
||||
given: nil,
|
||||
expected: nil,
|
||||
},
|
||||
{
|
||||
name: "should not change unquoted string",
|
||||
given: utils.Ptr("unquoted"),
|
||||
expected: utils.Ptr("unquoted"),
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testcases {
|
||||
t.Run(
|
||||
tc.name, func(t *testing.T) {
|
||||
actual := cleanString(tc.given)
|
||||
if diff := cmp.Diff(tc.expected, actual); diff != "" {
|
||||
t.Errorf("string mismatch (-want +got):\n%s", diff)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,92 @@
|
|||
package postgresflexalpha
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
||||
"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/utils"
|
||||
)
|
||||
|
||||
// mapFields maps fields from a ListDatabase API response to a resourceModel for the data source.
|
||||
func mapFields(
|
||||
source *postgresflexalpha.ListDatabase,
|
||||
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.DatabaseId.ValueInt64() != 0 {
|
||||
databaseId = model.DatabaseId.ValueInt64()
|
||||
} else if source.Id != nil {
|
||||
databaseId = *source.Id
|
||||
} else {
|
||||
return fmt.Errorf("database id not present")
|
||||
}
|
||||
|
||||
model.Id = types.Int64Value(databaseId)
|
||||
model.DatabaseId = types.Int64Value(databaseId)
|
||||
model.Name = types.StringValue(source.GetName())
|
||||
model.Owner = types.StringPointerValue(cleanString(source.Owner))
|
||||
model.Region = types.StringValue(region)
|
||||
model.ProjectId = types.StringValue(model.ProjectId.ValueString())
|
||||
model.InstanceId = types.StringValue(model.InstanceId.ValueString())
|
||||
model.TerraformID = utils.BuildInternalTerraformId(
|
||||
model.ProjectId.ValueString(),
|
||||
region,
|
||||
model.InstanceId.ValueString(),
|
||||
strconv.FormatInt(databaseId, 10),
|
||||
)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// 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")
|
||||
}
|
||||
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.DatabaseId = types.Int64Value(databaseId)
|
||||
model.Name = types.StringValue(source.GetName())
|
||||
model.Owner = types.StringPointerValue(cleanString(source.Owner))
|
||||
return nil
|
||||
}
|
||||
|
||||
// toCreatePayload converts the resource model to an API create payload.
|
||||
func toCreatePayload(model *resourceModel) (*postgresflexalpha.CreateDatabaseRequestPayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
|
||||
return &postgresflexalpha.CreateDatabaseRequestPayload{
|
||||
Name: model.Name.ValueStringPointer(),
|
||||
Owner: model.Owner.ValueStringPointer(),
|
||||
}, nil
|
||||
}
|
||||
|
|
@ -0,0 +1,240 @@
|
|||
package postgresflexalpha
|
||||
|
||||
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/postgresflexalpha"
|
||||
datasource "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/services/postgresflexalpha/database/datasources_gen"
|
||||
)
|
||||
|
||||
func TestMapFields(t *testing.T) {
|
||||
type given struct {
|
||||
source *postgresflexalpha.ListDatabase
|
||||
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: &postgresflexalpha.ListDatabase{
|
||||
Id: utils.Ptr(int64(1)),
|
||||
Name: utils.Ptr("my-db"),
|
||||
Owner: utils.Ptr("\"my-owner\""),
|
||||
},
|
||||
model: &dataSourceModel{},
|
||||
region: "eu01",
|
||||
},
|
||||
expected: expected{
|
||||
model: &dataSourceModel{
|
||||
DatabaseModel: datasource.DatabaseModel{
|
||||
Id: types.Int64Value(1),
|
||||
Name: types.StringValue("my-db"),
|
||||
Owner: types.StringValue("my-owner"),
|
||||
Region: types.StringValue("eu01"),
|
||||
DatabaseId: types.Int64Value(1),
|
||||
InstanceId: types.StringValue("my-instance"),
|
||||
ProjectId: types.StringValue("my-project"),
|
||||
},
|
||||
TerraformID: types.StringValue("my-project,eu01,my-instance,1"),
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "should preserve existing model ID",
|
||||
given: given{
|
||||
source: &postgresflexalpha.ListDatabase{
|
||||
Id: utils.Ptr(int64(1)),
|
||||
Name: utils.Ptr("my-db"),
|
||||
},
|
||||
model: &dataSourceModel{
|
||||
DatabaseModel: datasource.DatabaseModel{
|
||||
Id: types.Int64Value(1),
|
||||
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"),
|
||||
Owner: types.StringNull(), DatabaseId: types.Int64Value(1),
|
||||
Region: types.StringValue("eu01"),
|
||||
InstanceId: types.StringValue("my-instance"),
|
||||
ProjectId: types.StringValue("my-project"),
|
||||
},
|
||||
TerraformID: types.StringValue("my-project,eu01,my-instance,1"),
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
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: &postgresflexalpha.ListDatabase{Id: nil},
|
||||
model: &dataSourceModel{},
|
||||
},
|
||||
expected: expected{err: true},
|
||||
},
|
||||
{
|
||||
name: "should fail on nil model",
|
||||
given: given{
|
||||
source: &postgresflexalpha.ListDatabase{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 *postgresflexalpha.ListDatabase
|
||||
model *resourceModel
|
||||
}
|
||||
type expected struct {
|
||||
model *resourceModel
|
||||
err bool
|
||||
}
|
||||
|
||||
testcases := []struct {
|
||||
name string
|
||||
given given
|
||||
expected expected
|
||||
}{
|
||||
{
|
||||
name: "should map fields correctly",
|
||||
given: given{
|
||||
source: &postgresflexalpha.ListDatabase{
|
||||
Id: utils.Ptr(int64(1)),
|
||||
Name: utils.Ptr("my-db"),
|
||||
Owner: utils.Ptr("\"my-owner\""),
|
||||
},
|
||||
model: &resourceModel{},
|
||||
},
|
||||
expected: expected{
|
||||
model: &resourceModel{
|
||||
Id: types.Int64Value(1),
|
||||
Name: types.StringValue("my-db"),
|
||||
Owner: types.StringValue("my-owner"),
|
||||
DatabaseId: types.Int64Value(1),
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
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)
|
||||
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 *postgresflexalpha.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: &postgresflexalpha.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)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
fields:
|
||||
- name: 'id'
|
||||
modifiers:
|
||||
- 'UseStateForUnknown'
|
||||
|
||||
- name: 'database_id'
|
||||
modifiers:
|
||||
- 'UseStateForUnknown'
|
||||
validators:
|
||||
- validate.NoSeparator
|
||||
- validate.UUID
|
||||
|
||||
- name: 'instance_id'
|
||||
validators:
|
||||
- validate.NoSeparator
|
||||
- validate.UUID
|
||||
modifiers:
|
||||
- 'RequiresReplace'
|
||||
- 'UseStateForUnknown'
|
||||
|
||||
- name: 'project_id'
|
||||
modifiers:
|
||||
- 'RequiresReplace'
|
||||
- 'UseStateForUnknown'
|
||||
validators:
|
||||
- validate.NoSeparator
|
||||
- validate.UUID
|
||||
|
||||
- name: 'name'
|
||||
validators:
|
||||
- validate.NoSeparator
|
||||
|
||||
- name: 'region'
|
||||
modifiers:
|
||||
- 'RequiresReplace'
|
||||
|
|
@ -2,70 +2,73 @@ package postgresflexalpha
|
|||
|
||||
import (
|
||||
"context"
|
||||
_ "embed"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/path"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/int64planmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/identityschema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/oapierror"
|
||||
"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"
|
||||
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/core"
|
||||
postgresflexalpha2 "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/services/postgresflexalpha/database/resources_gen"
|
||||
postgresflexUtils "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/services/postgresflexalpha/utils"
|
||||
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/utils"
|
||||
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/validate"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
_ resource.Resource = &databaseResource{}
|
||||
_ resource.ResourceWithConfigure = &databaseResource{}
|
||||
_ resource.ResourceWithImportState = &databaseResource{}
|
||||
_ resource.ResourceWithModifyPlan = &databaseResource{}
|
||||
)
|
||||
_ resource.ResourceWithIdentity = &databaseResource{}
|
||||
|
||||
type Model struct {
|
||||
Id types.String `tfsdk:"id"` // needed by TF
|
||||
DatabaseId types.Int64 `tfsdk:"database_id"`
|
||||
InstanceId types.String `tfsdk:"instance_id"`
|
||||
ProjectId types.String `tfsdk:"project_id"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
Owner types.String `tfsdk:"owner"`
|
||||
Region types.String `tfsdk:"region"`
|
||||
}
|
||||
// Define errors
|
||||
errDatabaseNotFound = errors.New("database not found")
|
||||
|
||||
// Error message constants
|
||||
extractErrorSummary = "extracting failed"
|
||||
extractErrorMessage = "Extracting identity data: %v"
|
||||
)
|
||||
|
||||
// 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 {
|
||||
ProjectID types.String `tfsdk:"project_id"`
|
||||
Region types.String `tfsdk:"region"`
|
||||
InstanceID types.String `tfsdk:"instance_id"`
|
||||
DatabaseID types.Int64 `tfsdk:"database_id"`
|
||||
}
|
||||
|
||||
// databaseResource is the resource implementation.
|
||||
type databaseResource struct {
|
||||
client *postgresflexalpha.APIClient
|
||||
providerData core.ProviderData
|
||||
}
|
||||
|
||||
// ModifyPlan implements resource.ResourceWithModifyPlan.
|
||||
// Use the modifier to set the effective region in the current plan.
|
||||
// ModifyPlan adjusts the plan to set the correct region.
|
||||
func (r *databaseResource) ModifyPlan(
|
||||
ctx context.Context,
|
||||
req resource.ModifyPlanRequest,
|
||||
resp *resource.ModifyPlanResponse,
|
||||
) { // nolint:gocritic // function signature required by Terraform
|
||||
var configModel Model
|
||||
var configModel resourceModel
|
||||
// skip initial empty configuration to avoid follow-up errors
|
||||
if req.Config.Raw.IsNull() {
|
||||
return
|
||||
|
|
@ -75,7 +78,7 @@ func (r *databaseResource) ModifyPlan(
|
|||
return
|
||||
}
|
||||
|
||||
var planModel Model
|
||||
var planModel resourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &planModel)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
|
|
@ -117,85 +120,46 @@ func (r *databaseResource) Configure(
|
|||
tflog.Info(ctx, "Postgres Flex database client configured")
|
||||
}
|
||||
|
||||
//go:embed planModifiers.yaml
|
||||
var modifiersFileByte []byte
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *databaseResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "Postgres Flex database resource schema. Must have a `region` specified in the provider configuration.",
|
||||
"id": "Terraform's internal resource ID. It is structured as \"`project_id`,`region`,`instance_id`,`database_id`\".",
|
||||
"database_id": "Database ID.",
|
||||
"instance_id": "ID of the Postgres Flex instance.",
|
||||
"project_id": "STACKIT project ID to which the instance is associated.",
|
||||
"name": "Database name.",
|
||||
"owner": "Username of the database owner.",
|
||||
"region": "The resource region. If not defined, the provider region is used.",
|
||||
func (r *databaseResource) Schema(ctx context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
s := postgresflexalpha2.DatabaseResourceSchema(ctx)
|
||||
|
||||
fields, err := utils.ReadModifiersConfig(modifiersFileByte)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("error during read modifiers config file", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
err = utils.AddPlanModifiersToResourceSchema(fields, &s)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("error adding plan modifiers", err.Error())
|
||||
return
|
||||
}
|
||||
resp.Schema = s
|
||||
}
|
||||
|
||||
// IdentitySchema defines the schema for the resource's identity attributes.
|
||||
func (r *databaseResource) IdentitySchema(
|
||||
_ context.Context,
|
||||
_ resource.IdentitySchemaRequest,
|
||||
response *resource.IdentitySchemaResponse,
|
||||
) {
|
||||
response.IdentitySchema = identityschema.Schema{
|
||||
Attributes: map[string]identityschema.Attribute{
|
||||
"project_id": identityschema.StringAttribute{
|
||||
RequiredForImport: true,
|
||||
},
|
||||
"database_id": schema.Int64Attribute{
|
||||
Description: descriptions["database_id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.Int64{
|
||||
int64planmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.Int64{},
|
||||
"region": identityschema.StringAttribute{
|
||||
RequiredForImport: true,
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
"instance_id": identityschema.StringAttribute{
|
||||
RequiredForImport: true,
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: descriptions["name"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{},
|
||||
Validators: []validator.String{
|
||||
stringvalidator.RegexMatches(
|
||||
regexp.MustCompile("^[a-z]([a-z0-9]*)?$"),
|
||||
"must start with a letter, must have lower case letters or numbers",
|
||||
),
|
||||
},
|
||||
},
|
||||
"owner": schema.StringAttribute{
|
||||
Description: descriptions["owner"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{},
|
||||
},
|
||||
"region": schema.StringAttribute{
|
||||
Optional: true,
|
||||
// must be computed to allow for storing the override value from the provider
|
||||
Computed: true,
|
||||
Description: descriptions["region"],
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
"database_id": identityschema.Int64Attribute{
|
||||
RequiredForImport: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
|
@ -207,18 +171,26 @@ func (r *databaseResource) Create(
|
|||
req resource.CreateRequest,
|
||||
resp *resource.CreateResponse,
|
||||
) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
var model resourceModel
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
// Read identity data
|
||||
var identityData DatabaseResourceIdentityModel
|
||||
resp.Diagnostics.Append(req.Identity.Get(ctx, &identityData)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
region := model.Region.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
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)
|
||||
|
|
@ -272,7 +244,7 @@ func (r *databaseResource) Create(
|
|||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(database, &model, region)
|
||||
err = mapResourceFields(database, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(
|
||||
ctx,
|
||||
|
|
@ -282,9 +254,21 @@ func (r *databaseResource) Create(
|
|||
)
|
||||
return
|
||||
}
|
||||
|
||||
// Set data returned by API in identity
|
||||
identity := DatabaseResourceIdentityModel{
|
||||
ProjectID: types.StringValue(projectId),
|
||||
Region: types.StringValue(region),
|
||||
InstanceID: types.StringValue(instanceId),
|
||||
DatabaseID: types.Int64Value(databaseId),
|
||||
}
|
||||
resp.Diagnostics.Append(resp.Identity.Set(ctx, identity)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
// Set state to fully populated data
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, model)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
|
@ -297,23 +281,36 @@ func (r *databaseResource) Read(
|
|||
req resource.ReadRequest,
|
||||
resp *resource.ReadResponse,
|
||||
) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
var model resourceModel
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
// Read identity data
|
||||
var identityData DatabaseResourceIdentityModel
|
||||
resp.Diagnostics.Append(req.Identity.Get(ctx, &identityData)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
databaseId := model.DatabaseId.ValueInt64()
|
||||
region := r.providerData.GetRegionWithOverride(model.Region)
|
||||
projectId, instanceId, region, databaseId, 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, "database_id", databaseId)
|
||||
ctx = tflog.SetField(ctx, "region", region)
|
||||
ctx = tflog.SetField(ctx, "database_id", databaseId)
|
||||
|
||||
databaseResp, err := getDatabaseById(ctx, r.client, projectId, region, instanceId, databaseId)
|
||||
if err != nil {
|
||||
|
|
@ -329,7 +326,7 @@ func (r *databaseResource) Read(
|
|||
ctx = core.LogResponse(ctx)
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(databaseResp, &model, region)
|
||||
err = mapResourceFields(databaseResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(
|
||||
ctx,
|
||||
|
|
@ -355,32 +352,45 @@ func (r *databaseResource) Update(
|
|||
req resource.UpdateRequest,
|
||||
resp *resource.UpdateResponse,
|
||||
) {
|
||||
var model Model
|
||||
var model resourceModel
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
// Read identity data
|
||||
var identityData DatabaseResourceIdentityModel
|
||||
resp.Diagnostics.Append(req.Identity.Get(ctx, &identityData)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
databaseId64 := model.DatabaseId.ValueInt64()
|
||||
projectId, instanceId, region, databaseId64, errExt := r.extractIdentityData(model, identityData)
|
||||
if errExt != nil {
|
||||
core.LogAndAddError(
|
||||
ctx,
|
||||
&resp.Diagnostics,
|
||||
extractErrorSummary,
|
||||
fmt.Sprintf(extractErrorMessage, errExt),
|
||||
)
|
||||
}
|
||||
|
||||
if databaseId64 > math.MaxInt32 {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error in type conversion", "int value too large (databaseId)")
|
||||
return
|
||||
}
|
||||
databaseId := int32(databaseId64)
|
||||
|
||||
region := model.Region.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "database_id", databaseId)
|
||||
ctx = tflog.SetField(ctx, "region", region)
|
||||
ctx = tflog.SetField(ctx, "database_id", databaseId)
|
||||
|
||||
// Retrieve values from state
|
||||
var stateModel Model
|
||||
var stateModel resourceModel
|
||||
diags = req.State.Get(ctx, &stateModel)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
|
|
@ -420,7 +430,7 @@ func (r *databaseResource) Update(
|
|||
ctx = core.LogResponse(ctx)
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFieldsUpdatePartially(res, &model, region)
|
||||
err = mapResourceFields(res.Database, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(
|
||||
ctx,
|
||||
|
|
@ -445,29 +455,41 @@ func (r *databaseResource) Delete(
|
|||
req resource.DeleteRequest,
|
||||
resp *resource.DeleteResponse,
|
||||
) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
var model resourceModel
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
// Read identity data
|
||||
var identityData DatabaseResourceIdentityModel
|
||||
resp.Diagnostics.Append(req.Identity.Get(ctx, &identityData)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
databaseId64 := model.DatabaseId.ValueInt64()
|
||||
projectId, instanceId, region, databaseId64, errExt := r.extractIdentityData(model, identityData)
|
||||
if errExt != nil {
|
||||
core.LogAndAddError(
|
||||
ctx,
|
||||
&resp.Diagnostics,
|
||||
extractErrorSummary,
|
||||
fmt.Sprintf(extractErrorMessage, errExt),
|
||||
)
|
||||
}
|
||||
|
||||
if databaseId64 > math.MaxInt32 {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error in type conversion", "int value too large (databaseId)")
|
||||
return
|
||||
}
|
||||
databaseId := int32(databaseId64)
|
||||
region := model.Region.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "database_id", databaseId)
|
||||
ctx = tflog.SetField(ctx, "region", region)
|
||||
ctx = tflog.SetField(ctx, "database_id", databaseId)
|
||||
|
||||
// Delete existing record set
|
||||
err := r.client.DeleteDatabaseRequestExecute(ctx, projectId, region, instanceId, databaseId)
|
||||
|
|
@ -481,95 +503,118 @@ func (r *databaseResource) Delete(
|
|||
}
|
||||
|
||||
// ImportState imports a resource into the Terraform state on success.
|
||||
// The expected format of the resource import identifier is: project_id,zone_id,record_set_id
|
||||
// The expected import identifier format is: [project_id],[region],[instance_id],[database_id]
|
||||
func (r *databaseResource) ImportState(
|
||||
ctx context.Context,
|
||||
req resource.ImportStateRequest,
|
||||
resp *resource.ImportStateResponse,
|
||||
) {
|
||||
idParts := strings.Split(req.ID, core.Separator)
|
||||
if len(idParts) != 4 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" || idParts[3] == "" {
|
||||
core.LogAndAddError(
|
||||
ctx, &resp.Diagnostics,
|
||||
"Error importing database",
|
||||
fmt.Sprintf(
|
||||
"Expected import identifier with format [project_id],[region],[instance_id],[database_id], got %q",
|
||||
req.ID,
|
||||
),
|
||||
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
|
||||
if req.ID != "" {
|
||||
|
||||
idParts := strings.Split(req.ID, core.Separator)
|
||||
|
||||
if len(idParts) != 4 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" || idParts[3] == "" {
|
||||
core.LogAndAddError(
|
||||
ctx, &resp.Diagnostics,
|
||||
"Error importing database",
|
||||
fmt.Sprintf(
|
||||
"Expected import identifier with format [project_id],[region],[instance_id],[database_id], got %q",
|
||||
req.ID,
|
||||
),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
databaseId, err := strconv.ParseInt(idParts[3], 10, 64)
|
||||
if err != nil {
|
||||
core.LogAndAddError(
|
||||
ctx,
|
||||
&resp.Diagnostics,
|
||||
"Error importing database",
|
||||
fmt.Sprintf("Invalid database_id format: %q. It must be a valid integer.", idParts[3]),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), idParts[1])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[2])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("database_id"), databaseId)...)
|
||||
|
||||
core.LogAndAddWarning(
|
||||
ctx,
|
||||
&resp.Diagnostics,
|
||||
"Postgresflex database imported with empty password",
|
||||
"The database password is not imported as it is only available upon creation of a new database. The password field will be empty.",
|
||||
)
|
||||
|
||||
tflog.Info(ctx, "Postgres Flex database state imported")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), idParts[1])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[2])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("database_id"), idParts[3])...)
|
||||
core.LogAndAddWarning(
|
||||
ctx,
|
||||
&resp.Diagnostics,
|
||||
"Postgresflex database imported with empty password",
|
||||
"The database password is not imported as it is only available upon creation of a new database. The password field will be empty.",
|
||||
)
|
||||
// If no ID is provided, attempt to read identity attributes from the import configuration
|
||||
var identityData DatabaseResourceIdentityModel
|
||||
resp.Diagnostics.Append(req.Identity.Get(ctx, &identityData)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
projectId := identityData.ProjectID.ValueString()
|
||||
region := identityData.Region.ValueString()
|
||||
instanceId := identityData.InstanceID.ValueString()
|
||||
databaseId := identityData.DatabaseID.ValueInt64()
|
||||
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), projectId)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), region)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), instanceId)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("database_id"), databaseId)...)
|
||||
|
||||
tflog.Info(ctx, "Postgres Flex database state imported")
|
||||
}
|
||||
|
||||
func mapFields(resp *postgresflexalpha.ListDatabase, model *Model, region string) error {
|
||||
if resp == nil {
|
||||
return fmt.Errorf("response is nil")
|
||||
}
|
||||
if resp.Id == nil || *resp.Id == 0 {
|
||||
return fmt.Errorf("id not present")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
|
||||
var databaseId int64
|
||||
if model.DatabaseId.ValueInt64() != 0 {
|
||||
// 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 string, databaseId int64, err error) {
|
||||
if !model.DatabaseId.IsNull() && !model.DatabaseId.IsUnknown() {
|
||||
databaseId = model.DatabaseId.ValueInt64()
|
||||
} else if resp.Id != nil {
|
||||
databaseId = *resp.Id
|
||||
} else {
|
||||
return fmt.Errorf("database id not present")
|
||||
}
|
||||
model.Id = utils.BuildInternalTerraformId(
|
||||
model.ProjectId.ValueString(), region, model.InstanceId.ValueString(), strconv.FormatInt(databaseId, 10),
|
||||
)
|
||||
model.DatabaseId = types.Int64Value(databaseId)
|
||||
model.Name = types.StringPointerValue(resp.Name)
|
||||
model.Region = types.StringValue(region)
|
||||
model.Owner = types.StringPointerValue(cleanString(resp.Owner))
|
||||
return nil
|
||||
}
|
||||
|
||||
func mapFieldsUpdatePartially(
|
||||
res *postgresflexalpha.UpdateDatabasePartiallyResponse,
|
||||
model *Model,
|
||||
region string,
|
||||
) error {
|
||||
if res == nil {
|
||||
return fmt.Errorf("response is nil")
|
||||
}
|
||||
return mapFields(res.Database, model, region)
|
||||
}
|
||||
|
||||
func cleanString(s *string) *string {
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
res := strings.Trim(*s, "\"")
|
||||
return &res
|
||||
}
|
||||
|
||||
func toCreatePayload(model *Model) (*postgresflexalpha.CreateDatabaseRequestPayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
if identity.DatabaseID.IsNull() || identity.DatabaseID.IsUnknown() {
|
||||
return "", "", "", 0, fmt.Errorf("database_id not found in config")
|
||||
}
|
||||
databaseId = identity.DatabaseID.ValueInt64()
|
||||
}
|
||||
|
||||
return &postgresflexalpha.CreateDatabaseRequestPayload{
|
||||
Name: model.Name.ValueStringPointer(),
|
||||
Owner: model.Owner.ValueStringPointer(),
|
||||
}, nil
|
||||
}
|
||||
if !model.ProjectId.IsNull() && !model.ProjectId.IsUnknown() {
|
||||
projectId = model.ProjectId.ValueString()
|
||||
} else {
|
||||
if identity.ProjectID.IsNull() || identity.ProjectID.IsUnknown() {
|
||||
return "", "", "", 0, fmt.Errorf("project_id not found in config")
|
||||
}
|
||||
projectId = identity.ProjectID.ValueString()
|
||||
}
|
||||
|
||||
var errDatabaseNotFound = errors.New("database not found")
|
||||
if !model.Region.IsNull() && !model.Region.IsUnknown() {
|
||||
region = r.providerData.GetRegionWithOverride(model.Region)
|
||||
} else {
|
||||
if identity.Region.IsNull() || identity.Region.IsUnknown() {
|
||||
return "", "", "", 0, 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 "", "", "", 0, fmt.Errorf("instance_id not found in config")
|
||||
}
|
||||
instanceId = identity.InstanceID.ValueString()
|
||||
}
|
||||
return projectId, region, instanceId, databaseId, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,232 +0,0 @@
|
|||
package postgresflexalpha
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
postgresflex "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/pkg_gen/postgresflexalpha"
|
||||
)
|
||||
|
||||
func TestMapFields(t *testing.T) {
|
||||
const testRegion = "region"
|
||||
tests := []struct {
|
||||
description string
|
||||
input *postgresflex.ListDatabase
|
||||
region string
|
||||
expected Model
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&postgresflex.ListDatabase{
|
||||
Id: utils.Ptr(int64(1)),
|
||||
},
|
||||
testRegion,
|
||||
Model{
|
||||
Id: types.StringValue("pid,region,iid,1"),
|
||||
DatabaseId: types.Int64Value(int64(1)),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Name: types.StringNull(),
|
||||
Owner: types.StringNull(),
|
||||
Region: types.StringValue(testRegion),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&postgresflex.ListDatabase{
|
||||
Id: utils.Ptr(int64(1)),
|
||||
Name: utils.Ptr("dbname"),
|
||||
Owner: utils.Ptr("username"),
|
||||
},
|
||||
testRegion,
|
||||
Model{
|
||||
Id: types.StringValue("pid,region,iid,1"),
|
||||
DatabaseId: types.Int64Value(int64(1)),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Name: types.StringValue("dbname"),
|
||||
Owner: types.StringValue("username"),
|
||||
Region: types.StringValue(testRegion),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&postgresflex.ListDatabase{
|
||||
Id: utils.Ptr(int64(1)),
|
||||
Name: utils.Ptr(""),
|
||||
Owner: utils.Ptr(""),
|
||||
},
|
||||
testRegion,
|
||||
Model{
|
||||
Id: types.StringValue("pid,region,iid,1"),
|
||||
DatabaseId: types.Int64Value(int64(1)),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Name: types.StringValue(""),
|
||||
Owner: types.StringValue(""),
|
||||
Region: types.StringValue(testRegion),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
testRegion,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"empty_response",
|
||||
&postgresflex.ListDatabase{},
|
||||
testRegion,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&postgresflex.ListDatabase{
|
||||
Id: utils.Ptr(int64(0)),
|
||||
Name: utils.Ptr("dbname"),
|
||||
Owner: utils.Ptr("username"),
|
||||
},
|
||||
testRegion,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(
|
||||
tt.description, func(t *testing.T) {
|
||||
state := &Model{
|
||||
ProjectId: tt.expected.ProjectId,
|
||||
InstanceId: tt.expected.InstanceId,
|
||||
}
|
||||
err := mapFields(tt.input, state, tt.region)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(state, &tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestToCreatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
expected *postgresflex.CreateDatabaseRequestPayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&Model{
|
||||
Name: types.StringValue("dbname"),
|
||||
Owner: types.StringValue("username"),
|
||||
},
|
||||
&postgresflex.CreateDatabaseRequestPayload{
|
||||
Name: utils.Ptr("dbname"),
|
||||
Owner: utils.Ptr("username"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields",
|
||||
&Model{
|
||||
Name: types.StringNull(),
|
||||
Owner: types.StringNull(),
|
||||
},
|
||||
&postgresflex.CreateDatabaseRequestPayload{
|
||||
Name: nil,
|
||||
Owner: nil,
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(
|
||||
tt.description, func(t *testing.T) {
|
||||
output, err := toCreatePayload(tt.input)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(output, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_cleanString(t *testing.T) {
|
||||
type args struct {
|
||||
s *string
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
want *string
|
||||
}{
|
||||
{
|
||||
name: "simple_value",
|
||||
args: args{
|
||||
s: utils.Ptr("mytest"),
|
||||
},
|
||||
want: utils.Ptr("mytest"),
|
||||
},
|
||||
{
|
||||
name: "simple_value_with_quotes",
|
||||
args: args{
|
||||
s: utils.Ptr("\"mytest\""),
|
||||
},
|
||||
want: utils.Ptr("mytest"),
|
||||
},
|
||||
{
|
||||
name: "simple_values_with_quotes",
|
||||
args: args{
|
||||
s: utils.Ptr("\"my test here\""),
|
||||
},
|
||||
want: utils.Ptr("my test here"),
|
||||
},
|
||||
{
|
||||
name: "simple_values",
|
||||
args: args{
|
||||
s: utils.Ptr("my test here"),
|
||||
},
|
||||
want: utils.Ptr("my test here"),
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := cleanString(tt.args.s); !reflect.DeepEqual(got, tt.want) {
|
||||
t.Errorf("cleanString() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -4,6 +4,8 @@ package postgresflexalpha
|
|||
|
||||
import (
|
||||
"context"
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
|
||||
|
|
@ -12,11 +14,23 @@ import (
|
|||
func DatabaseResourceSchema(ctx context.Context) schema.Schema {
|
||||
return schema.Schema{
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"database_id": schema.Int64Attribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
Description: "The ID of the database.",
|
||||
MarkdownDescription: "The ID of the database.",
|
||||
},
|
||||
"id": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
Description: "The id of the database.",
|
||||
MarkdownDescription: "The id of the database.",
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
Description: "The ID of the instance.",
|
||||
MarkdownDescription: "The ID of the instance.",
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Required: true,
|
||||
Description: "The name of the database.",
|
||||
|
|
@ -28,12 +42,33 @@ func DatabaseResourceSchema(ctx context.Context) schema.Schema {
|
|||
Description: "The owner of the database.",
|
||||
MarkdownDescription: "The owner of the database.",
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
Description: "The STACKIT project ID.",
|
||||
MarkdownDescription: "The STACKIT project ID.",
|
||||
},
|
||||
"region": schema.StringAttribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
Description: "The region which should be addressed",
|
||||
MarkdownDescription: "The region which should be addressed",
|
||||
Validators: []validator.String{
|
||||
stringvalidator.OneOf(
|
||||
"eu01",
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
type DatabaseModel struct {
|
||||
Id types.Int64 `tfsdk:"id"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
Owner types.String `tfsdk:"owner"`
|
||||
DatabaseId types.Int64 `tfsdk:"database_id"`
|
||||
Id types.Int64 `tfsdk:"id"`
|
||||
InstanceId types.String `tfsdk:"instance_id"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
Owner types.String `tfsdk:"owner"`
|
||||
ProjectId types.String `tfsdk:"project_id"`
|
||||
Region types.String `tfsdk:"region"`
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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)...)
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ func FlavorsDataSourceSchema(ctx context.Context) schema.Schema {
|
|||
Description: "The flavor description.",
|
||||
MarkdownDescription: "The flavor description.",
|
||||
},
|
||||
"id": schema.StringAttribute{
|
||||
"tf_original_api_id": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Description: "The id of the instance flavor.",
|
||||
MarkdownDescription: "The id of the instance flavor.",
|
||||
|
|
|
|||
|
|
@ -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() {
|
||||
|
|
|
|||
|
|
@ -88,7 +88,7 @@ func InstanceDataSourceSchema(ctx context.Context) schema.Schema {
|
|||
Description: "The id of the instance flavor.",
|
||||
MarkdownDescription: "The id of the instance flavor.",
|
||||
},
|
||||
"id": schema.StringAttribute{
|
||||
"tf_original_api_id": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Description: "The ID of the instance.",
|
||||
MarkdownDescription: "The ID of the instance.",
|
||||
|
|
@ -204,7 +204,7 @@ type InstanceModel struct {
|
|||
ConnectionInfo ConnectionInfoValue `tfsdk:"connection_info"`
|
||||
Encryption EncryptionValue `tfsdk:"encryption"`
|
||||
FlavorId types.String `tfsdk:"flavor_id"`
|
||||
Id types.String `tfsdk:"id"`
|
||||
Id types.String `tfsdk:"tf_original_api_id"`
|
||||
InstanceId types.String `tfsdk:"instance_id"`
|
||||
IsDeletable types.Bool `tfsdk:"is_deletable"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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,8 +77,12 @@ 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
|
||||
var configModel postgresflexalpha.InstanceModel
|
||||
func (r *instanceResource) ModifyPlan(
|
||||
ctx context.Context,
|
||||
req resource.ModifyPlanRequest,
|
||||
resp *resource.ModifyPlanResponse,
|
||||
) { // nolint:gocritic // function signature required by Terraform
|
||||
var configModel resourceModel
|
||||
// skip initial empty configuration to avoid follow-up errors
|
||||
if req.Config.Raw.IsNull() {
|
||||
return
|
||||
|
|
@ -83,7 +92,7 @@ func (r *instanceResource) ModifyPlan(ctx context.Context, req resource.ModifyPl
|
|||
return
|
||||
}
|
||||
|
||||
var planModel postgresflexalpha.InstanceModel
|
||||
var planModel resourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &planModel)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
|
|
@ -135,13 +144,13 @@ var modifiersFileByte []byte
|
|||
// Schema defines the schema for the resource.
|
||||
func (r *instanceResource) Schema(ctx context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
schema := postgresflexalpha.InstanceResourceSchema(ctx)
|
||||
fields, err := postgresflexUtils.ReadModifiersConfig(modifiersFileByte)
|
||||
fields, err := utils.ReadModifiersConfig(modifiersFileByte)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("error during read modifiers config file", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
err = postgresflexUtils.AddPlanModifiersToResourceSchema(fields, &schema)
|
||||
err = utils.AddPlanModifiersToResourceSchema(fields, &schema)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("error adding plan modifiers", err.Error())
|
||||
return
|
||||
|
|
@ -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
|
||||
}
|
||||
|
|
@ -558,25 +630,20 @@ func (r *instanceResource) ImportState(ctx context.Context, req resource.ImportS
|
|||
return
|
||||
}
|
||||
|
||||
// If no ID is provided, attempt to read identity attributes from the import configuration
|
||||
var identityData InstanceResourceIdentityModel
|
||||
resp.Diagnostics.Append(req.Identity.Get(ctx, &identityData)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(
|
||||
resp.State.SetAttribute(
|
||||
ctx,
|
||||
path.Root("id"),
|
||||
utils.BuildInternalTerraformId(
|
||||
identityData.ProjectID.ValueString(),
|
||||
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("region"), identityData.Region.ValueString())...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), identityData.InstanceID.ValueString())...)
|
||||
projectId := identityData.ProjectID.ValueString()
|
||||
region := identityData.Region.ValueString()
|
||||
instanceId := identityData.InstanceID.ValueString()
|
||||
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), projectId)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), region)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), instanceId)...)
|
||||
|
||||
tflog.Info(ctx, "Postgres Flex instance state imported")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -164,6 +164,11 @@ func TestAccPostgresFlexFlexResource(t *testing.T) {
|
|||
Steps: []resource.TestStep{
|
||||
// Creation
|
||||
{
|
||||
// testdata/<Test_Name>
|
||||
// ConfigDirectory: config.TestNameDirectory(),
|
||||
|
||||
// testdata/<Test_Name>/<step_number>
|
||||
// ConfigDirectory: config.TestStepDirectory(),
|
||||
Config: configResources(instanceResource["backup_schedule"], &testutil.Region),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance
|
||||
|
|
|
|||
|
|
@ -5,22 +5,19 @@ import (
|
|||
"fmt"
|
||||
"math"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/diag"
|
||||
postgresflex "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"
|
||||
postgresflexalpha "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/services/postgresflexalpha/user/datasources_gen"
|
||||
postgresflexUtils "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/services/postgresflexalpha/utils"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"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/stackit/internal/core"
|
||||
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/utils"
|
||||
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
|
|
@ -28,25 +25,17 @@ var (
|
|||
_ datasource.DataSource = &userDataSource{}
|
||||
)
|
||||
|
||||
type DataSourceModel struct {
|
||||
Id types.String `tfsdk:"id"` // needed by TF
|
||||
UserId types.Int64 `tfsdk:"user_id"`
|
||||
InstanceId types.String `tfsdk:"instance_id"`
|
||||
ProjectId types.String `tfsdk:"project_id"`
|
||||
Username types.String `tfsdk:"username"`
|
||||
Roles types.Set `tfsdk:"roles"`
|
||||
Host types.String `tfsdk:"host"`
|
||||
Port types.Int64 `tfsdk:"port"`
|
||||
Region types.String `tfsdk:"region"`
|
||||
Status types.String `tfsdk:"status"`
|
||||
ConnectionString types.String `tfsdk:"connection_string"`
|
||||
}
|
||||
|
||||
// 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
|
||||
|
|
@ -83,84 +72,16 @@ func (r *userDataSource) Configure(
|
|||
}
|
||||
|
||||
// Schema defines the schema for the data source.
|
||||
func (r *userDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "Postgres Flex user data source schema. Must have a `region` specified in the provider configuration.",
|
||||
"id": "Terraform's internal data source. ID. It is structured as \"`project_id`,`region`,`instance_id`,`user_id`\".",
|
||||
"user_id": "User ID.",
|
||||
"instance_id": "ID of the PostgresFlex instance.",
|
||||
"project_id": "STACKIT project ID to which the instance is associated.",
|
||||
"username": "The name of the user.",
|
||||
"roles": "The roles assigned to the user.",
|
||||
"host": "The host address for the user to connect to the instance.",
|
||||
"port": "The port number for the user to connect to the instance.",
|
||||
"region": "The resource region. If not defined, the provider region is used.",
|
||||
"status": "The current status of the user.",
|
||||
"connection_string": "The connection string for the user to the instance.",
|
||||
func (r *userDataSource) Schema(ctx context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
s := postgresflexalpha.UserDataSourceSchema(ctx)
|
||||
s.Attributes["id"] = schema.StringAttribute{
|
||||
Description: "Terraform's internal resource ID. It is structured as \\\"`project_id`,`region`,`instance_id`," +
|
||||
"`user_id`\\\".\",",
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
},
|
||||
"user_id": schema.StringAttribute{
|
||||
Description: descriptions["user_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"username": schema.StringAttribute{
|
||||
Description: descriptions["username"],
|
||||
Computed: true,
|
||||
},
|
||||
"roles": schema.SetAttribute{
|
||||
Description: descriptions["roles"],
|
||||
ElementType: types.StringType,
|
||||
Computed: true,
|
||||
},
|
||||
"host": schema.StringAttribute{
|
||||
Description: descriptions["host"],
|
||||
Computed: true,
|
||||
},
|
||||
"port": schema.Int64Attribute{
|
||||
Description: descriptions["port"],
|
||||
Computed: true,
|
||||
},
|
||||
"region": schema.StringAttribute{
|
||||
// the region cannot be found automatically, so it has to be passed
|
||||
Optional: true,
|
||||
Description: descriptions["region"],
|
||||
},
|
||||
"status": schema.StringAttribute{
|
||||
Description: descriptions["status"],
|
||||
Computed: true,
|
||||
},
|
||||
"connection_string": schema.StringAttribute{
|
||||
Description: descriptions["connection_string"],
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
resp.Schema = s
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
|
|
@ -169,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() {
|
||||
|
|
@ -190,26 +111,12 @@ func (r *userDataSource) Read(
|
|||
region := r.providerData.GetRegionWithOverride(model.Region)
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "user_id", userId)
|
||||
ctx = tflog.SetField(ctx, "region", region)
|
||||
ctx = tflog.SetField(ctx, "user_id", userId)
|
||||
|
||||
recordSetResp, err := r.client.GetUserRequest(ctx, projectId, region, instanceId, userId).Execute()
|
||||
if err != nil {
|
||||
utils.LogError(
|
||||
ctx,
|
||||
&resp.Diagnostics,
|
||||
err,
|
||||
"Reading user",
|
||||
fmt.Sprintf(
|
||||
"User with ID %q or instance with ID %q does not exist in project %q.",
|
||||
userId,
|
||||
instanceId,
|
||||
projectId,
|
||||
),
|
||||
map[int]string{
|
||||
http.StatusForbidden: fmt.Sprintf("Project with ID %q not found or forbidden access", projectId),
|
||||
},
|
||||
)
|
||||
handleReadError(ctx, &diags, err, projectId, instanceId, userId)
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
|
|
@ -237,47 +144,38 @@ func (r *userDataSource) Read(
|
|||
tflog.Info(ctx, "Postgres Flex user read")
|
||||
}
|
||||
|
||||
func mapDataSourceFields(userResp *postgresflex.GetUserResponse, model *DataSourceModel, region string) error {
|
||||
if userResp == nil {
|
||||
return fmt.Errorf("response is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
user := userResp
|
||||
|
||||
var userId int64
|
||||
if model.UserId.ValueInt64() != 0 {
|
||||
userId = model.UserId.ValueInt64()
|
||||
} else if user.Id != nil {
|
||||
userId = *user.Id
|
||||
} else {
|
||||
return fmt.Errorf("user id not present")
|
||||
}
|
||||
|
||||
model.Id = utils.BuildInternalTerraformId(
|
||||
model.ProjectId.ValueString(), region, model.InstanceId.ValueString(), strconv.FormatInt(userId, 10),
|
||||
// handleReadError centralizes API error handling for the Read operation.
|
||||
func handleReadError(
|
||||
ctx context.Context,
|
||||
diags *diag.Diagnostics,
|
||||
err error,
|
||||
projectId, instanceId string,
|
||||
userId int32,
|
||||
) {
|
||||
utils.LogError(
|
||||
ctx,
|
||||
diags,
|
||||
err,
|
||||
"Reading user",
|
||||
fmt.Sprintf(
|
||||
"User with ID %q or instance with ID %q does not exist in project %q.",
|
||||
userId,
|
||||
instanceId,
|
||||
projectId,
|
||||
),
|
||||
map[int]string{
|
||||
http.StatusBadRequest: fmt.Sprintf(
|
||||
"Invalid user request parameters for project %q and instance %q.",
|
||||
projectId,
|
||||
instanceId,
|
||||
),
|
||||
http.StatusNotFound: fmt.Sprintf(
|
||||
"User, instance %q, or project %q or user %q not found.",
|
||||
instanceId,
|
||||
projectId,
|
||||
userId,
|
||||
),
|
||||
http.StatusForbidden: fmt.Sprintf("Forbidden access to project %q.", projectId),
|
||||
},
|
||||
)
|
||||
model.UserId = types.Int64Value(userId)
|
||||
model.Username = types.StringPointerValue(user.Name)
|
||||
|
||||
if user.Roles == nil {
|
||||
model.Roles = types.SetNull(types.StringType)
|
||||
} else {
|
||||
var roles []attr.Value
|
||||
for _, role := range *user.Roles {
|
||||
roles = append(roles, types.StringValue(string(role)))
|
||||
}
|
||||
rolesSet, diags := types.SetValue(types.StringType, roles)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("failed to map roles: %w", core.DiagsToError(diags))
|
||||
}
|
||||
model.Roles = rolesSet
|
||||
}
|
||||
model.Host = types.StringPointerValue(user.Host)
|
||||
model.Port = types.Int64PointerValue(user.Port)
|
||||
model.Region = types.StringValue(region)
|
||||
model.Status = types.StringPointerValue(user.Status)
|
||||
model.ConnectionString = types.StringPointerValue(user.ConnectionString)
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,146 +0,0 @@
|
|||
package postgresflexalpha
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"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/postgresflexalpha"
|
||||
)
|
||||
|
||||
func TestMapDataSourceFields(t *testing.T) {
|
||||
const testRegion = "region"
|
||||
tests := []struct {
|
||||
description string
|
||||
input *postgresflexalpha.GetUserResponse
|
||||
region string
|
||||
expected DataSourceModel
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&postgresflexalpha.GetUserResponse{},
|
||||
testRegion,
|
||||
DataSourceModel{
|
||||
Id: types.StringValue("pid,region,iid,1"),
|
||||
UserId: types.Int64Value(1),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Username: types.StringNull(),
|
||||
Roles: types.SetNull(types.StringType),
|
||||
Host: types.StringNull(),
|
||||
Port: types.Int64Null(),
|
||||
Region: types.StringValue(testRegion),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&postgresflexalpha.GetUserResponse{
|
||||
Roles: &[]postgresflexalpha.UserRole{
|
||||
"role_1",
|
||||
"role_2",
|
||||
"",
|
||||
},
|
||||
Name: utils.Ptr("username"),
|
||||
Host: utils.Ptr("host"),
|
||||
Port: utils.Ptr(int64(1234)),
|
||||
},
|
||||
testRegion,
|
||||
DataSourceModel{
|
||||
Id: types.StringValue("pid,region,iid,1"),
|
||||
UserId: types.Int64Value(1),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Username: types.StringValue("username"),
|
||||
Roles: types.SetValueMust(
|
||||
types.StringType, []attr.Value{
|
||||
types.StringValue("role_1"),
|
||||
types.StringValue("role_2"),
|
||||
types.StringValue(""),
|
||||
},
|
||||
),
|
||||
Host: types.StringValue("host"),
|
||||
Port: types.Int64Value(1234),
|
||||
Region: types.StringValue(testRegion),
|
||||
Status: types.StringNull(),
|
||||
ConnectionString: types.StringNull(),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&postgresflexalpha.GetUserResponse{
|
||||
Id: utils.Ptr(int64(1)),
|
||||
Roles: &[]postgresflexalpha.UserRole{},
|
||||
Name: nil,
|
||||
Host: nil,
|
||||
Port: utils.Ptr(int64(2123456789)),
|
||||
Status: utils.Ptr("status"),
|
||||
ConnectionString: utils.Ptr("connection_string"),
|
||||
},
|
||||
testRegion,
|
||||
DataSourceModel{
|
||||
Id: types.StringValue("pid,region,iid,1"),
|
||||
UserId: types.Int64Value(1),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Username: types.StringNull(),
|
||||
Roles: types.SetValueMust(types.StringType, []attr.Value{}),
|
||||
Host: types.StringNull(),
|
||||
Port: types.Int64Value(2123456789),
|
||||
Region: types.StringValue(testRegion),
|
||||
Status: types.StringValue("status"),
|
||||
ConnectionString: types.StringValue("connection_string"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
testRegion,
|
||||
DataSourceModel{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_response_2",
|
||||
&postgresflexalpha.GetUserResponse{},
|
||||
testRegion,
|
||||
DataSourceModel{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&postgresflexalpha.GetUserResponse{},
|
||||
testRegion,
|
||||
DataSourceModel{},
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(
|
||||
tt.description, func(t *testing.T) {
|
||||
state := &DataSourceModel{
|
||||
ProjectId: tt.expected.ProjectId,
|
||||
InstanceId: tt.expected.InstanceId,
|
||||
UserId: tt.expected.UserId,
|
||||
}
|
||||
err := mapDataSourceFields(tt.input, state, tt.region)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(state, &tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
@ -14,17 +14,7 @@ import (
|
|||
func UserDataSourceSchema(ctx context.Context) schema.Schema {
|
||||
return schema.Schema{
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"connection_string": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Description: "The connection string for the user to the instance.",
|
||||
MarkdownDescription: "The connection string for the user to the instance.",
|
||||
},
|
||||
"host": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Description: "The host of the instance in which the user belongs to.",
|
||||
MarkdownDescription: "The host of the instance in which the user belongs to.",
|
||||
},
|
||||
"id": schema.Int64Attribute{
|
||||
"tf_original_api_id": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
Description: "The ID of the user.",
|
||||
MarkdownDescription: "The ID of the user.",
|
||||
|
|
@ -39,11 +29,6 @@ func UserDataSourceSchema(ctx context.Context) schema.Schema {
|
|||
Description: "The name of the user.",
|
||||
MarkdownDescription: "The name of the user.",
|
||||
},
|
||||
"port": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
Description: "The port of the instance in which the user belongs to.",
|
||||
MarkdownDescription: "The port of the instance in which the user belongs to.",
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Required: true,
|
||||
Description: "The STACKIT project ID.",
|
||||
|
|
@ -80,15 +65,12 @@ func UserDataSourceSchema(ctx context.Context) schema.Schema {
|
|||
}
|
||||
|
||||
type UserModel struct {
|
||||
ConnectionString types.String `tfsdk:"connection_string"`
|
||||
Host types.String `tfsdk:"host"`
|
||||
Id types.Int64 `tfsdk:"id"`
|
||||
InstanceId types.String `tfsdk:"instance_id"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
Port types.Int64 `tfsdk:"port"`
|
||||
ProjectId types.String `tfsdk:"project_id"`
|
||||
Region types.String `tfsdk:"region"`
|
||||
Roles types.List `tfsdk:"roles"`
|
||||
Status types.String `tfsdk:"status"`
|
||||
UserId types.Int64 `tfsdk:"user_id"`
|
||||
Id types.Int64 `tfsdk:"tf_original_api_id"`
|
||||
InstanceId types.String `tfsdk:"instance_id"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
ProjectId types.String `tfsdk:"project_id"`
|
||||
Region types.String `tfsdk:"region"`
|
||||
Roles types.List `tfsdk:"roles"`
|
||||
Status types.String `tfsdk:"status"`
|
||||
UserId types.Int64 `tfsdk:"user_id"`
|
||||
}
|
||||
|
|
|
|||
142
stackit/internal/services/postgresflexalpha/user/mapper.go
Normal file
142
stackit/internal/services/postgresflexalpha/user/mapper.go
Normal file
|
|
@ -0,0 +1,142 @@
|
|||
package postgresflexalpha
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
postgresflex "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"
|
||||
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/core"
|
||||
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/utils"
|
||||
)
|
||||
|
||||
// mapDataSourceFields maps API response to data source model, preserving existing ID.
|
||||
func mapDataSourceFields(userResp *postgresflex.GetUserResponse, model *dataSourceModel, region string) error {
|
||||
if userResp == nil {
|
||||
return fmt.Errorf("response is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
user := userResp
|
||||
|
||||
var userId int64
|
||||
if model.UserId.ValueInt64() != 0 {
|
||||
userId = model.UserId.ValueInt64()
|
||||
} else if user.Id != nil {
|
||||
userId = *user.Id
|
||||
} 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.StringValue(user.GetName())
|
||||
|
||||
if user.Roles == nil {
|
||||
model.Roles = types.List(types.SetNull(types.StringType))
|
||||
} else {
|
||||
var roles []attr.Value
|
||||
for _, role := range *user.Roles {
|
||||
roles = append(roles, types.StringValue(string(role)))
|
||||
}
|
||||
rolesSet, diags := types.SetValue(types.StringType, roles)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("failed to map roles: %w", core.DiagsToError(diags))
|
||||
}
|
||||
model.Roles = types.List(rolesSet)
|
||||
}
|
||||
|
||||
model.Id = types.Int64Value(userId)
|
||||
model.Region = types.StringValue(region)
|
||||
model.Status = types.StringValue(user.GetStatus())
|
||||
return nil
|
||||
}
|
||||
|
||||
// toPayloadRoles converts a string slice to the API's role type.
|
||||
func toPayloadRoles(roles *[]string) *[]postgresflex.UserRole {
|
||||
var userRoles = make([]postgresflex.UserRole, 0, len(*roles))
|
||||
for _, role := range *roles {
|
||||
userRoles = append(userRoles, postgresflex.UserRole(role))
|
||||
}
|
||||
return &userRoles
|
||||
}
|
||||
|
||||
// toUpdatePayload creates an API update payload from the resource model.
|
||||
func toUpdatePayload(model *resourceModel, roles *[]string) (
|
||||
*postgresflex.UpdateUserRequestPayload,
|
||||
error,
|
||||
) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
if roles == nil {
|
||||
return nil, fmt.Errorf("nil roles")
|
||||
}
|
||||
|
||||
return &postgresflex.UpdateUserRequestPayload{
|
||||
Name: conversion.StringValueToPointer(model.Name),
|
||||
Roles: toPayloadRoles(roles),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// toCreatePayload creates an API create payload from the resource model.
|
||||
func toCreatePayload(model *resourceModel, roles *[]string) (*postgresflex.CreateUserRequestPayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
if roles == nil {
|
||||
return nil, fmt.Errorf("nil roles")
|
||||
}
|
||||
|
||||
return &postgresflex.CreateUserRequestPayload{
|
||||
Roles: toPayloadRoles(roles),
|
||||
Name: conversion.StringValueToPointer(model.Name),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// mapResourceFields maps API response to the resource model, preserving existing ID.
|
||||
func mapResourceFields(userResp *postgresflex.GetUserResponse, model *resourceModel, region string) error {
|
||||
if userResp == nil {
|
||||
return fmt.Errorf("response is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
user := userResp
|
||||
|
||||
var userId int64
|
||||
if model.UserId.ValueInt64() != 0 {
|
||||
userId = model.UserId.ValueInt64()
|
||||
} else if user.Id != nil {
|
||||
userId = *user.Id
|
||||
} else {
|
||||
return fmt.Errorf("user id not present")
|
||||
}
|
||||
|
||||
model.Id = types.Int64Value(userId)
|
||||
model.UserId = types.Int64Value(userId)
|
||||
model.Name = types.StringPointerValue(user.Name)
|
||||
|
||||
if user.Roles == nil {
|
||||
model.Roles = types.List(types.SetNull(types.StringType))
|
||||
} else {
|
||||
var roles []attr.Value
|
||||
for _, role := range *user.Roles {
|
||||
roles = append(roles, types.StringValue(string(role)))
|
||||
}
|
||||
rolesSet, diags := types.SetValue(types.StringType, roles)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("failed to map roles: %w", core.DiagsToError(diags))
|
||||
}
|
||||
model.Roles = types.List(rolesSet)
|
||||
}
|
||||
model.Region = types.StringValue(region)
|
||||
model.Status = types.StringPointerValue(user.Status)
|
||||
return nil
|
||||
}
|
||||
569
stackit/internal/services/postgresflexalpha/user/mapper_test.go
Normal file
569
stackit/internal/services/postgresflexalpha/user/mapper_test.go
Normal file
|
|
@ -0,0 +1,569 @@
|
|||
package postgresflexalpha
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"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"
|
||||
)
|
||||
|
||||
func TestMapDataSourceFields(t *testing.T) {
|
||||
const testRegion = "region"
|
||||
tests := []struct {
|
||||
description string
|
||||
input *postgresflex.GetUserResponse
|
||||
region string
|
||||
expected dataSourceModel
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&postgresflex.GetUserResponse{},
|
||||
testRegion,
|
||||
dataSourceModel{
|
||||
UserModel: data.UserModel{
|
||||
Id: types.Int64Value(1),
|
||||
UserId: types.Int64Value(1),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Name: types.StringValue(""),
|
||||
Roles: types.List(types.SetNull(types.StringType)),
|
||||
Status: types.StringValue(""),
|
||||
Region: types.StringValue(testRegion),
|
||||
},
|
||||
TerraformID: types.StringValue("pid,region,iid,1"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&postgresflex.GetUserResponse{
|
||||
Roles: &[]postgresflex.UserRole{
|
||||
"role_1",
|
||||
"role_2",
|
||||
"",
|
||||
},
|
||||
Name: utils.Ptr("username"),
|
||||
},
|
||||
testRegion,
|
||||
dataSourceModel{
|
||||
|
||||
UserModel: data.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(""),
|
||||
},
|
||||
),
|
||||
),
|
||||
Region: types.StringValue(testRegion),
|
||||
Status: types.StringValue(""),
|
||||
},
|
||||
TerraformID: types.StringValue("pid,region,iid,1"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&postgresflex.GetUserResponse{
|
||||
Id: utils.Ptr(int64(1)),
|
||||
Roles: &[]postgresflex.UserRole{},
|
||||
Name: nil,
|
||||
Status: utils.Ptr("status"),
|
||||
},
|
||||
testRegion,
|
||||
dataSourceModel{
|
||||
UserModel: data.UserModel{
|
||||
Id: types.Int64Value(1),
|
||||
UserId: types.Int64Value(1),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Name: types.StringValue(""),
|
||||
Roles: types.List(types.SetValueMust(types.StringType, []attr.Value{})),
|
||||
Region: types.StringValue(testRegion),
|
||||
Status: types.StringValue("status"),
|
||||
},
|
||||
TerraformID: types.StringValue("pid,region,iid,1"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
testRegion,
|
||||
dataSourceModel{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_response_2",
|
||||
&postgresflex.GetUserResponse{},
|
||||
testRegion,
|
||||
dataSourceModel{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&postgresflex.GetUserResponse{},
|
||||
testRegion,
|
||||
dataSourceModel{},
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(
|
||||
tt.description, func(t *testing.T) {
|
||||
state := &dataSourceModel{
|
||||
UserModel: data.UserModel{
|
||||
ProjectId: tt.expected.ProjectId,
|
||||
InstanceId: tt.expected.InstanceId,
|
||||
UserId: tt.expected.UserId,
|
||||
},
|
||||
}
|
||||
err := mapDataSourceFields(tt.input, state, tt.region)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(state, &tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMapFieldsCreate(t *testing.T) {
|
||||
const testRegion = "region"
|
||||
tests := []struct {
|
||||
description string
|
||||
input *postgresflex.GetUserResponse
|
||||
region string
|
||||
expected resourceModel
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&postgresflex.GetUserResponse{
|
||||
Id: utils.Ptr(int64(1)),
|
||||
},
|
||||
testRegion,
|
||||
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,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&postgresflex.GetUserResponse{
|
||||
Id: utils.Ptr(int64(1)),
|
||||
Name: utils.Ptr("username"),
|
||||
Status: utils.Ptr("status"),
|
||||
},
|
||||
testRegion,
|
||||
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,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&postgresflex.GetUserResponse{
|
||||
Id: utils.Ptr(int64(1)),
|
||||
Name: nil,
|
||||
Status: nil,
|
||||
},
|
||||
testRegion,
|
||||
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,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
testRegion,
|
||||
resourceModel{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_response_2",
|
||||
&postgresflex.GetUserResponse{},
|
||||
testRegion,
|
||||
resourceModel{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&postgresflex.GetUserResponse{},
|
||||
testRegion,
|
||||
resourceModel{},
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(
|
||||
tt.description, func(t *testing.T) {
|
||||
state := &resourceModel{
|
||||
ProjectId: tt.expected.ProjectId,
|
||||
InstanceId: tt.expected.InstanceId,
|
||||
}
|
||||
|
||||
err := mapResourceFields(tt.input, state, tt.region)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(state, &tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMapFields(t *testing.T) {
|
||||
const testRegion = "region"
|
||||
tests := []struct {
|
||||
description string
|
||||
input *postgresflex.GetUserResponse
|
||||
region string
|
||||
expected resourceModel
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&postgresflex.GetUserResponse{
|
||||
Id: utils.Ptr(int64(1)),
|
||||
},
|
||||
testRegion,
|
||||
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,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&postgresflex.GetUserResponse{
|
||||
Id: utils.Ptr(int64(1)),
|
||||
Roles: &[]postgresflex.UserRole{
|
||||
"role_1",
|
||||
"role_2",
|
||||
"",
|
||||
},
|
||||
Name: utils.Ptr("username"),
|
||||
},
|
||||
testRegion,
|
||||
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(),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&postgresflex.GetUserResponse{
|
||||
Id: utils.Ptr(int64(1)),
|
||||
Name: nil,
|
||||
},
|
||||
testRegion,
|
||||
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,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
testRegion,
|
||||
resourceModel{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_response_2",
|
||||
&postgresflex.GetUserResponse{},
|
||||
testRegion,
|
||||
resourceModel{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&postgresflex.GetUserResponse{},
|
||||
testRegion,
|
||||
resourceModel{},
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(
|
||||
tt.description, func(t *testing.T) {
|
||||
state := &resourceModel{
|
||||
ProjectId: tt.expected.ProjectId,
|
||||
InstanceId: tt.expected.InstanceId,
|
||||
}
|
||||
err := mapResourceFields(tt.input, state, tt.region)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(state, &tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestToCreatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *resourceModel
|
||||
inputRoles *[]string
|
||||
expected *postgresflex.CreateUserRequestPayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&resourceModel{},
|
||||
&[]string{},
|
||||
&postgresflex.CreateUserRequestPayload{
|
||||
Name: nil,
|
||||
Roles: &[]postgresflex.UserRole{},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&resourceModel{
|
||||
Name: types.StringValue("username"),
|
||||
},
|
||||
&[]string{
|
||||
"role_1",
|
||||
"role_2",
|
||||
},
|
||||
&postgresflex.CreateUserRequestPayload{
|
||||
Name: utils.Ptr("username"),
|
||||
Roles: &[]postgresflex.UserRole{
|
||||
"role_1",
|
||||
"role_2",
|
||||
},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&resourceModel{
|
||||
Name: types.StringNull(),
|
||||
},
|
||||
&[]string{
|
||||
"",
|
||||
},
|
||||
&postgresflex.CreateUserRequestPayload{
|
||||
Roles: &[]postgresflex.UserRole{
|
||||
"",
|
||||
},
|
||||
Name: nil,
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
&[]string{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_roles",
|
||||
&resourceModel{},
|
||||
nil,
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(
|
||||
tt.description, func(t *testing.T) {
|
||||
output, err := toCreatePayload(tt.input, tt.inputRoles)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(output, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestToUpdatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *resourceModel
|
||||
inputRoles *[]string
|
||||
expected *postgresflex.UpdateUserRequestPayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&resourceModel{},
|
||||
&[]string{},
|
||||
&postgresflex.UpdateUserRequestPayload{
|
||||
Roles: &[]postgresflex.UserRole{},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"default_values",
|
||||
&resourceModel{
|
||||
Name: types.StringValue("username"),
|
||||
},
|
||||
&[]string{
|
||||
"role_1",
|
||||
"role_2",
|
||||
},
|
||||
&postgresflex.UpdateUserRequestPayload{
|
||||
Name: utils.Ptr("username"),
|
||||
Roles: &[]postgresflex.UserRole{
|
||||
"role_1",
|
||||
"role_2",
|
||||
},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&resourceModel{
|
||||
Name: types.StringNull(),
|
||||
},
|
||||
&[]string{
|
||||
"",
|
||||
},
|
||||
&postgresflex.UpdateUserRequestPayload{
|
||||
Roles: &[]postgresflex.UserRole{
|
||||
"",
|
||||
},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
&[]string{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_roles",
|
||||
&resourceModel{},
|
||||
nil,
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(
|
||||
tt.description, func(t *testing.T) {
|
||||
output, err := toUpdatePayload(tt.input, tt.inputRoles)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(output, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
fields:
|
||||
- name: 'id'
|
||||
modifiers:
|
||||
- 'UseStateForUnknown'
|
||||
|
||||
- name: 'user_id'
|
||||
modifiers:
|
||||
- 'UseStateForUnknown'
|
||||
|
||||
- name: 'instance_id'
|
||||
validators:
|
||||
- validate.NoSeparator
|
||||
- validate.UUID
|
||||
modifiers:
|
||||
- 'UseStateForUnknown'
|
||||
|
||||
- name: 'project_id'
|
||||
validators:
|
||||
- validate.NoSeparator
|
||||
- validate.UUID
|
||||
modifiers:
|
||||
- 'UseStateForUnknown'
|
||||
- 'RequiresReplace'
|
||||
|
||||
- name: 'name'
|
||||
modifiers:
|
||||
- 'UseStateForUnknown'
|
||||
|
||||
- name: 'roles'
|
||||
modifiers:
|
||||
- 'UseStateForUnknown'
|
||||
|
||||
- name: 'password'
|
||||
modifiers:
|
||||
- 'UseStateForUnknown'
|
||||
|
||||
- name: 'host'
|
||||
modifiers:
|
||||
- 'UseStateForUnknown'
|
||||
|
||||
- name: 'port'
|
||||
modifiers:
|
||||
- 'UseStateForUnknown'
|
||||
|
||||
- name: 'region'
|
||||
modifiers:
|
||||
- 'RequiresReplace'
|
||||
|
||||
- name: 'status'
|
||||
modifiers:
|
||||
- 'UseStateForUnknown'
|
||||
|
||||
- name: 'connection_string'
|
||||
modifiers:
|
||||
- 'UseStateForUnknown'
|
||||
|
|
@ -2,6 +2,7 @@ package postgresflexalpha
|
|||
|
||||
import (
|
||||
"context"
|
||||
_ "embed"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
|
|
@ -9,60 +10,53 @@ import (
|
|||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/diag"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/int64planmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/identityschema"
|
||||
postgresflex "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/pkg_gen/postgresflexalpha"
|
||||
postgresflexalpha "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/services/postgresflexalpha/user/resources_gen"
|
||||
postgresflexUtils "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/services/postgresflexalpha/utils"
|
||||
|
||||
postgresflex "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/pkg_gen/postgresflexalpha"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/setvalidator"
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/path"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/oapierror"
|
||||
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/conversion"
|
||||
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/core"
|
||||
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/utils"
|
||||
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/path"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/oapierror"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
_ resource.Resource = &userResource{}
|
||||
_ resource.ResourceWithConfigure = &userResource{}
|
||||
_ resource.ResourceWithImportState = &userResource{}
|
||||
_ resource.ResourceWithModifyPlan = &userResource{}
|
||||
)
|
||||
_ resource.ResourceWithIdentity = &userResource{}
|
||||
|
||||
type Model struct {
|
||||
Id types.String `tfsdk:"id"` // needed by TF
|
||||
UserId types.Int64 `tfsdk:"user_id"`
|
||||
InstanceId types.String `tfsdk:"instance_id"`
|
||||
ProjectId types.String `tfsdk:"project_id"`
|
||||
Username types.String `tfsdk:"username"`
|
||||
Roles types.Set `tfsdk:"roles"`
|
||||
Password types.String `tfsdk:"password"`
|
||||
Host types.String `tfsdk:"host"`
|
||||
Port types.Int64 `tfsdk:"port"`
|
||||
Region types.String `tfsdk:"region"`
|
||||
Status types.String `tfsdk:"status"`
|
||||
ConnectionString types.String `tfsdk:"connection_string"`
|
||||
}
|
||||
// Error message constants
|
||||
extractErrorSummary = "extracting failed"
|
||||
extractErrorMessage = "Extracting identity data: %v"
|
||||
)
|
||||
|
||||
// NewUserResource is a helper function to simplify the provider implementation.
|
||||
func NewUserResource() resource.Resource {
|
||||
return &userResource{}
|
||||
}
|
||||
|
||||
// userResource is the resource implementation.
|
||||
// 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"`
|
||||
Region types.String `tfsdk:"region"`
|
||||
InstanceID types.String `tfsdk:"instance_id"`
|
||||
UserID types.Int64 `tfsdk:"database_id"`
|
||||
}
|
||||
|
||||
// userResource implements the resource handling for a PostgreSQL Flex user.
|
||||
type userResource struct {
|
||||
client *postgresflex.APIClient
|
||||
providerData core.ProviderData
|
||||
|
|
@ -75,7 +69,7 @@ func (r *userResource) ModifyPlan(
|
|||
req resource.ModifyPlanRequest,
|
||||
resp *resource.ModifyPlanResponse,
|
||||
) { // nolint:gocritic // function signature required by Terraform
|
||||
var configModel Model
|
||||
var configModel resourceModel
|
||||
// skip initial empty configuration to avoid follow-up errors
|
||||
if req.Config.Raw.IsNull() {
|
||||
return
|
||||
|
|
@ -85,7 +79,7 @@ func (r *userResource) ModifyPlan(
|
|||
return
|
||||
}
|
||||
|
||||
var planModel Model
|
||||
var planModel resourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &planModel)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
|
|
@ -123,117 +117,25 @@ func (r *userResource) Configure(ctx context.Context, req resource.ConfigureRequ
|
|||
tflog.Info(ctx, "Postgres Flex user client configured")
|
||||
}
|
||||
|
||||
//go:embed planModifiers.yaml
|
||||
var modifiersFileByte []byte
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *userResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
rolesOptions := []string{"login", "createdb", "createrole"}
|
||||
func (r *userResource) Schema(ctx context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
s := postgresflexalpha.UserResourceSchema(ctx)
|
||||
|
||||
descriptions := map[string]string{
|
||||
"main": "Postgres Flex user resource schema. Must have a `region` specified in the provider configuration.",
|
||||
"id": "Terraform's internal resource ID. It is structured as \"`project_id`,`region`,`instance_id`,`user_id`\".",
|
||||
"user_id": "User ID.",
|
||||
"instance_id": "ID of the PostgresFlex instance.",
|
||||
"project_id": "STACKIT project ID to which the instance is associated.",
|
||||
"username": "The name of the user.",
|
||||
"roles": "Database access levels for the user. " + utils.FormatPossibleValues(rolesOptions...),
|
||||
"region": "The resource region. If not defined, the provider region is used.",
|
||||
"status": "The current status of the user.",
|
||||
"password": "The password for the user. This is only set upon creation.",
|
||||
"host": "The host of the Postgres Flex instance.",
|
||||
"port": "The port of the Postgres Flex instance.",
|
||||
"connection_string": "The connection string for the user to the instance.",
|
||||
fields, err := utils.ReadModifiersConfig(modifiersFileByte)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("error during read modifiers config file", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"user_id": schema.Int64Attribute{
|
||||
Description: descriptions["user_id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.Int64{
|
||||
int64planmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.Int64{},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"username": schema.StringAttribute{
|
||||
Description: descriptions["username"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
// stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"roles": schema.SetAttribute{
|
||||
Description: descriptions["roles"],
|
||||
ElementType: types.StringType,
|
||||
Required: true,
|
||||
Validators: []validator.Set{
|
||||
setvalidator.ValueStringsAre(
|
||||
stringvalidator.OneOf(rolesOptions...),
|
||||
),
|
||||
},
|
||||
},
|
||||
"password": schema.StringAttribute{
|
||||
Description: descriptions["password"],
|
||||
Computed: true,
|
||||
Sensitive: true,
|
||||
},
|
||||
"host": schema.StringAttribute{
|
||||
Description: descriptions["host"],
|
||||
Computed: true,
|
||||
},
|
||||
"port": schema.Int64Attribute{
|
||||
Description: descriptions["port"],
|
||||
Computed: true,
|
||||
},
|
||||
"region": schema.StringAttribute{
|
||||
Optional: true,
|
||||
// must be computed to allow for storing the override value from the provider
|
||||
Computed: true,
|
||||
Description: descriptions["region"],
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"status": schema.StringAttribute{
|
||||
Description: descriptions["status"],
|
||||
Computed: true,
|
||||
},
|
||||
"connection_string": schema.StringAttribute{
|
||||
Description: descriptions["connection_string"],
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
err = utils.AddPlanModifiersToResourceSchema(fields, &s)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("error adding plan modifiers", err.Error())
|
||||
return
|
||||
}
|
||||
resp.Schema = s
|
||||
}
|
||||
|
||||
// Create creates the resource and sets the initial Terraform state.
|
||||
|
|
@ -242,16 +144,33 @@ func (r *userResource) Create(
|
|||
req resource.CreateRequest,
|
||||
resp *resource.CreateResponse,
|
||||
) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
var model resourceModel
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
// Read identity data
|
||||
var identityData UserResourceIdentityModel
|
||||
resp.Diagnostics.Append(req.Identity.Get(ctx, &identityData)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
ctx = r.setTFLogFields(ctx, &model)
|
||||
arg := r.getClientArg(&model)
|
||||
|
||||
arg, errExt := r.extractIdentityData(model, identityData)
|
||||
if errExt != nil {
|
||||
core.LogAndAddError(
|
||||
ctx,
|
||||
&resp.Diagnostics,
|
||||
extractErrorSummary,
|
||||
fmt.Sprintf(extractErrorMessage, errExt),
|
||||
)
|
||||
}
|
||||
|
||||
ctx = r.setTFLogFields(ctx, arg)
|
||||
|
||||
var roles = r.expandRoles(ctx, model.Roles, &resp.Diagnostics)
|
||||
if resp.Diagnostics.HasError() {
|
||||
|
|
@ -277,8 +196,6 @@ func (r *userResource) Create(
|
|||
return
|
||||
}
|
||||
|
||||
ctx = core.LogResponse(ctx)
|
||||
|
||||
if userResp.Id == nil || *userResp.Id == 0 {
|
||||
core.LogAndAddError(
|
||||
ctx,
|
||||
|
|
@ -288,12 +205,28 @@ func (r *userResource) Create(
|
|||
)
|
||||
return
|
||||
}
|
||||
model.Id = types.Int64PointerValue(userResp.Id)
|
||||
model.UserId = types.Int64PointerValue(userResp.Id)
|
||||
model.Password = types.StringPointerValue(userResp.Password)
|
||||
|
||||
ctx = tflog.SetField(ctx, "user_id", *userResp.Id)
|
||||
|
||||
exists, err := r.getUserResource(ctx, &model)
|
||||
ctx = core.LogResponse(ctx)
|
||||
|
||||
// Set data returned by API in identity
|
||||
identity := UserResourceIdentityModel{
|
||||
ProjectID: types.StringValue(arg.projectId),
|
||||
Region: types.StringValue(arg.region),
|
||||
InstanceID: types.StringValue(arg.instanceId),
|
||||
UserID: types.Int64PointerValue(userResp.Id),
|
||||
}
|
||||
resp.Diagnostics.Append(resp.Identity.Set(ctx, identity)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
// Verify creation
|
||||
exists, err := r.getUserResource(ctx, &model, arg)
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating user", fmt.Sprintf("Calling API: %v", err))
|
||||
|
|
@ -322,16 +255,38 @@ func (r *userResource) Read(
|
|||
req resource.ReadRequest,
|
||||
resp *resource.ReadResponse,
|
||||
) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
var model resourceModel
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
// Read identity data
|
||||
var identityData UserResourceIdentityModel
|
||||
resp.Diagnostics.Append(req.Identity.Get(ctx, &identityData)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
|
||||
exists, err := r.getUserResource(ctx, &model)
|
||||
arg, errExt := r.extractIdentityData(model, identityData)
|
||||
if errExt != nil {
|
||||
core.LogAndAddError(
|
||||
ctx,
|
||||
&resp.Diagnostics,
|
||||
extractErrorSummary,
|
||||
fmt.Sprintf(extractErrorMessage, errExt),
|
||||
)
|
||||
}
|
||||
|
||||
ctx = r.setTFLogFields(ctx, arg)
|
||||
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
|
||||
// Read resource state
|
||||
exists, err := r.getUserResource(ctx, &model, arg)
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading user", fmt.Sprintf("Calling API: %v", err))
|
||||
|
|
@ -360,19 +315,37 @@ func (r *userResource) Update(
|
|||
req resource.UpdateRequest,
|
||||
resp *resource.UpdateResponse,
|
||||
) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
var model resourceModel
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
// Read identity data
|
||||
var identityData UserResourceIdentityModel
|
||||
resp.Diagnostics.Append(req.Identity.Get(ctx, &identityData)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
|
||||
arg, errExt := r.extractIdentityData(model, identityData)
|
||||
if errExt != nil {
|
||||
core.LogAndAddError(
|
||||
ctx,
|
||||
&resp.Diagnostics,
|
||||
extractErrorSummary,
|
||||
fmt.Sprintf(extractErrorMessage, errExt),
|
||||
)
|
||||
}
|
||||
|
||||
ctx = r.setTFLogFields(ctx, arg)
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
ctx = r.setTFLogFields(ctx, &model)
|
||||
arg := r.getClientArg(&model)
|
||||
|
||||
// Retrieve values from state
|
||||
var stateModel Model
|
||||
var stateModel resourceModel
|
||||
diags = req.State.Get(ctx, &stateModel)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
|
|
@ -413,7 +386,8 @@ func (r *userResource) Update(
|
|||
|
||||
ctx = core.LogResponse(ctx)
|
||||
|
||||
exists, err := r.getUserResource(ctx, &stateModel)
|
||||
// Verify update
|
||||
exists, err := r.getUserResource(ctx, &stateModel, arg)
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating user", fmt.Sprintf("Calling API: %v", err))
|
||||
|
|
@ -443,16 +417,33 @@ func (r *userResource) Delete(
|
|||
req resource.DeleteRequest,
|
||||
resp *resource.DeleteResponse,
|
||||
) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
var model resourceModel
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
// Read identity data
|
||||
var identityData UserResourceIdentityModel
|
||||
resp.Diagnostics.Append(req.Identity.Get(ctx, &identityData)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
ctx = r.setTFLogFields(ctx, &model)
|
||||
arg := r.getClientArg(&model)
|
||||
|
||||
arg, errExt := r.extractIdentityData(model, identityData)
|
||||
if errExt != nil {
|
||||
core.LogAndAddError(
|
||||
ctx,
|
||||
&resp.Diagnostics,
|
||||
extractErrorSummary,
|
||||
fmt.Sprintf(extractErrorMessage, errExt),
|
||||
)
|
||||
}
|
||||
|
||||
ctx = r.setTFLogFields(ctx, arg)
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
|
||||
userId64 := arg.userId
|
||||
if userId64 > math.MaxInt32 {
|
||||
|
|
@ -469,7 +460,8 @@ func (r *userResource) Delete(
|
|||
|
||||
ctx = core.LogResponse(ctx)
|
||||
|
||||
exists, err := r.getUserResource(ctx, &model)
|
||||
// Verify deletion
|
||||
exists, err := r.getUserResource(ctx, &model, arg)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting user", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
|
|
@ -487,40 +479,31 @@ func (r *userResource) Delete(
|
|||
tflog.Info(ctx, "Postgres Flex user deleted")
|
||||
}
|
||||
|
||||
// ImportState imports a resource into the Terraform state on success.
|
||||
// The expected format of the resource import identifier is: project_id,zone_id,record_set_id
|
||||
func (r *userResource) ImportState(
|
||||
ctx context.Context,
|
||||
req resource.ImportStateRequest,
|
||||
resp *resource.ImportStateResponse,
|
||||
// IdentitySchema defines the fields that are required to uniquely identify a resource.
|
||||
func (r *userResource) IdentitySchema(
|
||||
_ context.Context,
|
||||
_ resource.IdentitySchemaRequest,
|
||||
response *resource.IdentitySchemaResponse,
|
||||
) {
|
||||
idParts := strings.Split(req.ID, core.Separator)
|
||||
if len(idParts) != 4 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" || idParts[3] == "" {
|
||||
core.LogAndAddError(
|
||||
ctx, &resp.Diagnostics,
|
||||
"Error importing user",
|
||||
fmt.Sprintf(
|
||||
"Expected import identifier with format [project_id],[region],[instance_id],[user_id], got %q",
|
||||
req.ID,
|
||||
),
|
||||
)
|
||||
return
|
||||
response.IdentitySchema = identityschema.Schema{
|
||||
Attributes: map[string]identityschema.Attribute{
|
||||
"project_id": identityschema.StringAttribute{
|
||||
RequiredForImport: true,
|
||||
},
|
||||
"region": identityschema.StringAttribute{
|
||||
RequiredForImport: true,
|
||||
},
|
||||
"instance_id": identityschema.StringAttribute{
|
||||
RequiredForImport: true,
|
||||
},
|
||||
"user_id": identityschema.Int64Attribute{
|
||||
RequiredForImport: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), idParts[1])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[2])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("user_id"), idParts[3])...)
|
||||
core.LogAndAddWarning(
|
||||
ctx,
|
||||
&resp.Diagnostics,
|
||||
"postgresflexalpha user imported with empty password and empty uri",
|
||||
"The user password and uri are not imported as they are only available upon creation of a new user. The password and uri fields will be empty.",
|
||||
)
|
||||
tflog.Info(ctx, "postgresflexalpha user state imported")
|
||||
}
|
||||
|
||||
func mapFields(userResp *postgresflex.GetUserResponse, model *Model, region string) error {
|
||||
func mapFields(userResp *postgresflex.GetUserResponse, model *resourceModel, region string) error {
|
||||
if userResp == nil {
|
||||
return fmt.Errorf("response is nil")
|
||||
}
|
||||
|
|
@ -537,14 +520,12 @@ func mapFields(userResp *postgresflex.GetUserResponse, model *Model, region stri
|
|||
} else {
|
||||
return fmt.Errorf("user id not present")
|
||||
}
|
||||
model.Id = utils.BuildInternalTerraformId(
|
||||
model.ProjectId.ValueString(), region, model.InstanceId.ValueString(), strconv.FormatInt(userId, 10),
|
||||
)
|
||||
|
||||
model.UserId = types.Int64Value(userId)
|
||||
model.Username = types.StringPointerValue(user.Name)
|
||||
model.Name = types.StringPointerValue(user.Name)
|
||||
|
||||
if user.Roles == nil {
|
||||
model.Roles = types.SetNull(types.StringType)
|
||||
model.Roles = types.List(types.SetNull(types.StringType))
|
||||
} else {
|
||||
var roles []attr.Value
|
||||
for _, role := range *user.Roles {
|
||||
|
|
@ -554,27 +535,21 @@ func mapFields(userResp *postgresflex.GetUserResponse, model *Model, region stri
|
|||
if diags.HasError() {
|
||||
return fmt.Errorf("failed to map roles: %w", core.DiagsToError(diags))
|
||||
}
|
||||
model.Roles = rolesSet
|
||||
model.Roles = types.List(rolesSet)
|
||||
}
|
||||
model.Host = types.StringPointerValue(user.Host)
|
||||
model.Port = types.Int64PointerValue(user.Port)
|
||||
model.Region = types.StringValue(region)
|
||||
model.Status = types.StringPointerValue(user.Status)
|
||||
model.ConnectionString = types.StringPointerValue(user.ConnectionString)
|
||||
return nil
|
||||
}
|
||||
|
||||
// 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 *Model) (bool, error) {
|
||||
ctx = r.setTFLogFields(ctx, model)
|
||||
arg := r.getClientArg(model)
|
||||
func (r *userResource) getUserResource(ctx context.Context, model *resourceModel, arg *clientArg) (bool, error) {
|
||||
|
||||
userId64 := arg.userId
|
||||
if userId64 > math.MaxInt32 {
|
||||
if arg.userId > math.MaxInt32 {
|
||||
return false, errors.New("error in type conversion: int value too large (userId)")
|
||||
}
|
||||
userId := int32(userId64)
|
||||
userId := int32(arg.userId)
|
||||
|
||||
// API Call
|
||||
userResp, err := r.client.GetUserRequest(ctx, arg.projectId, arg.region, arg.instanceId, userId).Execute()
|
||||
|
|
@ -588,13 +563,14 @@ func (r *userResource) getUserResource(ctx context.Context, model *Model) (bool,
|
|||
return false, fmt.Errorf("error fetching user resource: %w", err)
|
||||
}
|
||||
|
||||
if err := mapFields(userResp, model, arg.region); err != nil {
|
||||
if err := mapResourceFields(userResp, model, arg.region); err != nil {
|
||||
return false, fmt.Errorf("error mapping user resource: %w", err)
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// clientArg holds the arguments for API calls.
|
||||
type clientArg struct {
|
||||
projectId string
|
||||
instanceId string
|
||||
|
|
@ -602,29 +578,137 @@ type clientArg struct {
|
|||
userId int64
|
||||
}
|
||||
|
||||
// getClientArg constructs client arguments from the model.
|
||||
func (r *userResource) getClientArg(model *Model) *clientArg {
|
||||
return &clientArg{
|
||||
projectId: model.ProjectId.ValueString(),
|
||||
instanceId: model.InstanceId.ValueString(),
|
||||
region: r.providerData.GetRegionWithOverride(model.Region),
|
||||
userId: model.UserId.ValueInt64(),
|
||||
// ImportState imports a resource into the Terraform state on success.
|
||||
// The expected import identifier format is: [project_id],[region],[instance_id],[database_id]
|
||||
func (r *userResource) 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) != 4 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" || idParts[3] == "" {
|
||||
core.LogAndAddError(
|
||||
ctx, &resp.Diagnostics,
|
||||
"Error importing user",
|
||||
fmt.Sprintf(
|
||||
"Expected import identifier with format [project_id],[region],[instance_id],[user_id], got %q",
|
||||
req.ID,
|
||||
),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
userId, err := strconv.ParseInt(idParts[3], 10, 64)
|
||||
if err != nil {
|
||||
core.LogAndAddError(
|
||||
ctx,
|
||||
&resp.Diagnostics,
|
||||
"Error importing user",
|
||||
fmt.Sprintf("Invalid user_id format: %q. It must be a valid integer.", idParts[3]),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), idParts[1])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[2])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("user_id"), userId)...)
|
||||
|
||||
tflog.Info(ctx, "Postgres Flex user state imported")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// If no ID is provided, attempt to read identity attributes from the import configuration
|
||||
var identityData UserResourceIdentityModel
|
||||
resp.Diagnostics.Append(req.Identity.Get(ctx, &identityData)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
projectId := identityData.ProjectID.ValueString()
|
||||
region := identityData.Region.ValueString()
|
||||
instanceId := identityData.InstanceID.ValueString()
|
||||
userId := identityData.UserID.ValueInt64()
|
||||
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), projectId)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), region)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), instanceId)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("user_id"), userId)...)
|
||||
|
||||
tflog.Info(ctx, "Postgres Flex user state imported")
|
||||
}
|
||||
|
||||
// extractIdentityData extracts essential identifiers from the resource model, falling back to the identity model.
|
||||
func (r *userResource) extractIdentityData(
|
||||
model resourceModel,
|
||||
identity UserResourceIdentityModel,
|
||||
) (*clientArg, error) {
|
||||
|
||||
var projectId, region, instanceId string
|
||||
var userId int64
|
||||
|
||||
if !model.UserId.IsNull() && !model.UserId.IsUnknown() {
|
||||
userId = model.UserId.ValueInt64()
|
||||
} else {
|
||||
if identity.UserID.IsNull() || identity.UserID.IsUnknown() {
|
||||
return nil, fmt.Errorf("user_id not found in config")
|
||||
}
|
||||
userId = identity.UserID.ValueInt64()
|
||||
}
|
||||
|
||||
if !model.ProjectId.IsNull() && !model.ProjectId.IsUnknown() {
|
||||
projectId = model.ProjectId.ValueString()
|
||||
} else {
|
||||
if identity.ProjectID.IsNull() || identity.ProjectID.IsUnknown() {
|
||||
return nil, 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 nil, 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 nil, fmt.Errorf("instance_id not found in config")
|
||||
}
|
||||
instanceId = identity.InstanceID.ValueString()
|
||||
}
|
||||
return &clientArg{
|
||||
projectId: projectId,
|
||||
instanceId: instanceId,
|
||||
region: region,
|
||||
userId: userId,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// setTFLogFields adds relevant fields to the context for terraform logging purposes.
|
||||
func (r *userResource) setTFLogFields(ctx context.Context, model *Model) context.Context {
|
||||
usrCtx := r.getClientArg(model)
|
||||
|
||||
ctx = tflog.SetField(ctx, "project_id", usrCtx.projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", usrCtx.instanceId)
|
||||
ctx = tflog.SetField(ctx, "user_id", usrCtx.userId)
|
||||
ctx = tflog.SetField(ctx, "region", usrCtx.region)
|
||||
func (r *userResource) setTFLogFields(ctx context.Context, arg *clientArg) context.Context {
|
||||
ctx = tflog.SetField(ctx, "project_id", arg.projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", arg.instanceId)
|
||||
ctx = tflog.SetField(ctx, "region", arg.region)
|
||||
ctx = tflog.SetField(ctx, "user_id", arg.userId)
|
||||
|
||||
return ctx
|
||||
}
|
||||
|
||||
func (r *userResource) expandRoles(ctx context.Context, rolesSet types.Set, diags *diag.Diagnostics) []string {
|
||||
// expandRoles converts a Terraform list of roles to a string slice.
|
||||
func (r *userResource) expandRoles(ctx context.Context, rolesSet types.List, diags *diag.Diagnostics) []string {
|
||||
if rolesSet.IsNull() || rolesSet.IsUnknown() {
|
||||
return nil
|
||||
}
|
||||
|
|
@ -632,42 +716,3 @@ func (r *userResource) expandRoles(ctx context.Context, rolesSet types.Set, diag
|
|||
diags.Append(rolesSet.ElementsAs(ctx, &roles, false)...)
|
||||
return roles
|
||||
}
|
||||
|
||||
func toCreatePayload(model *Model, roles *[]string) (*postgresflex.CreateUserRequestPayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
if roles == nil {
|
||||
return nil, fmt.Errorf("nil roles")
|
||||
}
|
||||
|
||||
return &postgresflex.CreateUserRequestPayload{
|
||||
Roles: toPayloadRoles(roles),
|
||||
Name: conversion.StringValueToPointer(model.Username),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func toPayloadRoles(roles *[]string) *[]postgresflex.UserRole {
|
||||
var userRoles = make([]postgresflex.UserRole, 0, len(*roles))
|
||||
for _, role := range *roles {
|
||||
userRoles = append(userRoles, postgresflex.UserRole(role))
|
||||
}
|
||||
return &userRoles
|
||||
}
|
||||
|
||||
func toUpdatePayload(model *Model, roles *[]string) (
|
||||
*postgresflex.UpdateUserRequestPayload,
|
||||
error,
|
||||
) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
if roles == nil {
|
||||
return nil, fmt.Errorf("nil roles")
|
||||
}
|
||||
|
||||
return &postgresflex.UpdateUserRequestPayload{
|
||||
Name: conversion.StringValueToPointer(model.Username),
|
||||
Roles: toPayloadRoles(roles),
|
||||
}, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,448 +0,0 @@
|
|||
package postgresflexalpha
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"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/postgresflexalpha"
|
||||
)
|
||||
|
||||
func TestMapFieldsCreate(t *testing.T) {
|
||||
const testRegion = "region"
|
||||
tests := []struct {
|
||||
description string
|
||||
input *postgresflexalpha.GetUserResponse
|
||||
region string
|
||||
expected Model
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&postgresflexalpha.GetUserResponse{
|
||||
Id: utils.Ptr(int64(1)),
|
||||
},
|
||||
testRegion,
|
||||
Model{
|
||||
Id: types.StringValue("pid,region,iid,1"),
|
||||
UserId: types.Int64Value(1),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Username: types.StringNull(),
|
||||
Roles: types.SetNull(types.StringType),
|
||||
Password: types.StringNull(),
|
||||
Host: types.StringNull(),
|
||||
Port: types.Int64Null(),
|
||||
Region: types.StringValue(testRegion),
|
||||
Status: types.StringNull(),
|
||||
ConnectionString: types.StringNull(),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&postgresflexalpha.GetUserResponse{
|
||||
Id: utils.Ptr(int64(1)),
|
||||
Name: utils.Ptr("username"),
|
||||
ConnectionString: utils.Ptr("connection_string"),
|
||||
Status: utils.Ptr("status"),
|
||||
},
|
||||
testRegion,
|
||||
Model{
|
||||
Id: types.StringValue("pid,region,iid,1"),
|
||||
UserId: types.Int64Value(1),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Username: types.StringValue("username"),
|
||||
Roles: types.SetNull(types.StringType),
|
||||
Password: types.StringNull(),
|
||||
Host: types.StringNull(),
|
||||
Port: types.Int64Null(),
|
||||
Region: types.StringValue(testRegion),
|
||||
Status: types.StringValue("status"),
|
||||
ConnectionString: types.StringValue("connection_string"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&postgresflexalpha.GetUserResponse{
|
||||
Id: utils.Ptr(int64(1)),
|
||||
Name: nil,
|
||||
ConnectionString: nil,
|
||||
Status: nil,
|
||||
},
|
||||
testRegion,
|
||||
Model{
|
||||
Id: types.StringValue("pid,region,iid,1"),
|
||||
UserId: types.Int64Value(1),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Username: types.StringNull(),
|
||||
Roles: types.SetNull(types.StringType),
|
||||
Password: types.StringNull(),
|
||||
Host: types.StringNull(),
|
||||
Port: types.Int64Null(),
|
||||
Region: types.StringValue(testRegion),
|
||||
Status: types.StringNull(),
|
||||
ConnectionString: types.StringNull(),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
testRegion,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_response_2",
|
||||
&postgresflexalpha.GetUserResponse{},
|
||||
testRegion,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&postgresflexalpha.GetUserResponse{},
|
||||
testRegion,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(
|
||||
tt.description, func(t *testing.T) {
|
||||
state := &Model{
|
||||
ProjectId: tt.expected.ProjectId,
|
||||
InstanceId: tt.expected.InstanceId,
|
||||
}
|
||||
|
||||
err := mapFields(tt.input, state, tt.region)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(state, &tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMapFields(t *testing.T) {
|
||||
const testRegion = "region"
|
||||
tests := []struct {
|
||||
description string
|
||||
input *postgresflexalpha.GetUserResponse
|
||||
region string
|
||||
expected Model
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&postgresflexalpha.GetUserResponse{},
|
||||
testRegion,
|
||||
Model{
|
||||
Id: types.StringValue("pid,region,iid,1"),
|
||||
UserId: types.Int64Value(int64(1)),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Username: types.StringNull(),
|
||||
Roles: types.SetNull(types.StringType),
|
||||
Host: types.StringNull(),
|
||||
Port: types.Int64Null(),
|
||||
Region: types.StringValue(testRegion),
|
||||
Status: types.StringNull(),
|
||||
ConnectionString: types.StringNull(),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&postgresflexalpha.GetUserResponse{
|
||||
Roles: &[]postgresflexalpha.UserRole{
|
||||
"role_1",
|
||||
"role_2",
|
||||
"",
|
||||
},
|
||||
Name: utils.Ptr("username"),
|
||||
Host: utils.Ptr("host"),
|
||||
Port: utils.Ptr(int64(1234)),
|
||||
},
|
||||
testRegion,
|
||||
Model{
|
||||
Id: types.StringValue("pid,region,iid,1"),
|
||||
UserId: types.Int64Value(1),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Username: types.StringValue("username"),
|
||||
Roles: types.SetValueMust(
|
||||
types.StringType, []attr.Value{
|
||||
types.StringValue("role_1"),
|
||||
types.StringValue("role_2"),
|
||||
types.StringValue(""),
|
||||
},
|
||||
),
|
||||
Host: types.StringValue("host"),
|
||||
Port: types.Int64Value(1234),
|
||||
Region: types.StringValue(testRegion),
|
||||
Status: types.StringNull(),
|
||||
ConnectionString: types.StringNull(),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&postgresflexalpha.GetUserResponse{
|
||||
Id: utils.Ptr(int64(1)),
|
||||
Name: nil,
|
||||
Host: nil,
|
||||
Port: utils.Ptr(int64(2123456789)),
|
||||
},
|
||||
testRegion,
|
||||
Model{
|
||||
Id: types.StringValue("pid,region,iid,1"),
|
||||
UserId: types.Int64Value(1),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Username: types.StringNull(),
|
||||
Roles: types.SetNull(types.StringType),
|
||||
Host: types.StringNull(),
|
||||
Port: types.Int64Value(2123456789),
|
||||
Region: types.StringValue(testRegion),
|
||||
Status: types.StringNull(),
|
||||
ConnectionString: types.StringNull(),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
testRegion,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_response_2",
|
||||
&postgresflexalpha.GetUserResponse{},
|
||||
testRegion,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&postgresflexalpha.GetUserResponse{},
|
||||
testRegion,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(
|
||||
tt.description, func(t *testing.T) {
|
||||
state := &Model{
|
||||
ProjectId: tt.expected.ProjectId,
|
||||
InstanceId: tt.expected.InstanceId,
|
||||
UserId: tt.expected.UserId,
|
||||
}
|
||||
err := mapFields(tt.input, state, tt.region)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(state, &tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestToCreatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
inputRoles *[]string
|
||||
expected *postgresflexalpha.CreateUserRequestPayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&Model{},
|
||||
&[]string{},
|
||||
&postgresflexalpha.CreateUserRequestPayload{
|
||||
Name: nil,
|
||||
Roles: &[]postgresflexalpha.UserRole{},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&Model{
|
||||
Username: types.StringValue("username"),
|
||||
},
|
||||
&[]string{
|
||||
"role_1",
|
||||
"role_2",
|
||||
},
|
||||
&postgresflexalpha.CreateUserRequestPayload{
|
||||
Name: utils.Ptr("username"),
|
||||
Roles: &[]postgresflexalpha.UserRole{
|
||||
"role_1",
|
||||
"role_2",
|
||||
},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&Model{
|
||||
Username: types.StringNull(),
|
||||
},
|
||||
&[]string{
|
||||
"",
|
||||
},
|
||||
&postgresflexalpha.CreateUserRequestPayload{
|
||||
Roles: &[]postgresflexalpha.UserRole{
|
||||
"",
|
||||
},
|
||||
Name: nil,
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
&[]string{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_roles",
|
||||
&Model{},
|
||||
nil,
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(
|
||||
tt.description, func(t *testing.T) {
|
||||
output, err := toCreatePayload(tt.input, tt.inputRoles)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(output, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestToUpdatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
inputRoles *[]string
|
||||
expected *postgresflexalpha.UpdateUserRequestPayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&Model{},
|
||||
&[]string{},
|
||||
&postgresflexalpha.UpdateUserRequestPayload{
|
||||
Roles: &[]postgresflexalpha.UserRole{},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"default_values",
|
||||
&Model{
|
||||
Username: types.StringValue("username"),
|
||||
},
|
||||
&[]string{
|
||||
"role_1",
|
||||
"role_2",
|
||||
},
|
||||
&postgresflexalpha.UpdateUserRequestPayload{
|
||||
Name: utils.Ptr("username"),
|
||||
Roles: &[]postgresflexalpha.UserRole{
|
||||
"role_1",
|
||||
"role_2",
|
||||
},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&Model{
|
||||
Username: types.StringNull(),
|
||||
},
|
||||
&[]string{
|
||||
"",
|
||||
},
|
||||
&postgresflexalpha.UpdateUserRequestPayload{
|
||||
Roles: &[]postgresflexalpha.UserRole{
|
||||
"",
|
||||
},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
&[]string{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_roles",
|
||||
&Model{},
|
||||
nil,
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(
|
||||
tt.description, func(t *testing.T) {
|
||||
output, err := toUpdatePayload(tt.input, tt.inputRoles)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(output, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
@ -19,11 +19,6 @@ func UserResourceSchema(ctx context.Context) schema.Schema {
|
|||
Description: "The connection string for the user to the instance.",
|
||||
MarkdownDescription: "The connection string for the user to the instance.",
|
||||
},
|
||||
"host": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Description: "The host of the instance in which the user belongs to.",
|
||||
MarkdownDescription: "The host of the instance in which the user belongs to.",
|
||||
},
|
||||
"id": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
Description: "The ID of the user.",
|
||||
|
|
@ -45,11 +40,6 @@ func UserResourceSchema(ctx context.Context) schema.Schema {
|
|||
Description: "The password for the user.",
|
||||
MarkdownDescription: "The password for the user.",
|
||||
},
|
||||
"port": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
Description: "The port of the instance in which the user belongs to.",
|
||||
MarkdownDescription: "The port of the instance in which the user belongs to.",
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
|
|
@ -91,12 +81,10 @@ func UserResourceSchema(ctx context.Context) schema.Schema {
|
|||
|
||||
type UserModel struct {
|
||||
ConnectionString types.String `tfsdk:"connection_string"`
|
||||
Host types.String `tfsdk:"host"`
|
||||
Id types.Int64 `tfsdk:"id"`
|
||||
InstanceId types.String `tfsdk:"instance_id"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
Password types.String `tfsdk:"password"`
|
||||
Port types.Int64 `tfsdk:"port"`
|
||||
ProjectId types.String `tfsdk:"project_id"`
|
||||
Region types.String `tfsdk:"region"`
|
||||
Roles types.List `tfsdk:"roles"`
|
||||
|
|
|
|||
|
|
@ -1,229 +0,0 @@
|
|||
package utils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"reflect"
|
||||
"slices"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/boolplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/int64planmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/listplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
|
||||
"github.com/iancoleman/strcase"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
type Field struct {
|
||||
Name string `yaml:"name"`
|
||||
Modifiers []*string `yaml:"modifiers"`
|
||||
}
|
||||
|
||||
type Fields struct {
|
||||
Fields []*Field `yaml:"fields"`
|
||||
}
|
||||
|
||||
var validModifiers = []string{
|
||||
"UseStateForUnknown",
|
||||
"RequiresReplace",
|
||||
}
|
||||
|
||||
func ReadModifiersConfig(content []byte) (*Fields, error) {
|
||||
var fields Fields
|
||||
err := yaml.Unmarshal(content, &fields)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &fields, nil
|
||||
}
|
||||
|
||||
func AddPlanModifiersToResourceSchema(fields *Fields, s *schema.Schema) error {
|
||||
err := validateFields(fields)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
resAttr, err := handleAttributes("", s.Attributes, fields)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.Attributes = resAttr
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func handleAttributes(prefix string, attributes map[string]schema.Attribute, fields *Fields) (map[string]schema.Attribute, error) {
|
||||
fieldMap := fieldListToMap(fields)
|
||||
for attrName, attrValue := range attributes {
|
||||
attrNameSnake := strcase.ToSnake(attrName)
|
||||
if prefix != "" {
|
||||
attrNameSnake = prefix + "." + attrNameSnake
|
||||
}
|
||||
switch reflect.TypeOf(attrValue).String() {
|
||||
case "schema.BoolAttribute":
|
||||
if field, ok := fieldMap[attrNameSnake]; ok {
|
||||
res, err := handleBoolPlanModifiers(attrValue, field)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
attributes[attrName] = res
|
||||
}
|
||||
case "schema.Int64Attribute":
|
||||
if field, ok := fieldMap[attrNameSnake]; ok {
|
||||
res, err := handleInt64PlanModifiers(attrValue, field)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
attributes[attrName] = res
|
||||
}
|
||||
case "schema.StringAttribute":
|
||||
if field, ok := fieldMap[attrNameSnake]; ok {
|
||||
res, err := handleStringPlanModifiers(attrValue, field)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
attributes[attrName] = res
|
||||
}
|
||||
case "schema.ListAttribute":
|
||||
if field, ok := fieldMap[attrNameSnake]; ok {
|
||||
res, err := handleListPlanModifiers(attrValue, field)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
attributes[attrName] = res
|
||||
}
|
||||
case "schema.SingleNestedAttribute":
|
||||
nested, ok := attrValue.(schema.SingleNestedAttribute)
|
||||
if !ok {
|
||||
if _, ok := attrValue.(interface {
|
||||
GetAttributes() map[string]schema.Attribute
|
||||
}); ok {
|
||||
return nil, fmt.Errorf("unsupported type for single nested attribute")
|
||||
}
|
||||
}
|
||||
|
||||
res, err := handleAttributes(attrName, nested.Attributes, fields)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nested.Attributes = res
|
||||
attributes[attrName] = nested
|
||||
default:
|
||||
slog.Warn("type currently not supported", "type", reflect.TypeOf(attrValue).String())
|
||||
}
|
||||
}
|
||||
return attributes, nil
|
||||
}
|
||||
|
||||
func handleBoolPlanModifiers(
|
||||
attr schema.Attribute,
|
||||
fields []*string,
|
||||
) (schema.Attribute, error) {
|
||||
a, ok := attr.(schema.BoolAttribute)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("field is not a string attribute")
|
||||
}
|
||||
|
||||
for _, v := range fields {
|
||||
switch *v {
|
||||
case "RequiresReplace":
|
||||
a.PlanModifiers = append(a.PlanModifiers, boolplanmodifier.RequiresReplace())
|
||||
case "UseStateForUnknown":
|
||||
a.PlanModifiers = append(a.PlanModifiers, boolplanmodifier.UseStateForUnknown())
|
||||
}
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
|
||||
func handleStringPlanModifiers(
|
||||
attr schema.Attribute,
|
||||
fields []*string,
|
||||
) (schema.Attribute, error) {
|
||||
a, ok := attr.(schema.StringAttribute)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("field is not a string attribute")
|
||||
}
|
||||
|
||||
for _, v := range fields {
|
||||
switch *v {
|
||||
case "RequiresReplace":
|
||||
a.PlanModifiers = append(a.PlanModifiers, stringplanmodifier.RequiresReplace())
|
||||
case "UseStateForUnknown":
|
||||
a.PlanModifiers = append(a.PlanModifiers, stringplanmodifier.UseStateForUnknown())
|
||||
}
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
|
||||
func handleInt64PlanModifiers(
|
||||
attr schema.Attribute,
|
||||
fields []*string,
|
||||
) (schema.Attribute, error) {
|
||||
a, ok := attr.(schema.Int64Attribute)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("field is not a string attribute")
|
||||
}
|
||||
|
||||
for _, v := range fields {
|
||||
switch *v {
|
||||
case "RequiresReplace":
|
||||
a.PlanModifiers = append(a.PlanModifiers, int64planmodifier.RequiresReplace())
|
||||
case "UseStateForUnknown":
|
||||
a.PlanModifiers = append(a.PlanModifiers, int64planmodifier.UseStateForUnknown())
|
||||
}
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
|
||||
func handleListPlanModifiers(
|
||||
attr schema.Attribute,
|
||||
fields []*string,
|
||||
) (schema.Attribute, error) {
|
||||
a, ok := attr.(schema.ListAttribute)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("field is not a string attribute")
|
||||
}
|
||||
|
||||
for _, v := range fields {
|
||||
switch *v {
|
||||
case "RequiresReplace":
|
||||
a.PlanModifiers = append(a.PlanModifiers, listplanmodifier.RequiresReplace())
|
||||
case "UseStateForUnknown":
|
||||
a.PlanModifiers = append(a.PlanModifiers, listplanmodifier.UseStateForUnknown())
|
||||
}
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
|
||||
func validateFields(fields *Fields) error {
|
||||
if fields == nil {
|
||||
return nil
|
||||
}
|
||||
for _, field := range fields.Fields {
|
||||
for _, modifier := range field.Modifiers {
|
||||
if *modifier == "" {
|
||||
return fmt.Errorf("modifier %s is required", *modifier)
|
||||
}
|
||||
if !slices.Contains(validModifiers, *modifier) {
|
||||
return fmt.Errorf("modifier %s is invalid", *modifier)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func fieldListToMap(fields *Fields) map[string][]*string {
|
||||
res := make(map[string][]*string)
|
||||
|
||||
if fields != nil {
|
||||
for _, field := range fields.Fields {
|
||||
res[field.Name] = field.Modifiers
|
||||
}
|
||||
} else {
|
||||
slog.Warn("no fields available")
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue