chore: updated files - work save

This commit is contained in:
Marcel S. Henselin 2026-01-22 16:00:34 +01:00
parent e91e10e29a
commit b4c5b3774b
110 changed files with 1498 additions and 3013 deletions

View file

@ -1,3 +1,6 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: Apache-2.0
package sqlserverFlexAlphaFlavor
import (
@ -5,24 +8,25 @@ import (
"fmt"
"github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-framework/types/basetypes"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/mhenselin/terraform-provider-stackitprivatepreview/pkg/sqlserverflexalpha"
"github.com/mhenselin/terraform-provider-stackitprivatepreview/stackit/internal/conversion"
"github.com/mhenselin/terraform-provider-stackitprivatepreview/stackit/internal/core"
"github.com/mhenselin/terraform-provider-stackitprivatepreview/stackit/internal/utils"
sqlserverflex "github.com/mhenselin/terraform-provider-stackitprivatepreview/stackit/internal/services/sqlserverflexalpha"
sqlserverflexalphaGen "github.com/mhenselin/terraform-provider-stackitprivatepreview/stackit/internal/services/sqlserverflexalpha/flavor/datasources_gen"
sqlserverflexUtils "github.com/mhenselin/terraform-provider-stackitprivatepreview/stackit/internal/services/sqlserverflexalpha/utils"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/mhenselin/terraform-provider-stackitprivatepreview/stackit/internal/core"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ datasource.DataSource = &flavorDataSource{}
_ datasource.DataSource = &flavorDataSource{}
_ datasource.DataSourceWithConfigure = &flavorDataSource{}
)
type FlavorModel struct {
@ -144,9 +148,9 @@ func (r *flavorDataSource) Schema(ctx context.Context, _ datasource.SchemaReques
Computed: true,
},
},
CustomType: sqlserverflex.StorageClassesType{
CustomType: sqlserverflexalphaGen.StorageClassesType{
ObjectType: types.ObjectType{
AttrTypes: sqlserverflex.StorageClassesValue{}.AttributeTypes(ctx),
AttrTypes: sqlserverflexalphaGen.StorageClassesValue{}.AttributeTypes(ctx),
},
},
},
@ -211,9 +215,9 @@ func (r *flavorDataSource) Read(ctx context.Context, req datasource.ReadRequest,
model.MinGb = types.Int64Value(*f.MinGB)
if f.StorageClasses == nil {
model.StorageClasses = types.ListNull(sqlserverflex.StorageClassesType{
model.StorageClasses = types.ListNull(sqlserverflexalphaGen.StorageClassesType{
ObjectType: basetypes.ObjectType{
AttrTypes: sqlserverflex.StorageClassesValue{}.AttributeTypes(ctx),
AttrTypes: sqlserverflexalphaGen.StorageClassesValue{}.AttributeTypes(ctx),
},
})
} else {
@ -221,8 +225,8 @@ func (r *flavorDataSource) Read(ctx context.Context, req datasource.ReadRequest,
for _, sc := range *f.StorageClasses {
scList = append(
scList,
sqlserverflex.NewStorageClassesValueMust(
sqlserverflex.StorageClassesValue{}.AttributeTypes(ctx),
sqlserverflexalphaGen.NewStorageClassesValueMust(
sqlserverflexalphaGen.StorageClassesValue{}.AttributeTypes(ctx),
map[string]attr.Value{
"class": types.StringValue(*sc.Class),
"max_io_per_sec": types.Int64Value(*sc.MaxIoPerSec),
@ -232,9 +236,9 @@ func (r *flavorDataSource) Read(ctx context.Context, req datasource.ReadRequest,
)
}
storageClassesList := types.ListValueMust(
sqlserverflex.StorageClassesType{
sqlserverflexalphaGen.StorageClassesType{
ObjectType: basetypes.ObjectType{
AttrTypes: sqlserverflex.StorageClassesValue{}.AttributeTypes(ctx),
AttrTypes: sqlserverflexalphaGen.StorageClassesValue{}.AttributeTypes(ctx),
},
},
scList,

View file

@ -1,198 +1,68 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: Apache-2.0
package sqlserverFlexAlphaFlavor
import (
"context"
"fmt"
sqlserverflex "github.com/mhenselin/terraform-provider-stackitprivatepreview/pkg/sqlserverflexalpha"
"github.com/mhenselin/terraform-provider-stackitprivatepreview/pkg/sqlserverflexalpha"
)
type flavorsClient interface {
GetFlavorsRequestExecute(ctx context.Context, projectId, region string) (*sqlserverflex.GetFlavorsResponse, error)
GetFlavorsRequest(ctx context.Context, projectId, region string) sqlserverflex.ApiGetFlavorsRequestRequest
type flavorsClientReader interface {
GetFlavorsRequest(
ctx context.Context,
projectId, region string,
) sqlserverflexalpha.ApiGetFlavorsRequestRequest
}
// func loadFlavorId(ctx context.Context, client flavorsClient, model *Model, flavor *flavorModel, storage *storageModel) error {
// if model == nil {
// return fmt.Errorf("nil model")
// }
// if flavor == nil {
// return fmt.Errorf("nil flavor")
// }
// cpu := flavor.CPU.ValueInt64()
// if cpu == 0 {
// return fmt.Errorf("nil CPU")
// }
// ram := flavor.RAM.ValueInt64()
// if ram == 0 {
// return fmt.Errorf("nil RAM")
// }
//
// nodeType := flavor.NodeType.ValueString()
// if nodeType == "" {
// if model.Replicas.IsNull() || model.Replicas.IsUnknown() {
// return fmt.Errorf("nil NodeType")
// }
// switch model.Replicas.ValueInt64() {
// case 1:
// nodeType = "Single"
// case 3:
// nodeType = "Replica"
// default:
// return fmt.Errorf("unknown Replicas value: %d", model.Replicas.ValueInt64())
// }
// }
//
// storageClass := conversion.StringValueToPointer(storage.Class)
// if storageClass == nil {
// return fmt.Errorf("nil StorageClass")
// }
// storageSize := conversion.Int64ValueToPointer(storage.Size)
// if storageSize == nil {
// return fmt.Errorf("nil StorageSize")
// }
//
// projectId := model.ProjectId.ValueString()
// region := model.Region.ValueString()
//
// flavorList, err := getAllFlavors(ctx, client, projectId, region)
// if err != nil {
// return err
// }
//
// avl := ""
// foundFlavorCount := 0
// var foundFlavors []string
// for _, f := range flavorList {
// if f.Id == nil || f.Cpu == nil || f.Memory == nil {
// continue
// }
// if !strings.EqualFold(*f.NodeType, nodeType) {
// continue
// }
// if *f.Cpu == cpu && *f.Memory == ram {
// var useSc *sqlserverflex.FlavorStorageClassesStorageClass
// for _, sc := range *f.StorageClasses {
// if *sc.Class != *storageClass {
// continue
// }
// if *storageSize < *f.MinGB || *storageSize > *f.MaxGB {
// return fmt.Errorf("storage size %d out of bounds (min: %d - max: %d)", *storageSize, *f.MinGB, *f.MaxGB)
// }
// useSc = &sc
// }
// if useSc == nil {
// return fmt.Errorf("no storage class found for %s", *storageClass)
// }
//
// flavor.Id = types.StringValue(*f.Id)
// flavor.Description = types.StringValue(*f.Description)
// foundFlavors = append(foundFlavors, fmt.Sprintf("%s (%d/%d - %s)", *f.Id, *f.Cpu, *f.Memory, *f.NodeType))
// foundFlavorCount++
// }
// for _, cls := range *f.StorageClasses {
// avl = fmt.Sprintf("%s\n- %d CPU, %d GB RAM, storage %s (min: %d - max: %d)", avl, *f.Cpu, *f.Memory, *cls.Class, *f.MinGB, *f.MaxGB)
// }
// }
// if foundFlavorCount > 1 {
// return fmt.Errorf(
// "number of flavors returned: %d\nmultiple flavors found: %d flavors\n %s",
// len(flavorList),
// foundFlavorCount,
// strings.Join(foundFlavors, "\n "),
// )
// }
// if flavor.Id.ValueString() == "" {
// return fmt.Errorf("couldn't find flavor, available specs are:%s", avl)
// }
//
// return nil
//}
func getAllFlavors(ctx context.Context, client flavorsClient, projectId, region string) (
[]sqlserverflex.ListFlavors,
func getAllFlavors(ctx context.Context, client flavorsClientReader, projectId, region string) (
[]sqlserverflexalpha.ListFlavors,
error,
) {
if projectId == "" || region == "" {
return nil, fmt.Errorf("listing sqlserverflex flavors: projectId and region are required")
}
var flavorList []sqlserverflex.ListFlavors
var page int64 = 1
counter := 0
for {
res, err := client.GetFlavorsRequest(ctx, projectId, region).Page(page).Execute()
if err != nil {
return nil, fmt.Errorf("listing sqlserverflex flavors: %w", err)
}
if res.Flavors == nil {
return nil, fmt.Errorf("finding flavors for project %s", projectId)
}
pagination := res.GetPagination()
flavors := res.GetFlavors()
flavorList = append(flavorList, flavors...)
if *pagination.TotalRows < int64(len(flavorList)) {
return nil, fmt.Errorf("total rows is smaller than current accumulated list - that should not happen")
}
if *pagination.TotalRows == int64(len(flavorList)) {
break
}
page++
if page > *pagination.TotalPages {
break
}
// implement a breakpoint
counter++
if counter > 1000 {
panic("too many pagination results")
}
getAllFilter := func(_ sqlserverflexalpha.ListFlavors) bool { return true }
flavorList, err := getFlavorsByFilter(ctx, client, projectId, region, getAllFilter)
if err != nil {
return nil, err
}
return flavorList, nil
}
// func getFlavorModelById(ctx context.Context, client flavorsClient, model *Model, flavor *flavorModel) error {
// if model == nil {
// return fmt.Errorf("nil model")
// }
// if flavor == nil {
// return fmt.Errorf("nil flavor")
// }
// id := conversion.StringValueToPointer(flavor.Id)
// if id == nil {
// return fmt.Errorf("nil flavor ID")
// }
//
// flavor.Id = types.StringValue("")
//
// projectId := model.ProjectId.ValueString()
// region := model.Region.ValueString()
//
// flavorList, err := getAllFlavors(ctx, client, projectId, region)
// if err != nil {
// return err
// }
//
// avl := ""
// for _, f := range flavorList {
// if f.Id == nil || f.Cpu == nil || f.Memory == nil {
// continue
// }
// if *f.Id == *id {
// flavor.Id = types.StringValue(*f.Id)
// flavor.Description = types.StringValue(*f.Description)
// flavor.CPU = types.Int64Value(*f.Cpu)
// flavor.RAM = types.Int64Value(*f.Memory)
// flavor.NodeType = types.StringValue(*f.NodeType)
// break
// }
// avl = fmt.Sprintf("%s\n- %d CPU, %d GB RAM", avl, *f.Cpu, *f.Memory)
// }
// if flavor.Id.ValueString() == "" {
// return fmt.Errorf("couldn't find flavor, available specs are: %s", avl)
// }
//
// return nil
//}
// getFlavorsByFilter is a helper function to retrieve flavors using a filtern function.
// Hint: The API does not have a GetFlavors endpoint, only ListFlavors
func getFlavorsByFilter(
ctx context.Context,
client flavorsClientReader,
projectId, region string,
filter func(db sqlserverflexalpha.ListFlavors) bool,
) ([]sqlserverflexalpha.ListFlavors, error) {
if projectId == "" || region == "" {
return nil, fmt.Errorf("listing sqlserverflexalpha flavors: projectId and region are required")
}
const pageSize = 25
var result = make([]sqlserverflexalpha.ListFlavors, 0)
for page := int64(1); ; page++ {
res, err := client.GetFlavorsRequest(ctx, projectId, region).
Page(page).Size(pageSize).Sort(sqlserverflexalpha.FLAVORSORT_INDEX_ASC).Execute()
if err != nil {
return nil, fmt.Errorf("requesting flavors list (page %d): %w", page, err)
}
// If the API returns no flavors, we have reached the end of the list.
if res.Flavors == nil || len(*res.Flavors) == 0 {
break
}
for _, flavor := range *res.Flavors {
if filter(flavor) {
result = append(result, flavor)
}
}
}
return result, nil
}

View file

@ -0,0 +1,137 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: Apache-2.0
package sqlserverFlexAlphaFlavor
import (
"context"
"testing"
"github.com/mhenselin/terraform-provider-stackitprivatepreview/pkg/sqlserverflexalpha"
"github.com/stackitcloud/stackit-sdk-go/core/utils"
)
type mockRequest struct {
executeFunc func() (*sqlserverflexalpha.GetFlavorsResponse, error)
}
func (m *mockRequest) Page(_ int64) sqlserverflexalpha.ApiGetFlavorsRequestRequest { return m }
func (m *mockRequest) Size(_ int64) sqlserverflexalpha.ApiGetFlavorsRequestRequest { return m }
func (m *mockRequest) Sort(_ sqlserverflexalpha.FlavorSort) sqlserverflexalpha.ApiGetFlavorsRequestRequest {
return m
}
func (m *mockRequest) Execute() (*sqlserverflexalpha.GetFlavorsResponse, error) {
return m.executeFunc()
}
type mockFlavorsClient struct {
executeRequest func() sqlserverflexalpha.ApiGetFlavorsRequestRequest
}
func (m *mockFlavorsClient) GetFlavorsRequest(_ context.Context, _, _ string) sqlserverflexalpha.ApiGetFlavorsRequestRequest {
return m.executeRequest()
}
var mockResp = func(page int64) (*sqlserverflexalpha.GetFlavorsResponse, error) {
if page == 1 {
return &sqlserverflexalpha.GetFlavorsResponse{
Flavors: &[]sqlserverflexalpha.ListFlavors{
{Id: utils.Ptr("flavor-1"), Description: utils.Ptr("first")},
{Id: utils.Ptr("flavor-2"), Description: utils.Ptr("second")},
},
}, nil
}
if page == 2 {
return &sqlserverflexalpha.GetFlavorsResponse{
Flavors: &[]sqlserverflexalpha.ListFlavors{
{Id: utils.Ptr("flavor-3"), Description: utils.Ptr("three")},
},
}, nil
}
return &sqlserverflexalpha.GetFlavorsResponse{
Flavors: &[]sqlserverflexalpha.ListFlavors{},
}, nil
}
func TestGetFlavorsByFilter(t *testing.T) {
tests := []struct {
description string
projectId string
region string
mockErr error
filter func(sqlserverflexalpha.ListFlavors) bool
wantCount int
wantErr bool
}{
{
description: "Success - Get all flavors (2 pages)",
projectId: "pid", region: "reg",
filter: func(_ sqlserverflexalpha.ListFlavors) bool { return true },
wantCount: 3,
wantErr: false,
},
{
description: "Success - Filter flavors by description",
projectId: "pid", region: "reg",
filter: func(f sqlserverflexalpha.ListFlavors) bool { return *f.Description == "first" },
wantCount: 1,
wantErr: false,
},
{
description: "Error - Missing parameters",
projectId: "", region: "reg",
wantErr: true,
},
}
for _, tt := range tests {
t.Run(
tt.description, func(t *testing.T) {
var currentPage int64
client := &mockFlavorsClient{
executeRequest: func() sqlserverflexalpha.ApiGetFlavorsRequestRequest {
return &mockRequest{
executeFunc: func() (*sqlserverflexalpha.GetFlavorsResponse, error) {
currentPage++
return mockResp(currentPage)
},
}
},
}
actual, err := getFlavorsByFilter(context.Background(), client, tt.projectId, tt.region, tt.filter)
if (err != nil) != tt.wantErr {
t.Errorf("getFlavorsByFilter() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !tt.wantErr && len(actual) != tt.wantCount {
t.Errorf("getFlavorsByFilter() got %d flavors, want %d", len(actual), tt.wantCount)
}
},
)
}
}
func TestGetAllFlavors(t *testing.T) {
var currentPage int64
client := &mockFlavorsClient{
executeRequest: func() sqlserverflexalpha.ApiGetFlavorsRequestRequest {
return &mockRequest{
executeFunc: func() (*sqlserverflexalpha.GetFlavorsResponse, error) {
currentPage++
return mockResp(currentPage)
},
}
},
}
res, err := getAllFlavors(context.Background(), client, "pid", "reg")
if err != nil {
t.Errorf("getAllFlavors() unexpected error: %v", err)
}
if len(res) != 3 {
t.Errorf("getAllFlavors() expected 3 flavor, got %d", len(res))
}
}

View file

@ -1,79 +0,0 @@
package postgresFlexAlphaFlavor
import (
"context"
"github.com/mhenselin/terraform-provider-stackitprivatepreview/pkg/postgresflexalpha"
"github.com/mhenselin/terraform-provider-stackitprivatepreview/stackit/internal/conversion"
"github.com/mhenselin/terraform-provider-stackitprivatepreview/stackit/internal/services/postgresflexalpha"
postgresflexUtils "github.com/mhenselin/terraform-provider-stackitprivatepreview/stackit/internal/services/postgresflexalpha/utils"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/mhenselin/terraform-provider-stackitprivatepreview/stackit/internal/core"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ datasource.DataSource = &flavorListDataSource{}
)
// NewFlavorListDataSource is a helper function to simplify the provider implementation.
func NewFlavorListDataSource() datasource.DataSource {
return &flavorListDataSource{}
}
// flavorDataSource is the data source implementation.
type flavorListDataSource struct {
client *postgresflexalpha.APIClient
providerData core.ProviderData
}
// Metadata returns the data source type name.
func (r *flavorListDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_postgresflexalpha_flavorlist"
}
// Configure adds the provider configured client to the data source.
func (r *flavorListDataSource) 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 {
return
}
apiClient := postgresflexUtils.ConfigureClient(ctx, &r.providerData, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}
r.client = apiClient
tflog.Info(ctx, "Postgres Flex flavors client configured")
}
func (r *flavorListDataSource) Schema(ctx context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
resp.Schema = postgresflex.FlavorDataSourceSchema(ctx)
}
func (r *flavorListDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
var model postgresflex.FlavorModel
diags := req.Config.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
ctx = core.InitProviderContext(ctx)
projectId := model.ProjectId.ValueString()
region := r.providerData.GetRegionWithOverride(model.Region)
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "region", region)
// Set refreshed state
diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "Postgres Flex flavors read")
}