diff --git a/internal/common/conversion/type_conversion.go b/internal/common/conversion/type_conversion.go index 539dbea6b5..cbc1f17f75 100644 --- a/internal/common/conversion/type_conversion.go +++ b/internal/common/conversion/type_conversion.go @@ -56,3 +56,17 @@ func IsStringPresent(strPtr *string) bool { func MongoDBRegionToAWSRegion(region string) string { return strings.ReplaceAll(strings.ToLower(region), "_", "-") } + +func SlicePtrToSlice[T any](v *[]T) []T { + if v == nil { + return nil + } + return *v +} + +func NonEmptySliceToPtrSlice[T any](v []T) *[]T { + if len(v) == 0 { + return nil + } + return &v +} diff --git a/internal/service/alertconfiguration/data_source_alert_configuration.go b/internal/service/alertconfiguration/data_source_alert_configuration.go index 082419f1a9..33e6fa77ba 100644 --- a/internal/service/alertconfiguration/data_source_alert_configuration.go +++ b/internal/service/alertconfiguration/data_source_alert_configuration.go @@ -319,7 +319,7 @@ func outputAlertConfigurationResourceHcl(label string, alert *admin.GroupAlertsC resource.SetAttributeValue("enabled", cty.BoolVal(*alert.Enabled)) } - for _, matcher := range alert.Matchers { + for _, matcher := range conversion.SlicePtrToSlice(alert.Matchers) { appendBlockWithCtyValues(resource, "matcher", []string{}, convertMatcherToCtyValues(matcher)) } @@ -331,8 +331,9 @@ func outputAlertConfigurationResourceHcl(label string, alert *admin.GroupAlertsC appendBlockWithCtyValues(resource, "threshold_config", []string{}, convertThresholdToCtyValues(alert.Threshold)) } - for i := 0; i < len(alert.Notifications); i++ { - appendBlockWithCtyValues(resource, "notification", []string{}, convertNotificationToCtyValues(&alert.Notifications[i])) + notifications := conversion.SlicePtrToSlice(alert.Notifications) + for i := 0; i < len(notifications); i++ { + appendBlockWithCtyValues(resource, "notification", []string{}, convertNotificationToCtyValues(¬ifications[i])) } return string(f.Bytes()) @@ -438,16 +439,14 @@ func convertNotificationToCtyValues(notification *admin.AlertsNotificationRootFo values["sms_enabled"] = cty.BoolVal(*notification.SmsEnabled) } - if len(notification.Roles) > 0 { - roles := make([]cty.Value, 0) - - for _, r := range notification.Roles { + if roles := conversion.SlicePtrToSlice(notification.Roles); len(roles) > 0 { + roleList := make([]cty.Value, 0) + for _, r := range roles { if r != "" { - roles = append(roles, cty.StringVal(r)) + roleList = append(roleList, cty.StringVal(r)) } } - - values["roles"] = cty.TupleVal(roles) + values["roles"] = cty.TupleVal(roleList) } return values diff --git a/internal/service/alertconfiguration/data_source_alert_configurations.go b/internal/service/alertconfiguration/data_source_alert_configurations.go index 7ecb7b5761..018b8afa17 100644 --- a/internal/service/alertconfiguration/data_source_alert_configurations.go +++ b/internal/service/alertconfiguration/data_source_alert_configurations.go @@ -143,7 +143,7 @@ func (d *AlertConfigurationsDS) Read(ctx context.Context, req datasource.ReadReq alertConfigurationsConfig.ID = types.StringValue(conversion.EncodeStateID(map[string]string{ "project_id": projectID, })) - alertConfigurationsConfig.Results = NewTFAlertConfigurationDSModelList(alerts.Results, projectID, alertConfigurationsConfig.OutputType) + alertConfigurationsConfig.Results = NewTFAlertConfigurationDSModelList(conversion.SlicePtrToSlice(alerts.Results), projectID, alertConfigurationsConfig.OutputType) if *params.IncludeCount { alertConfigurationsConfig.TotalCount = types.Int64Value(int64(*alerts.TotalCount)) } diff --git a/internal/service/alertconfiguration/model_alert_configuration.go b/internal/service/alertconfiguration/model_alert_configuration.go index eb48f0bd2e..9e03779127 100644 --- a/internal/service/alertconfiguration/model_alert_configuration.go +++ b/internal/service/alertconfiguration/model_alert_configuration.go @@ -43,7 +43,7 @@ func NewNotificationList(tfNotificationSlice []TfNotificationModel) ([]admin.Ale Username: n.Username.ValueStringPointer(), VictorOpsApiKey: n.VictorOpsAPIKey.ValueStringPointer(), VictorOpsRoutingKey: n.VictorOpsRoutingKey.ValueStringPointer(), - Roles: n.Roles, + Roles: conversion.NonEmptySliceToPtrSlice(n.Roles), MicrosoftTeamsWebhookUrl: n.MicrosoftTeamsWebhookURL.ValueStringPointer(), WebhookSecret: n.WebhookSecret.ValueStringPointer(), WebhookUrl: n.WebhookURL.ValueStringPointer(), @@ -108,8 +108,8 @@ func NewTFAlertConfigurationModel(apiRespConfig *admin.GroupAlertsConfig, currSt Enabled: types.BoolPointerValue(apiRespConfig.Enabled), MetricThresholdConfig: NewTFMetricThresholdConfigModel(apiRespConfig.MetricThreshold, currState.MetricThresholdConfig), ThresholdConfig: NewTFThresholdConfigModel(apiRespConfig.Threshold, currState.ThresholdConfig), - Notification: NewTFNotificationModelList(apiRespConfig.Notifications, currState.Notification), - Matcher: NewTFMatcherModelList(apiRespConfig.Matchers, currState.Matcher), + Notification: NewTFNotificationModelList(conversion.SlicePtrToSlice(apiRespConfig.Notifications), currState.Notification), + Matcher: NewTFMatcherModelList(conversion.SlicePtrToSlice(apiRespConfig.Matchers), currState.Matcher), } } @@ -121,7 +121,7 @@ func NewTFNotificationModelList(n []admin.AlertsNotificationRootForGroup, currSt value := n[i] notifications[i] = TfNotificationModel{ TeamName: conversion.StringPtrNullIfEmpty(value.TeamName), - Roles: value.Roles, + Roles: conversion.SlicePtrToSlice(value.Roles), ChannelName: conversion.StringPtrNullIfEmpty(value.ChannelName), DatadogRegion: conversion.StringPtrNullIfEmpty(value.DatadogRegion), DelayMin: types.Int64PointerValue(conversion.IntPtrToInt64Ptr(value.DelayMin)), @@ -145,7 +145,7 @@ func NewTFNotificationModelList(n []admin.AlertsNotificationRootForGroup, currSt currState := currStateNotifications[i] newState := TfNotificationModel{ TeamName: conversion.StringPtrNullIfEmpty(value.TeamName), - Roles: value.Roles, + Roles: conversion.SlicePtrToSlice(value.Roles), // sentive attributes do not use value returned from API APIToken: conversion.StringNullIfEmpty(currState.APIToken.ValueString()), DatadogAPIKey: conversion.StringNullIfEmpty(currState.DatadogAPIKey.ValueString()), @@ -303,8 +303,8 @@ func NewTfAlertConfigurationDSModel(apiRespConfig *admin.GroupAlertsConfig, proj Enabled: types.BoolPointerValue(apiRespConfig.Enabled), MetricThresholdConfig: NewTFMetricThresholdConfigModel(apiRespConfig.MetricThreshold, []TfMetricThresholdConfigModel{}), ThresholdConfig: NewTFThresholdConfigModel(apiRespConfig.Threshold, []TfThresholdConfigModel{}), - Notification: NewTFNotificationModelList(apiRespConfig.Notifications, []TfNotificationModel{}), - Matcher: NewTFMatcherModelList(apiRespConfig.Matchers, []TfMatcherModel{}), + Notification: NewTFNotificationModelList(conversion.SlicePtrToSlice(apiRespConfig.Notifications), []TfNotificationModel{}), + Matcher: NewTFMatcherModelList(conversion.SlicePtrToSlice(apiRespConfig.Matchers), []TfMatcherModel{}), } } diff --git a/internal/service/alertconfiguration/model_alert_configuration_test.go b/internal/service/alertconfiguration/model_alert_configuration_test.go index bcdc1423f1..bfcb295d12 100644 --- a/internal/service/alertconfiguration/model_alert_configuration_test.go +++ b/internal/service/alertconfiguration/model_alert_configuration_test.go @@ -45,7 +45,7 @@ func TestNotificationSDKToTFModel(t *testing.T) { SmsEnabled: admin.PtrBool(disabled), EmailEnabled: admin.PtrBool(enabled), ChannelName: admin.PtrString("#channel"), - Roles: roles, + Roles: conversion.NonEmptySliceToPtrSlice(roles), ApiToken: admin.PtrString("newApiToken"), }, }, @@ -290,7 +290,7 @@ func TestNotificationTFModelToSDK(t *testing.T) { DelayMin: admin.PtrInt(delayMin), SmsEnabled: admin.PtrBool(disabled), EmailEnabled: admin.PtrBool(enabled), - Roles: roles, + Roles: conversion.NonEmptySliceToPtrSlice(roles), }, }, }, diff --git a/internal/service/alertconfiguration/resource_alert_configuration.go b/internal/service/alertconfiguration/resource_alert_configuration.go index 037e0e0b6b..b48828b4ef 100644 --- a/internal/service/alertconfiguration/resource_alert_configuration.go +++ b/internal/service/alertconfiguration/resource_alert_configuration.go @@ -380,7 +380,7 @@ func (r *alertConfigurationRS) Create(ctx context.Context, req resource.CreateRe apiReq := &admin.GroupAlertsConfig{ EventTypeName: alertConfigPlan.EventType.ValueStringPointer(), Enabled: alertConfigPlan.Enabled.ValueBoolPointer(), - Matchers: NewMatcherList(alertConfigPlan.Matcher), + Matchers: conversion.NonEmptySliceToPtrSlice(NewMatcherList(alertConfigPlan.Matcher)), MetricThreshold: NewMetricThreshold(alertConfigPlan.MetricThresholdConfig), Threshold: NewThreshold(alertConfigPlan.ThresholdConfig), } @@ -390,7 +390,7 @@ func (r *alertConfigurationRS) Create(ctx context.Context, req resource.CreateRe resp.Diagnostics.AddError(errorCreateAlertConf, err.Error()) return } - apiReq.Notifications = notifications + apiReq.Notifications = conversion.NonEmptySliceToPtrSlice(notifications) apiResp, _, err := connV2.AlertConfigurationsApi.CreateAlertConfiguration(ctx, projectID, apiReq).Execute() if err != nil { @@ -482,7 +482,7 @@ func (r *alertConfigurationRS) Update(ctx context.Context, req resource.UpdateRe } if !reflect.DeepEqual(alertConfigPlan.Matcher, alertConfigState.Matcher) { - apiReq.Matchers = NewMatcherList(alertConfigPlan.Matcher) + apiReq.Matchers = conversion.NonEmptySliceToPtrSlice(NewMatcherList(alertConfigPlan.Matcher)) } // Always refresh structure to handle service keys being obfuscated coming back from read API call @@ -491,7 +491,7 @@ func (r *alertConfigurationRS) Update(ctx context.Context, req resource.UpdateRe resp.Diagnostics.AddError(errorUpdateAlertConf, err.Error()) return } - apiReq.Notifications = notifications + apiReq.Notifications = conversion.NonEmptySliceToPtrSlice(notifications) var updatedAlertConfigResp *admin.GroupAlertsConfig diff --git a/internal/service/atlasuser/data_source_atlas_user.go b/internal/service/atlasuser/data_source_atlas_user.go index d508fd118a..72b9c77a0f 100644 --- a/internal/service/atlasuser/data_source_atlas_user.go +++ b/internal/service/atlasuser/data_source_atlas_user.go @@ -189,9 +189,9 @@ func newTFAtlasUserDSModel(user *admin.CloudAppUser) tfAtlasUserDSModel { LastAuth: types.StringPointerValue(conversion.TimePtrToStringPtr(user.LastAuth)), LastName: types.StringValue(user.LastName), MobileNumber: types.StringValue(user.MobileNumber), - TeamIDs: user.TeamIds, - Links: newTFLinksList(user.Links), - Roles: newTFRolesList(user.Roles), + TeamIDs: conversion.SlicePtrToSlice(user.TeamIds), + Links: newTFLinksList(conversion.SlicePtrToSlice(user.Links)), + Roles: newTFRolesList(conversion.SlicePtrToSlice(user.Roles)), } } diff --git a/internal/service/atlasuser/data_source_atlas_user_test.go b/internal/service/atlasuser/data_source_atlas_user_test.go index 701ede7b46..ad37cc608e 100644 --- a/internal/service/atlasuser/data_source_atlas_user_test.go +++ b/internal/service/atlasuser/data_source_atlas_user_test.go @@ -66,8 +66,8 @@ func dataSourceChecksForUser(dataSourceName, attrPrefix string, user *admin.Clou resource.TestCheckResourceAttr(dataSourceName, fmt.Sprintf("%smobile_number", attrPrefix), user.MobileNumber), resource.TestCheckResourceAttr(dataSourceName, fmt.Sprintf("%scountry", attrPrefix), user.Country), resource.TestCheckResourceAttr(dataSourceName, fmt.Sprintf("%screated_at", attrPrefix), *conversion.TimePtrToStringPtr(user.CreatedAt)), - resource.TestCheckResourceAttr(dataSourceName, fmt.Sprintf("%steam_ids.#", attrPrefix), fmt.Sprintf("%d", len(user.TeamIds))), - resource.TestCheckResourceAttr(dataSourceName, fmt.Sprintf("%slinks.#", attrPrefix), fmt.Sprintf("%d", len(user.Links))), + resource.TestCheckResourceAttr(dataSourceName, fmt.Sprintf("%steam_ids.#", attrPrefix), fmt.Sprintf("%d", len(*user.TeamIds))), + resource.TestCheckResourceAttr(dataSourceName, fmt.Sprintf("%slinks.#", attrPrefix), fmt.Sprintf("%d", len(*user.Links))), // for assertion of roles the values of `user.Roles` must not be used as it has the risk of flaky executions. CLOUDP-220377 resource.TestCheckResourceAttrWith(dataSourceName, fmt.Sprintf("%sroles.#", attrPrefix), acc.IntGreatThan(0)), resource.TestCheckResourceAttrSet(dataSourceName, fmt.Sprintf("%sroles.0.role_name", attrPrefix)), diff --git a/internal/service/atlasuser/data_source_atlas_users.go b/internal/service/atlasuser/data_source_atlas_users.go index cc16da601d..81e8b543cd 100644 --- a/internal/service/atlasuser/data_source_atlas_users.go +++ b/internal/service/atlasuser/data_source_atlas_users.go @@ -191,7 +191,7 @@ func (d *atlasUsersDS) Read(ctx context.Context, req datasource.ReadRequest, res resp.Diagnostics.AddError("error when getting users from Atlas", fmt.Sprintf(errorUsersRead, "project", projectID, err.Error())) return } - users = apiResp.Results + users = conversion.SlicePtrToSlice(apiResp.Results) totalCount = *apiResp.TotalCount case !atlasUsersConfig.TeamID.IsNull() && !atlasUsersConfig.OrgID.IsNull(): teamID := atlasUsersConfig.TeamID.ValueString() @@ -205,7 +205,7 @@ func (d *atlasUsersDS) Read(ctx context.Context, req datasource.ReadRequest, res resp.Diagnostics.AddError("error when getting users from Atlas", fmt.Sprintf(errorUsersRead, "team", teamID, err.Error())) return } - users = apiResp.Results + users = conversion.SlicePtrToSlice(apiResp.Results) totalCount = *apiResp.TotalCount default: // only org_id is defined orgID := atlasUsersConfig.OrgID.ValueString() @@ -218,7 +218,7 @@ func (d *atlasUsersDS) Read(ctx context.Context, req datasource.ReadRequest, res resp.Diagnostics.AddError("error when getting users from Atlas", fmt.Sprintf(errorUsersRead, "org", orgID, err.Error())) return } - users = apiResp.Results + users = conversion.SlicePtrToSlice(apiResp.Results) totalCount = *apiResp.TotalCount } diff --git a/internal/service/atlasuser/data_source_atlas_users_test.go b/internal/service/atlasuser/data_source_atlas_users_test.go index ec9abf3aeb..0d3376d4f7 100644 --- a/internal/service/atlasuser/data_source_atlas_users_test.go +++ b/internal/service/atlasuser/data_source_atlas_users_test.go @@ -223,8 +223,8 @@ func dataSourceChecksForUsers(dataSourceName, orgID string, users *admin.Paginat resource.TestCheckResourceAttr(dataSourceName, "org_id", orgID), resource.TestCheckResourceAttr(dataSourceName, "total_count", fmt.Sprintf("%d", totalCountValue)), } - for i := range users.Results { - checks = append(checks, dataSourceChecksForUser(dataSourceName, fmt.Sprintf("results.%d.", i), &users.Results[i])...) + for i := range *users.Results { + checks = append(checks, dataSourceChecksForUser(dataSourceName, fmt.Sprintf("results.%d.", i), &(*users.Results)[i])...) } return checks diff --git a/internal/service/databaseuser/model_database_user.go b/internal/service/databaseuser/model_database_user.go index 9ea7e08cb5..b86f7e9169 100644 --- a/internal/service/databaseuser/model_database_user.go +++ b/internal/service/databaseuser/model_database_user.go @@ -40,24 +40,24 @@ func NewMongoDBDatabaseUser(ctx context.Context, dbUserModel *TfDatabaseUserMode OidcAuthType: dbUserModel.OIDCAuthType.ValueStringPointer(), LdapAuthType: dbUserModel.LDAPAuthType.ValueStringPointer(), DatabaseName: dbUserModel.AuthDatabaseName.ValueString(), - Roles: NewMongoDBAtlasRoles(rolesModel), - Labels: NewMongoDBAtlasLabels(labelsModel), - Scopes: NewMongoDBAtlasScopes(scopesModel), + Roles: conversion.NonEmptySliceToPtrSlice(NewMongoDBAtlasRoles(rolesModel)), + Labels: conversion.NonEmptySliceToPtrSlice(NewMongoDBAtlasLabels(labelsModel)), + Scopes: conversion.NonEmptySliceToPtrSlice(NewMongoDBAtlasScopes(scopesModel)), }, nil } func NewTfDatabaseUserModel(ctx context.Context, model *TfDatabaseUserModel, dbUser *admin.CloudDatabaseUser) (*TfDatabaseUserModel, diag.Diagnostics) { - rolesSet, diagnostic := types.SetValueFrom(ctx, RoleObjectType, NewTFRolesModel(dbUser.Roles)) + rolesSet, diagnostic := types.SetValueFrom(ctx, RoleObjectType, NewTFRolesModel(conversion.SlicePtrToSlice(dbUser.Roles))) if diagnostic.HasError() { return nil, diagnostic } - labelsSet, diagnostic := types.SetValueFrom(ctx, LabelObjectType, NewTFLabelsModel(dbUser.Labels)) + labelsSet, diagnostic := types.SetValueFrom(ctx, LabelObjectType, NewTFLabelsModel(conversion.SlicePtrToSlice(dbUser.Labels))) if diagnostic.HasError() { return nil, diagnostic } - scopesSet, diagnostic := types.SetValueFrom(ctx, ScopeObjectType, NewTFScopesModel(dbUser.Scopes)) + scopesSet, diagnostic := types.SetValueFrom(ctx, ScopeObjectType, NewTFScopesModel(conversion.SlicePtrToSlice(dbUser.Scopes))) if diagnostic.HasError() { return nil, diagnostic } @@ -102,9 +102,9 @@ func NewTFDatabaseDSUserModel(ctx context.Context, dbUser *admin.CloudDatabaseUs OIDCAuthType: types.StringValue(dbUser.GetOidcAuthType()), LDAPAuthType: types.StringValue(dbUser.GetLdapAuthType()), AWSIAMType: types.StringValue(dbUser.GetAwsIAMType()), - Roles: NewTFRolesModel(dbUser.Roles), - Labels: NewTFLabelsModel(dbUser.Labels), - Scopes: NewTFScopesModel(dbUser.Scopes), + Roles: NewTFRolesModel(conversion.SlicePtrToSlice(dbUser.Roles)), + Labels: NewTFLabelsModel(conversion.SlicePtrToSlice(dbUser.Labels)), + Scopes: NewTFScopesModel(conversion.SlicePtrToSlice(dbUser.Scopes)), } return databaseUserModel, nil diff --git a/internal/service/databaseuser/model_database_user_test.go b/internal/service/databaseuser/model_database_user_test.go index 48fd6a3823..ebae7a0f3f 100644 --- a/internal/service/databaseuser/model_database_user_test.go +++ b/internal/service/databaseuser/model_database_user_test.go @@ -69,9 +69,9 @@ var ( OidcAuthType: &oidCAuthType, LdapAuthType: &ldapAuthType, AwsIAMType: &awsIAMType, - Roles: []admin.DatabaseUserRole{sdkRole}, - Labels: []admin.ComponentLabel{sdkLabel}, - Scopes: []admin.UserScope{sdkScope}, + Roles: &[]admin.DatabaseUserRole{sdkRole}, + Labels: &[]admin.ComponentLabel{sdkLabel}, + Scopes: &[]admin.UserScope{sdkScope}, } ) diff --git a/internal/service/federateddatabaseinstance/data_source_federated_database_instance.go b/internal/service/federateddatabaseinstance/data_source_federated_database_instance.go index 6aa8c171f2..c9ea9c38c1 100644 --- a/internal/service/federateddatabaseinstance/data_source_federated_database_instance.go +++ b/internal/service/federateddatabaseinstance/data_source_federated_database_instance.go @@ -347,13 +347,13 @@ func dataSourceMongoDBAtlasFederatedDatabaseInstanceRead(ctx context.Context, d return diag.FromErr(fmt.Errorf(errorFederatedDatabaseInstanceSetting, "data_process_region", name, err)) } - if storageDatabaseField := flattenDataFederationDatabase(dataFederationInstance.Storage.Databases); storageDatabaseField != nil { + if storageDatabaseField := flattenDataFederationDatabase(conversion.SlicePtrToSlice(dataFederationInstance.Storage.Databases)); storageDatabaseField != nil { if err := d.Set("storage_databases", storageDatabaseField); err != nil { return diag.FromErr(fmt.Errorf(errorFederatedDatabaseInstanceSetting, "storage_databases", name, err)) } } - if err := d.Set("storage_stores", flattenDataFederationStores(dataFederationInstance.Storage.Stores)); err != nil { + if err := d.Set("storage_stores", flattenDataFederationStores(conversion.SlicePtrToSlice(dataFederationInstance.Storage.Stores))); err != nil { return diag.FromErr(fmt.Errorf(errorFederatedDatabaseInstanceSetting, "storage_stores", name, err)) } diff --git a/internal/service/federateddatabaseinstance/data_source_federated_database_instances.go b/internal/service/federateddatabaseinstance/data_source_federated_database_instances.go index d0e93fc9cb..44c7b49347 100644 --- a/internal/service/federateddatabaseinstance/data_source_federated_database_instances.go +++ b/internal/service/federateddatabaseinstance/data_source_federated_database_instances.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/config" ) @@ -146,8 +147,8 @@ func flattenFederatedDatabaseInstances(d *schema.ResourceData, projectID string, "hostnames": federatedDatabaseInstances[i].GetHostnames(), "cloud_provider_config": flattenCloudProviderConfig(d, federatedDatabaseInstances[i].CloudProviderConfig), "data_process_region": flattenDataProcessRegion(federatedDatabaseInstances[i].DataProcessRegion), - "storage_databases": flattenDataFederationDatabase(federatedDatabaseInstances[i].Storage.Databases), - "storage_stores": flattenDataFederationStores(federatedDatabaseInstances[i].Storage.Stores), + "storage_databases": flattenDataFederationDatabase(conversion.SlicePtrToSlice(federatedDatabaseInstances[i].Storage.Databases)), + "storage_stores": flattenDataFederationStores(conversion.SlicePtrToSlice(federatedDatabaseInstances[i].Storage.Stores)), } } } diff --git a/internal/service/federateddatabaseinstance/resource_federated_database_instance.go b/internal/service/federateddatabaseinstance/resource_federated_database_instance.go index 93266a88fa..a53cf8b5d6 100644 --- a/internal/service/federateddatabaseinstance/resource_federated_database_instance.go +++ b/internal/service/federateddatabaseinstance/resource_federated_database_instance.go @@ -496,7 +496,7 @@ func resourceMongoDBAtlasFederatedDatabaseInstanceImportState(ctx context.Contex if storage, ok := dataFederationInstance.GetStorageOk(); ok { if databases, ok := storage.GetDatabasesOk(); ok { - if storageDatabaseField := flattenDataFederationDatabase(databases); storageDatabaseField != nil { + if storageDatabaseField := flattenDataFederationDatabase(conversion.SlicePtrToSlice(databases)); storageDatabaseField != nil { if err := d.Set("storage_databases", storageDatabaseField); err != nil { return nil, fmt.Errorf(errorFederatedDatabaseInstanceSetting, "storage_databases", name, err) } @@ -504,7 +504,7 @@ func resourceMongoDBAtlasFederatedDatabaseInstanceImportState(ctx context.Contex } if stores, ok := storage.GetStoresOk(); ok { - if err := d.Set("storage_stores", flattenDataFederationStores(stores)); err != nil { + if err := d.Set("storage_stores", flattenDataFederationStores(conversion.SlicePtrToSlice(stores))); err != nil { return nil, fmt.Errorf(errorFederatedDatabaseInstanceSetting, "storage_stores", name, err) } } @@ -528,8 +528,8 @@ func resourceMongoDBAtlasFederatedDatabaseInstanceImportState(ctx context.Contex func newDataFederationStorage(d *schema.ResourceData) *admin.DataLakeStorage { return &admin.DataLakeStorage{ - Databases: newDataFederationDatabase(d), - Stores: newStores(d), + Databases: conversion.NonEmptySliceToPtrSlice(newDataFederationDatabase(d)), + Stores: conversion.NonEmptySliceToPtrSlice(newStores(d)), } } @@ -552,7 +552,7 @@ func newStores(d *schema.ResourceData) []admin.DataLakeStoreSettings { Prefix: conversion.StringPtr(storeFromConfMap["prefix"].(string)), Delimiter: conversion.StringPtr(storeFromConfMap["delimiter"].(string)), IncludeTags: conversion.Pointer(storeFromConfMap["include_tags"].(bool)), - AdditionalStorageClasses: newAdditionalStorageClasses(storeFromConfMap["additional_storage_classes"].([]any)), + AdditionalStorageClasses: conversion.NonEmptySliceToPtrSlice(newAdditionalStorageClasses(storeFromConfMap["additional_storage_classes"].([]any))), ReadPreference: newReadPreference(storeFromConfMap), } } @@ -582,7 +582,7 @@ func newReadPreference(storeFromConfMap map[string]any) *admin.DataLakeAtlasStor return &admin.DataLakeAtlasStoreReadPreference{ Mode: conversion.StringPtr(readPreferenceFromConfMap["mode"].(string)), MaxStalenessSeconds: conversion.IntPtr(readPreferenceFromConfMap["max_staleness_seconds"].(int)), - TagSets: newTagSets(readPreferenceFromConfMap), + TagSets: conversion.NonEmptySliceToPtrSlice(newTagSets(readPreferenceFromConfMap)), } } @@ -626,7 +626,7 @@ func newDataFederationDatabase(d *schema.ResourceData) []admin.DataLakeDatabaseI dbs[i] = admin.DataLakeDatabaseInstance{ Name: conversion.StringPtr(storageDBFromConfMap["name"].(string)), MaxWildcardCollections: conversion.IntPtr(storageDBFromConfMap["max_wildcard_collections"].(int)), - Collections: newDataFederationCollections(storageDBFromConfMap), + Collections: conversion.NonEmptySliceToPtrSlice(newDataFederationCollections(storageDBFromConfMap)), } } @@ -643,7 +643,7 @@ func newDataFederationCollections(storageDBFromConfMap map[string]any) []admin.D for i, collectionFromConf := range collectionsFromConf { collections[i] = admin.DataLakeDatabaseCollection{ Name: conversion.StringPtr(collectionFromConf.(map[string]any)["name"].(string)), - DataSources: newDataFederationDataSource(collectionFromConf.(map[string]any)), + DataSources: conversion.NonEmptySliceToPtrSlice(newDataFederationDataSource(collectionFromConf.(map[string]any))), } } @@ -670,7 +670,7 @@ func newDataFederationDataSource(collectionFromConf map[string]any) []admin.Data ProvenanceFieldName: conversion.StringPtr(dataSourceFromConfMap["provenance_field_name"].(string)), StoreName: conversion.StringPtr(dataSourceFromConfMap["store_name"].(string)), DatasetName: conversion.StringPtr(dataSourceFromConfMap["dataset_name"].(string)), - Urls: newUrls(dataSourceFromConfMap["urls"].([]any)), + Urls: conversion.NonEmptySliceToPtrSlice(newUrls(dataSourceFromConfMap["urls"].([]any))), } } @@ -777,8 +777,8 @@ func flattenDataFederationDatabase(atlasDatabases []admin.DataLakeDatabaseInstan dbs[i] = map[string]any{ "name": atlasDatabase.GetName(), "max_wildcard_collections": atlasDatabase.GetMaxWildcardCollections(), - "collections": flattenDataFederationCollections(atlasDatabase.Collections), - "views": flattenDataFederationDatabaseViews(atlasDatabase.Views), + "collections": flattenDataFederationCollections(conversion.SlicePtrToSlice(atlasDatabase.Collections)), + "views": flattenDataFederationDatabaseViews(conversion.SlicePtrToSlice(atlasDatabase.Views)), } } @@ -805,7 +805,7 @@ func flattenDataFederationCollections(atlasCollections []admin.DataLakeDatabaseC for i, atlasCollection := range atlasCollections { colls[i] = map[string]any{ "name": atlasCollection.GetName(), - "data_sources": flattenDataFederationDataSources(atlasCollection.DataSources), + "data_sources": flattenDataFederationDataSources(conversion.SlicePtrToSlice(atlasCollection.DataSources)), } } @@ -869,7 +869,7 @@ func newReadPreferenceField(atlasReadPreference *admin.DataLakeAtlasStoreReadPre { "mode": atlasReadPreference.GetMode(), "max_staleness_seconds": atlasReadPreference.GetMaxStalenessSeconds(), - "tag_sets": flattenReadPreferenceTagSets(atlasReadPreference.TagSets), + "tag_sets": flattenReadPreferenceTagSets(conversion.SlicePtrToSlice(atlasReadPreference.TagSets)), }, } } diff --git a/internal/service/federatedsettingsidentityprovider/data_source_federated_settings_identity_provider.go b/internal/service/federatedsettingsidentityprovider/data_source_federated_settings_identity_provider.go index 37b89142ed..ecb26f4c92 100644 --- a/internal/service/federatedsettingsidentityprovider/data_source_federated_settings_identity_provider.go +++ b/internal/service/federatedsettingsidentityprovider/data_source_federated_settings_identity_provider.go @@ -242,7 +242,7 @@ func dataSourceMongoDBAtlasFederatedSettingsIdentityProviderRead(ctx context.Con return diag.FromErr(fmt.Errorf("error setting `associated_domains` for federatedSettings IdentityProviders: %s", err)) } - if err := d.Set("associated_orgs", FlattenAssociatedOrgs(federatedSettingsIdentityProvider.AssociatedOrgs)); err != nil { + if err := d.Set("associated_orgs", FlattenAssociatedOrgs(conversion.SlicePtrToSlice(federatedSettingsIdentityProvider.AssociatedOrgs))); err != nil { return diag.FromErr(fmt.Errorf("error setting `associated_orgs` for federatedSettings IdentityProviders: %s", err)) } diff --git a/internal/service/federatedsettingsidentityprovider/model_federated_settings_identity_provider.go b/internal/service/federatedsettingsidentityprovider/model_federated_settings_identity_provider.go index 3228ff8871..75770af640 100644 --- a/internal/service/federatedsettingsidentityprovider/model_federated_settings_identity_provider.go +++ b/internal/service/federatedsettingsidentityprovider/model_federated_settings_identity_provider.go @@ -19,7 +19,7 @@ func FlattenFederatedSettingsIdentityProvider(federatedSettingsIdentityProvider federatedSettingsIdentityProviderMap[i] = map[string]any{ "acs_url": federatedSettingsIdentityProvider[i].AcsUrl, "associated_domains": federatedSettingsIdentityProvider[i].AssociatedDomains, - "associated_orgs": FlattenAssociatedOrgs(federatedSettingsIdentityProvider[i].AssociatedOrgs), + "associated_orgs": FlattenAssociatedOrgs(conversion.SlicePtrToSlice(federatedSettingsIdentityProvider[i].AssociatedOrgs)), "audience_uri": federatedSettingsIdentityProvider[i].AudienceUri, "display_name": federatedSettingsIdentityProvider[i].DisplayName, "issuer_uri": federatedSettingsIdentityProvider[i].IssuerUri, @@ -53,7 +53,7 @@ func FlattenAssociatedOrgs(associatedOrgs []admin.ConnectedOrgConfig) []map[stri "identity_provider_id": associatedOrgs[i].IdentityProviderId, "org_id": associatedOrgs[i].OrgId, "post_auth_role_grants": associatedOrgs[i].PostAuthRoleGrants, - "role_mappings": FlattenAuthFederationRoleMapping(associatedOrgs[i].RoleMappings), + "role_mappings": FlattenAuthFederationRoleMapping(conversion.SlicePtrToSlice(associatedOrgs[i].RoleMappings)), "user_conflicts": nil, } } else { @@ -63,8 +63,8 @@ func FlattenAssociatedOrgs(associatedOrgs []admin.ConnectedOrgConfig) []map[stri "identity_provider_id": associatedOrgs[i].IdentityProviderId, "org_id": associatedOrgs[i].OrgId, "post_auth_role_grants": associatedOrgs[i].PostAuthRoleGrants, - "role_mappings": FlattenAuthFederationRoleMapping(associatedOrgs[i].RoleMappings), - "user_conflicts": FlattenFederatedUser(associatedOrgs[i].UserConflicts), + "role_mappings": FlattenAuthFederationRoleMapping(conversion.SlicePtrToSlice(associatedOrgs[i].RoleMappings)), + "user_conflicts": FlattenFederatedUser(conversion.SlicePtrToSlice(associatedOrgs[i].UserConflicts)), } } } @@ -154,7 +154,7 @@ func FlattenAuthFederationRoleMapping(roleMappings []admin.AuthFederationRoleMap roleMappingsMap[i] = map[string]any{ "external_group_name": roleMappings[i].ExternalGroupName, "id": roleMappings[i].Id, - "role_assignments": FlattenRoleAssignmentsV2(roleMappings[i].RoleAssignments), + "role_assignments": FlattenRoleAssignmentsV2(conversion.SlicePtrToSlice(roleMappings[i].RoleAssignments)), } } } @@ -165,11 +165,11 @@ func FlattenAuthFederationRoleMapping(roleMappings []admin.AuthFederationRoleMap func FlattenPemFileInfo(pemFileInfo admin.PemFileInfo) []map[string]any { var pemFileInfoMap []map[string]any - if len(pemFileInfo.Certificates) > 0 { + if certificates := conversion.SlicePtrToSlice(pemFileInfo.Certificates); len(certificates) > 0 { pemFileInfoMap = make([]map[string]any, 1) pemFileInfoMap[0] = map[string]any{ - "certificates": FlattenFederatedSettingsCertificates(pemFileInfo.Certificates), + "certificates": FlattenFederatedSettingsCertificates(certificates), "file_name": pemFileInfo.FileName, } } diff --git a/internal/service/federatedsettingsidentityprovider/resource_federated_settings_identity_provider.go b/internal/service/federatedsettingsidentityprovider/resource_federated_settings_identity_provider.go index cf0510dc22..aec5af4c51 100644 --- a/internal/service/federatedsettingsidentityprovider/resource_federated_settings_identity_provider.go +++ b/internal/service/federatedsettingsidentityprovider/resource_federated_settings_identity_provider.go @@ -237,7 +237,7 @@ func resourceMongoDBAtlasFederatedSettingsIdentityProviderUpdate(ctx context.Con if d.HasChange("associated_domains") { associatedDomains := d.Get("associated_domains") - updateRequest.AssociatedDomains = cast.ToStringSlice(associatedDomains) + updateRequest.AssociatedDomains = conversion.NonEmptySliceToPtrSlice(cast.ToStringSlice(associatedDomains)) } if d.HasChange("name") { diff --git a/internal/service/onlinearchive/data_source_online_archive.go b/internal/service/onlinearchive/data_source_online_archive.go index e7097eb365..60e5640f83 100644 --- a/internal/service/onlinearchive/data_source_online_archive.go +++ b/internal/service/onlinearchive/data_source_online_archive.go @@ -255,10 +255,10 @@ func dataSourceMongoDBAtlasOnlineArchivesRead(ctx context.Context, d *schema.Res return diag.FromErr(fmt.Errorf("error getting Online Archives list for project(%s) in cluster (%s): (%s)", projectID, clusterName, err.Error())) } - results := make([]map[string]any, 0, len(archives.Results)) - - for i := range archives.Results { - archiveData := fromOnlineArchiveToMap(&archives.Results[i]) + input := conversion.SlicePtrToSlice(archives.Results) + results := make([]map[string]any, 0, len(input)) + for i := range input { + archiveData := fromOnlineArchiveToMap(&input[i]) archiveData["project_id"] = projectID results = append(results, archiveData) } diff --git a/internal/service/onlinearchive/resource_online_archive.go b/internal/service/onlinearchive/resource_online_archive.go index 01eb0a1a5d..e189a6a69e 100644 --- a/internal/service/onlinearchive/resource_online_archive.go +++ b/internal/service/onlinearchive/resource_online_archive.go @@ -414,7 +414,7 @@ func mapToArchivePayload(d *schema.ResourceData) admin.BackupOnlineArchiveCreate partitionList = append(partitionList, query) } - requestInput.PartitionFields = partitionList + requestInput.PartitionFields = conversion.NonEmptySliceToPtrSlice(partitionList) } } @@ -568,13 +568,12 @@ func fromOnlineArchiveToMap(in *admin.BackupOnlineArchive) map[string]any { schemaVals["data_process_region"] = []any{dataProcessRegion} } - // partitions fields - if len(in.PartitionFields) == 0 { + partitionFields := conversion.SlicePtrToSlice(in.PartitionFields) + if len(partitionFields) == 0 { return schemaVals } - - partitionFieldsMap := make([]map[string]any, 0, len(in.PartitionFields)) - for _, field := range in.PartitionFields { + partitionFieldsMap := make([]map[string]any, 0, len(partitionFields)) + for _, field := range partitionFields { fieldMap := map[string]any{ "field_name": field.FieldName, "field_type": field.FieldType, diff --git a/internal/service/project/data_source_project_test.go b/internal/service/project/data_source_project_test.go index bb99a711fe..a51a1e4a6e 100644 --- a/internal/service/project/data_source_project_test.go +++ b/internal/service/project/data_source_project_test.go @@ -27,11 +27,11 @@ func TestAccProjectDSProject_byID(t *testing.T) { []*admin.TeamRole{ { TeamId: conversion.StringPtr(acc.GetProjectTeamsIdsWithPos(0)), - RoleNames: []string{"GROUP_READ_ONLY", "GROUP_DATA_ACCESS_ADMIN"}, + RoleNames: &[]string{"GROUP_READ_ONLY", "GROUP_DATA_ACCESS_ADMIN"}, }, { TeamId: conversion.StringPtr(acc.GetProjectTeamsIdsWithPos(1)), - RoleNames: []string{"GROUP_DATA_ACCESS_ADMIN", "GROUP_OWNER"}, + RoleNames: &[]string{"GROUP_DATA_ACCESS_ADMIN", "GROUP_OWNER"}, }, }, )), @@ -59,12 +59,12 @@ func TestAccProjectDSProject_byName(t *testing.T) { []*admin.TeamRole{ { TeamId: conversion.StringPtr(acc.GetProjectTeamsIdsWithPos(0)), - RoleNames: []string{"GROUP_READ_ONLY", "GROUP_DATA_ACCESS_ADMIN"}, + RoleNames: &[]string{"GROUP_READ_ONLY", "GROUP_DATA_ACCESS_ADMIN"}, }, { TeamId: conversion.StringPtr(acc.GetProjectTeamsIdsWithPos(1)), - RoleNames: []string{"GROUP_DATA_ACCESS_ADMIN", "GROUP_OWNER"}, + RoleNames: &[]string{"GROUP_DATA_ACCESS_ADMIN", "GROUP_OWNER"}, }, }, )), @@ -92,12 +92,12 @@ func TestAccProjectDSProject_defaultFlags(t *testing.T) { []*admin.TeamRole{ { TeamId: conversion.StringPtr(acc.GetProjectTeamsIdsWithPos(0)), - RoleNames: []string{"GROUP_READ_ONLY", "GROUP_DATA_ACCESS_ADMIN"}, + RoleNames: &[]string{"GROUP_READ_ONLY", "GROUP_DATA_ACCESS_ADMIN"}, }, { TeamId: conversion.StringPtr(acc.GetProjectTeamsIdsWithPos(1)), - RoleNames: []string{"GROUP_DATA_ACCESS_ADMIN", "GROUP_OWNER"}, + RoleNames: &[]string{"GROUP_DATA_ACCESS_ADMIN", "GROUP_OWNER"}, }, }, )), diff --git a/internal/service/project/data_source_projects.go b/internal/service/project/data_source_projects.go index 022af1dbdc..4aa49505f3 100644 --- a/internal/service/project/data_source_projects.go +++ b/internal/service/project/data_source_projects.go @@ -170,9 +170,10 @@ func (d *ProjectsDS) Read(ctx context.Context, req datasource.ReadRequest, resp } func populateProjectsDataSourceModel(ctx context.Context, connV2 *admin.APIClient, stateModel *tfProjectsDSModel, projectsRes *admin.PaginatedAtlasGroup) error { - results := make([]*TfProjectDSModel, 0, len(projectsRes.Results)) - for i := range projectsRes.Results { - project := projectsRes.Results[i] + input := conversion.SlicePtrToSlice(projectsRes.Results) + results := make([]*TfProjectDSModel, 0, len(input)) + for i := range input { + project := input[i] atlasTeams, atlasLimits, atlasProjectSettings, err := GetProjectPropsFromAPI(ctx, ServiceFromClient(connV2), project.GetId()) if err == nil { // if the project is still valid, e.g. could have just been deleted projectModel := NewTFProjectDataSourceModel(ctx, &project, atlasTeams, atlasProjectSettings, atlasLimits) diff --git a/internal/service/project/data_source_projects_test.go b/internal/service/project/data_source_projects_test.go index ccdbf4c66c..2bcc24eb27 100644 --- a/internal/service/project/data_source_projects_test.go +++ b/internal/service/project/data_source_projects_test.go @@ -27,11 +27,11 @@ func TestAccProjectDSProjects_basic(t *testing.T) { []*admin.TeamRole{ { TeamId: conversion.StringPtr(acc.GetProjectTeamsIdsWithPos(0)), - RoleNames: []string{"GROUP_READ_ONLY", "GROUP_DATA_ACCESS_ADMIN"}, + RoleNames: &[]string{"GROUP_READ_ONLY", "GROUP_DATA_ACCESS_ADMIN"}, }, { TeamId: conversion.StringPtr(acc.GetProjectTeamsIdsWithPos(1)), - RoleNames: []string{"GROUP_DATA_ACCESS_ADMIN", "GROUP_OWNER"}, + RoleNames: &[]string{"GROUP_DATA_ACCESS_ADMIN", "GROUP_OWNER"}, }, }, ), @@ -62,11 +62,11 @@ func TestAccProjectDSProjects_withPagination(t *testing.T) { []*admin.TeamRole{ { TeamId: conversion.StringPtr(acc.GetProjectTeamsIdsWithPos(0)), - RoleNames: []string{"GROUP_READ_ONLY", "GROUP_DATA_ACCESS_ADMIN"}, + RoleNames: &[]string{"GROUP_READ_ONLY", "GROUP_DATA_ACCESS_ADMIN"}, }, { TeamId: conversion.StringPtr(acc.GetProjectTeamsIdsWithPos(1)), - RoleNames: []string{"GROUP_DATA_ACCESS_ADMIN", "GROUP_OWNER"}, + RoleNames: &[]string{"GROUP_DATA_ACCESS_ADMIN", "GROUP_OWNER"}, }, }, 2, 5, diff --git a/internal/service/project/model_project.go b/internal/service/project/model_project.go index 1ee707d429..d4c4100e9c 100644 --- a/internal/service/project/model_project.go +++ b/internal/service/project/model_project.go @@ -32,11 +32,10 @@ func NewTFTeamsDataSourceModel(ctx context.Context, atlasTeams *admin.PaginatedT if atlasTeams.GetTotalCount() == 0 { return nil } - teams := make([]*TfTeamDSModel, len(atlasTeams.Results)) - - for i, atlasTeam := range atlasTeams.Results { + results := conversion.SlicePtrToSlice(atlasTeams.Results) + teams := make([]*TfTeamDSModel, len(results)) + for i, atlasTeam := range results { roleNames, _ := types.ListValueFrom(ctx, types.StringType, atlasTeam.RoleNames) - teams[i] = &TfTeamDSModel{ TeamID: types.StringValue(atlasTeam.GetTeamId()), RoleNames: roleNames, @@ -104,11 +103,10 @@ func newTFLimitsResourceModel(ctx context.Context, dataFederationLimits []admin. } func newTFTeamsResourceModel(ctx context.Context, atlasTeams *admin.PaginatedTeamRole) types.Set { - teams := make([]TfTeamModel, len(atlasTeams.Results)) - - for i, atlasTeam := range atlasTeams.Results { + results := conversion.SlicePtrToSlice(atlasTeams.Results) + teams := make([]TfTeamModel, len(results)) + for i, atlasTeam := range results { roleNames, _ := types.SetValueFrom(ctx, types.StringType, atlasTeam.RoleNames) - teams[i] = TfTeamModel{ TeamID: types.StringValue(atlasTeam.GetTeamId()), RoleNames: roleNames, @@ -125,7 +123,7 @@ func NewTeamRoleList(ctx context.Context, teams []TfTeamModel) *[]admin.TeamRole for i, team := range teams { res[i] = admin.TeamRole{ TeamId: team.TeamID.ValueStringPointer(), - RoleNames: conversion.TypesSetToString(ctx, team.RoleNames), + RoleNames: conversion.NonEmptySliceToPtrSlice(conversion.TypesSetToString(ctx, team.RoleNames)), } } return &res diff --git a/internal/service/project/model_project_test.go b/internal/service/project/model_project_test.go index 17887436c9..c6f736a0df 100644 --- a/internal/service/project/model_project_test.go +++ b/internal/service/project/model_project_test.go @@ -30,7 +30,7 @@ var ( teamRolesSDK = []admin.TeamRole{ { TeamId: conversion.StringPtr("teamId"), - RoleNames: roles, + RoleNames: conversion.NonEmptySliceToPtrSlice(roles), }, } teamsDSTF = []*project.TfTeamDSModel{ @@ -88,7 +88,7 @@ func TestTeamsDataSourceSDKToTFModel(t *testing.T) { { name: "Complete TeamRole", paginatedTeamRole: &admin.PaginatedTeamRole{ - Results: teamRolesSDK, + Results: conversion.NonEmptySliceToPtrSlice(teamRolesSDK), TotalCount: conversion.IntPtr(1), }, expectedTFModel: teamsDSTF, @@ -141,7 +141,7 @@ func TestProjectDataSourceSDKToTFModel(t *testing.T) { name: "Project", project: &projectSDK, teams: &admin.PaginatedTeamRole{ - Results: teamRolesSDK, + Results: conversion.NonEmptySliceToPtrSlice(teamRolesSDK), TotalCount: conversion.IntPtr(1), }, projectSettings: &projectSettingsSDK, diff --git a/internal/service/project/resource_project.go b/internal/service/project/resource_project.go index 4efab44a4f..541128d95a 100644 --- a/internal/service/project/resource_project.go +++ b/internal/service/project/resource_project.go @@ -675,7 +675,7 @@ func UpdateProjectTeams(ctx context.Context, client GroupProjectService, project _, _, err := client.UpdateTeamRoles(ctx, projectID, teamID, &admin.TeamRole{ - RoleNames: conversion.TypesSetToString(ctx, team.RoleNames), + RoleNames: conversion.NonEmptySliceToPtrSlice(conversion.TypesSetToString(ctx, team.RoleNames)), }, ) if err != nil { @@ -768,8 +768,9 @@ func ResourceProjectDependentsDeletingRefreshFunc(ctx context.Context, projectID return dependents, projectDependentsStateIdle, nil } - for i := range dependents.AdvancedClusters.Results { - if *dependents.AdvancedClusters.Results[i].StateName != projectDependentsStateDeleting { + results := conversion.SlicePtrToSlice(dependents.AdvancedClusters.Results) + for i := range results { + if *results[i].StateName != projectDependentsStateDeleting { return dependents, projectDependentsStateIdle, nil } } diff --git a/internal/service/project/resource_project_migration_test.go b/internal/service/project/resource_project_migration_test.go index 0760959aad..fddc639ed8 100644 --- a/internal/service/project/resource_project_migration_test.go +++ b/internal/service/project/resource_project_migration_test.go @@ -68,11 +68,11 @@ func TestAccMigrationProjectRS_Teams(t *testing.T) { []*admin.TeamRole{ { TeamId: &teamsIds[0], - RoleNames: []string{"GROUP_READ_ONLY", "GROUP_DATA_ACCESS_ADMIN"}, + RoleNames: &[]string{"GROUP_READ_ONLY", "GROUP_DATA_ACCESS_ADMIN"}, }, { TeamId: &teamsIds[1], - RoleNames: []string{"GROUP_DATA_ACCESS_ADMIN", "GROUP_OWNER"}, + RoleNames: &[]string{"GROUP_DATA_ACCESS_ADMIN", "GROUP_OWNER"}, }, }) ) diff --git a/internal/service/project/resource_project_test.go b/internal/service/project/resource_project_test.go index b70c8439a6..4864953d4d 100644 --- a/internal/service/project/resource_project_test.go +++ b/internal/service/project/resource_project_test.go @@ -433,7 +433,7 @@ func TestResourceProjectDependentsDeletingRefreshFunc(t *testing.T) { mockResponses: AdvancedClusterDescriptionResponse{ AdvancedClusterDescription: &admin.PaginatedAdvancedClusterDescription{ TotalCount: conversion.IntPtr(2), - Results: []admin.AdvancedClusterDescription{ + Results: &[]admin.AdvancedClusterDescription{ {StateName: conversion.StringPtr("IDLE")}, {StateName: conversion.StringPtr("DELETING")}, }, @@ -477,11 +477,11 @@ func TestAccProjectRSProject_basic(t *testing.T) { []*admin.TeamRole{ { TeamId: conversion.StringPtr(acc.GetProjectTeamsIdsWithPos(0)), - RoleNames: []string{"GROUP_READ_ONLY", "GROUP_DATA_ACCESS_ADMIN"}, + RoleNames: &[]string{"GROUP_READ_ONLY", "GROUP_DATA_ACCESS_ADMIN"}, }, { TeamId: conversion.StringPtr(acc.GetProjectTeamsIdsWithPos(1)), - RoleNames: []string{"GROUP_DATA_ACCESS_ADMIN", "GROUP_OWNER"}, + RoleNames: &[]string{"GROUP_DATA_ACCESS_ADMIN", "GROUP_OWNER"}, }, }, ), @@ -499,15 +499,15 @@ func TestAccProjectRSProject_basic(t *testing.T) { []*admin.TeamRole{ { TeamId: conversion.StringPtr(acc.GetProjectTeamsIdsWithPos(0)), - RoleNames: []string{"GROUP_OWNER"}, + RoleNames: &[]string{"GROUP_OWNER"}, }, { TeamId: conversion.StringPtr(acc.GetProjectTeamsIdsWithPos(1)), - RoleNames: []string{"GROUP_DATA_ACCESS_READ_WRITE"}, + RoleNames: &[]string{"GROUP_DATA_ACCESS_READ_WRITE"}, }, { TeamId: conversion.StringPtr(acc.GetProjectTeamsIdsWithPos(2)), - RoleNames: []string{"GROUP_READ_ONLY", "GROUP_DATA_ACCESS_ADMIN"}, + RoleNames: &[]string{"GROUP_READ_ONLY", "GROUP_DATA_ACCESS_ADMIN"}, }, }, ), @@ -526,11 +526,11 @@ func TestAccProjectRSProject_basic(t *testing.T) { []*admin.TeamRole{ { TeamId: conversion.StringPtr(acc.GetProjectTeamsIdsWithPos(0)), - RoleNames: []string{"GROUP_READ_ONLY", "GROUP_READ_ONLY"}, + RoleNames: &[]string{"GROUP_READ_ONLY", "GROUP_READ_ONLY"}, }, { TeamId: conversion.StringPtr(acc.GetProjectTeamsIdsWithPos(1)), - RoleNames: []string{"GROUP_OWNER", "GROUP_DATA_ACCESS_ADMIN"}, + RoleNames: &[]string{"GROUP_OWNER", "GROUP_DATA_ACCESS_ADMIN"}, }, }, ), diff --git a/internal/service/searchdeployment/model_search_deployment.go b/internal/service/searchdeployment/model_search_deployment.go index 39a3696c90..e7567e8cb7 100644 --- a/internal/service/searchdeployment/model_search_deployment.go +++ b/internal/service/searchdeployment/model_search_deployment.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-framework-timeouts/resource/timeouts" "github.com/hashicorp/terraform-plugin-framework/diag" "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "go.mongodb.org/atlas-sdk/v20231115003/admin" ) @@ -22,7 +23,7 @@ func NewSearchDeploymentReq(ctx context.Context, searchDeploymentPlan *TFSearchD } return admin.ApiSearchDeploymentRequest{ - Specs: resultSpecs, + Specs: conversion.NonEmptySliceToPtrSlice(resultSpecs), } } @@ -38,7 +39,7 @@ func NewTFSearchDeployment(ctx context.Context, clusterName string, deployResp * result.Timeouts = *timeout } - specsList, diagnostics := types.ListValueFrom(ctx, SpecObjectType, newTFSpecsModel(deployResp.Specs)) + specsList, diagnostics := types.ListValueFrom(ctx, SpecObjectType, newTFSpecsModel(conversion.SlicePtrToSlice(deployResp.Specs))) if diagnostics.HasError() { return nil, diagnostics } diff --git a/internal/service/searchdeployment/model_search_deployment_test.go b/internal/service/searchdeployment/model_search_deployment_test.go index 3914d23768..d74d9db54d 100644 --- a/internal/service/searchdeployment/model_search_deployment_test.go +++ b/internal/service/searchdeployment/model_search_deployment_test.go @@ -36,7 +36,7 @@ func TestSearchDeploymentSDKToTFModel(t *testing.T) { Id: admin.PtrString(dummyDeploymentID), GroupId: admin.PtrString(dummyProjectID), StateName: admin.PtrString(stateName), - Specs: []admin.ApiSearchDeploymentSpec{ + Specs: &[]admin.ApiSearchDeploymentSpec{ { InstanceSize: instanceSize, NodeCount: nodeCount, @@ -84,7 +84,7 @@ func TestSearchDeploymentTFModelToSDK(t *testing.T) { Specs: tfSpecsList(t, instanceSize, nodeCount), }, expectedSDKReq: admin.ApiSearchDeploymentRequest{ - Specs: []admin.ApiSearchDeploymentSpec{ + Specs: &[]admin.ApiSearchDeploymentSpec{ { InstanceSize: instanceSize, NodeCount: nodeCount, diff --git a/internal/service/searchdeployment/state_transition_search_deployment_test.go b/internal/service/searchdeployment/state_transition_search_deployment_test.go index 96de1a075a..d074002102 100644 --- a/internal/service/searchdeployment/state_transition_search_deployment_test.go +++ b/internal/service/searchdeployment/state_transition_search_deployment_test.go @@ -140,7 +140,7 @@ func responseWithState(state *string) *admin.ApiSearchDeploymentResponse { return &admin.ApiSearchDeploymentResponse{ GroupId: admin.PtrString(dummyProjectID), Id: admin.PtrString(dummyDeploymentID), - Specs: []admin.ApiSearchDeploymentSpec{ + Specs: &[]admin.ApiSearchDeploymentSpec{ { InstanceSize: instanceSize, NodeCount: nodeCount, diff --git a/internal/service/searchindex/data_source_search_index.go b/internal/service/searchindex/data_source_search_index.go index 4a2ce89959..ee02bfcbb8 100644 --- a/internal/service/searchindex/data_source_search_index.go +++ b/internal/service/searchindex/data_source_search_index.go @@ -128,8 +128,8 @@ func dataSourceMongoDBAtlasSearchIndexRead(ctx context.Context, d *schema.Resour return diag.Errorf("error setting `analyzer` for search index (%s): %s", d.Id(), err) } - if len(searchIndex.Analyzers) > 0 { - searchIndexMappingFields, err := marshalSearchIndex(searchIndex.Analyzers) + if analyzers := conversion.SlicePtrToSlice(searchIndex.Analyzers); len(analyzers) > 0 { + searchIndexMappingFields, err := marshalSearchIndex(analyzers) if err != nil { return diag.FromErr(err) } @@ -155,7 +155,7 @@ func dataSourceMongoDBAtlasSearchIndexRead(ctx context.Context, d *schema.Resour return diag.Errorf("error setting `searchAnalyzer` for search index (%s): %s", d.Id(), err) } - if err := d.Set("synonyms", flattenSearchIndexSynonyms(searchIndex.Synonyms)); err != nil { + if err := d.Set("synonyms", flattenSearchIndexSynonyms(conversion.SlicePtrToSlice(searchIndex.Synonyms))); err != nil { return diag.Errorf("error setting `synonyms` for search index (%s): %s", d.Id(), err) } @@ -175,13 +175,13 @@ func dataSourceMongoDBAtlasSearchIndexRead(ctx context.Context, d *schema.Resour } } - if len(searchIndex.Fields) > 0 { - fields, err := marshalSearchIndex(searchIndex.Fields) + if fields := conversion.SlicePtrToSlice(searchIndex.Fields); len(fields) > 0 { + fieldsMarshaled, err := marshalSearchIndex(fields) if err != nil { return diag.FromErr(err) } - if err := d.Set("fields", fields); err != nil { + if err := d.Set("fields", fieldsMarshaled); err != nil { return diag.Errorf("error setting `fields` for for search index (%s): %s", d.Id(), err) } } diff --git a/internal/service/searchindex/data_source_search_indexes.go b/internal/service/searchindex/data_source_search_indexes.go index 31675fbdc3..250d7adf02 100644 --- a/internal/service/searchindex/data_source_search_indexes.go +++ b/internal/service/searchindex/data_source_search_indexes.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/constant" + "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/config" "go.mongodb.org/atlas-sdk/v20231115003/admin" ) @@ -111,7 +112,7 @@ func flattenSearchIndexes(searchIndexes []admin.ClusterSearchIndex, projectID, c "name": searchIndexes[i].Name, "search_analyzer": searchIndexes[i].SearchAnalyzer, "status": searchIndexes[i].Status, - "synonyms": flattenSearchIndexSynonyms(searchIndexes[i].Synonyms), + "synonyms": flattenSearchIndexSynonyms(conversion.SlicePtrToSlice(searchIndexes[i].Synonyms)), "type": searchIndexes[i].Type, } @@ -127,20 +128,20 @@ func flattenSearchIndexes(searchIndexes []admin.ClusterSearchIndex, projectID, c } } - if len(searchIndexes[i].Analyzers) > 0 { - searchIndexAnalyzers, err := marshalSearchIndex(searchIndexes[i].Analyzers) + if analyzers := conversion.SlicePtrToSlice(searchIndexes[i].Analyzers); len(analyzers) > 0 { + searchIndexAnalyzers, err := marshalSearchIndex(analyzers) if err != nil { return nil, err } searchIndexesMap[i]["analyzers"] = searchIndexAnalyzers } - if len(searchIndexes[i].Fields) > 0 { - fields, err := marshalSearchIndex(searchIndexes[i].Fields) + if fields := conversion.SlicePtrToSlice(searchIndexes[i].Fields); len(fields) > 0 { + fieldsMarshaled, err := marshalSearchIndex(fields) if err != nil { return nil, err } - searchIndexesMap[i]["fields"] = fields + searchIndexesMap[i]["fields"] = fieldsMarshaled } } diff --git a/internal/service/searchindex/resource_search_index.go b/internal/service/searchindex/resource_search_index.go index fe01df9dc9..cb79f9c976 100644 --- a/internal/service/searchindex/resource_search_index.go +++ b/internal/service/searchindex/resource_search_index.go @@ -224,7 +224,7 @@ func resourceMongoDBAtlasSearchIndexUpdate(ctx context.Context, d *schema.Resour if err != nil { return err } - searchIndex.Analyzers = analyzers + searchIndex.Analyzers = conversion.NonEmptySliceToPtrSlice(analyzers) } if d.HasChange("mappings_dynamic") { @@ -251,11 +251,11 @@ func resourceMongoDBAtlasSearchIndexUpdate(ctx context.Context, d *schema.Resour if err != nil { return err } - searchIndex.Fields = fields + searchIndex.Fields = conversion.NonEmptySliceToPtrSlice(fields) } if d.HasChange("synonyms") { - searchIndex.Synonyms = expandSearchIndexSynonyms(d) + searchIndex.Synonyms = conversion.NonEmptySliceToPtrSlice(expandSearchIndexSynonyms(d)) } searchIndex.IndexID = conversion.StringPtr("") @@ -320,8 +320,8 @@ func resourceMongoDBAtlasSearchIndexRead(ctx context.Context, d *schema.Resource return diag.Errorf("error setting `analyzer` for search index (%s): %s", d.Id(), err) } - if len(searchIndex.Analyzers) > 0 { - searchIndexMappingFields, err := marshalSearchIndex(searchIndex.Analyzers) + if analyzers := conversion.SlicePtrToSlice(searchIndex.Analyzers); len(analyzers) > 0 { + searchIndexMappingFields, err := marshalSearchIndex(analyzers) if err != nil { return diag.FromErr(err) } @@ -347,7 +347,7 @@ func resourceMongoDBAtlasSearchIndexRead(ctx context.Context, d *schema.Resource return diag.Errorf("error setting `searchAnalyzer` for search index (%s): %s", d.Id(), err) } - if err := d.Set("synonyms", flattenSearchIndexSynonyms(searchIndex.Synonyms)); err != nil { + if err := d.Set("synonyms", flattenSearchIndexSynonyms(conversion.SlicePtrToSlice(searchIndex.Synonyms))); err != nil { return diag.Errorf("error setting `synonyms` for search index (%s): %s", d.Id(), err) } @@ -368,8 +368,8 @@ func resourceMongoDBAtlasSearchIndexRead(ctx context.Context, d *schema.Resource } } - if len(searchIndex.Fields) > 0 { - fields, err := marshalSearchIndex(searchIndex.Fields) + if fields := conversion.SlicePtrToSlice(searchIndex.Fields); len(fields) > 0 { + fields, err := marshalSearchIndex(fields) if err != nil { return diag.FromErr(err) } @@ -413,7 +413,7 @@ func resourceMongoDBAtlasSearchIndexCreate(ctx context.Context, d *schema.Resour Name: d.Get("name").(string), SearchAnalyzer: conversion.StringPtr(d.Get("search_analyzer").(string)), Status: conversion.StringPtr(d.Get("status").(string)), - Synonyms: expandSearchIndexSynonyms(d), + Synonyms: conversion.NonEmptySliceToPtrSlice(expandSearchIndexSynonyms(d)), } if indexType == vectorSearch { @@ -421,13 +421,13 @@ func resourceMongoDBAtlasSearchIndexCreate(ctx context.Context, d *schema.Resour if err != nil { return err } - searchIndexRequest.Fields = fields + searchIndexRequest.Fields = conversion.NonEmptySliceToPtrSlice(fields) } else { analyzers, err := unmarshalSearchIndexAnalyzersFields(d.Get("analyzers").(string)) if err != nil { return err } - searchIndexRequest.Analyzers = analyzers + searchIndexRequest.Analyzers = conversion.NonEmptySliceToPtrSlice(analyzers) mappingsFields, err := unmarshalSearchIndexMappingFields(d.Get("mappings_fields").(string)) if err != nil { return err diff --git a/internal/service/sharedtier/data_source_cloud_shared_tier_restore_jobs.go b/internal/service/sharedtier/data_source_cloud_shared_tier_restore_jobs.go index a1d9b4c214..f43dbed500 100644 --- a/internal/service/sharedtier/data_source_cloud_shared_tier_restore_jobs.go +++ b/internal/service/sharedtier/data_source_cloud_shared_tier_restore_jobs.go @@ -97,7 +97,7 @@ func dataSourceMongoDBAtlasCloudSharedTierRestoreJobRead(ctx context.Context, d return diag.FromErr(fmt.Errorf("error getting shared tier restore jobs for cluster '%s': %w", clusterName, err)) } - if err := d.Set("results", flattenShardTierRestoreJobs(jobs.Results)); err != nil { + if err := d.Set("results", flattenShardTierRestoreJobs(conversion.SlicePtrToSlice(jobs.Results))); err != nil { return diag.FromErr(fmt.Errorf("error setting `results`: %w", err)) } diff --git a/internal/service/sharedtier/data_source_shared_tier_snapshots.go b/internal/service/sharedtier/data_source_shared_tier_snapshots.go index a75cbf16d0..e3f30a78d5 100644 --- a/internal/service/sharedtier/data_source_shared_tier_snapshots.go +++ b/internal/service/sharedtier/data_source_shared_tier_snapshots.go @@ -80,7 +80,7 @@ func dataSourceMongoDBAtlasSharedTierSnapshotsRead(ctx context.Context, d *schem return diag.FromErr(fmt.Errorf("error getting shard-tier snapshots for cluster '%s': %w", clusterName, err)) } - if err := d.Set("results", flattenSharedTierSnapshots(snapshots.Results)); err != nil { + if err := d.Set("results", flattenSharedTierSnapshots(conversion.SlicePtrToSlice(snapshots.Results))); err != nil { return diag.FromErr(fmt.Errorf("error setting `results`: %w", err)) } diff --git a/internal/service/streamconnection/model_stream_connection.go b/internal/service/streamconnection/model_stream_connection.go index b7aafee88b..72b035959a 100644 --- a/internal/service/streamconnection/model_stream_connection.go +++ b/internal/service/streamconnection/model_stream_connection.go @@ -122,11 +122,12 @@ func newTFConnectionAuthenticationModel(ctx context.Context, currAuthConfig *typ func NewTFStreamConnections(ctx context.Context, streamConnectionsConfig *TFStreamConnectionsDSModel, paginatedResult *admin.PaginatedApiStreamsConnection) (*TFStreamConnectionsDSModel, diag.Diagnostics) { - results := make([]TFStreamConnectionModel, len(paginatedResult.Results)) - for i := range paginatedResult.Results { + input := conversion.SlicePtrToSlice(paginatedResult.Results) + results := make([]TFStreamConnectionModel, len(input)) + for i := range input { projectID := streamConnectionsConfig.ProjectID.ValueString() instanceName := streamConnectionsConfig.InstanceName.ValueString() - connectionModel, diags := NewTFStreamConnection(ctx, projectID, instanceName, nil, &paginatedResult.Results[i]) + connectionModel, diags := NewTFStreamConnection(ctx, projectID, instanceName, nil, &input[i]) if diags.HasError() { return nil, diags } diff --git a/internal/service/streamconnection/model_stream_connection_test.go b/internal/service/streamconnection/model_stream_connection_test.go index 0ba584cda0..bc727ce58e 100644 --- a/internal/service/streamconnection/model_stream_connection_test.go +++ b/internal/service/streamconnection/model_stream_connection_test.go @@ -168,7 +168,7 @@ func TestStreamConnectionsSDKToTFModel(t *testing.T) { { name: "Complete SDK response with configured page options", SDKResp: &admin.PaginatedApiStreamsConnection{ - Results: []admin.StreamsConnection{ + Results: &[]admin.StreamsConnection{ { Name: admin.PtrString(connectionName), Type: admin.PtrString("Kafka"), @@ -232,7 +232,7 @@ func TestStreamConnectionsSDKToTFModel(t *testing.T) { { name: "Without defining page options", SDKResp: &admin.PaginatedApiStreamsConnection{ - Results: []admin.StreamsConnection{}, + Results: &[]admin.StreamsConnection{}, TotalCount: admin.PtrInt(0), }, providedConfig: &streamconnection.TFStreamConnectionsDSModel{ diff --git a/internal/service/streaminstance/model_stream_instance.go b/internal/service/streaminstance/model_stream_instance.go index d54f7e1de4..998fa30736 100644 --- a/internal/service/streaminstance/model_stream_instance.go +++ b/internal/service/streaminstance/model_stream_instance.go @@ -63,9 +63,10 @@ func NewTFStreamInstance(ctx context.Context, apiResp *admin.StreamsTenant) (*TF } func NewTFStreamInstances(ctx context.Context, streamInstancesConfig *TFStreamInstancesModel, paginatedResult *admin.PaginatedApiStreamsTenant) (*TFStreamInstancesModel, diag.Diagnostics) { - results := make([]TFStreamInstanceModel, len(paginatedResult.Results)) - for i := range paginatedResult.Results { - instance, diags := NewTFStreamInstance(ctx, &paginatedResult.Results[i]) + input := conversion.SlicePtrToSlice(paginatedResult.Results) + results := make([]TFStreamInstanceModel, len(input)) + for i := range input { + instance, diags := NewTFStreamInstance(ctx, &input[i]) if diags.HasError() { return nil, diags } diff --git a/internal/service/streaminstance/model_stream_instance_test.go b/internal/service/streaminstance/model_stream_instance_test.go index 98aa289d40..92532c38a2 100644 --- a/internal/service/streaminstance/model_stream_instance_test.go +++ b/internal/service/streaminstance/model_stream_instance_test.go @@ -18,7 +18,7 @@ const ( instanceName = "InstanceName" ) -var hostnames = []string{"atlas-stream.virginia-usa.a.query.mongodb-dev.net"} +var hostnames = &[]string{"atlas-stream.virginia-usa.a.query.mongodb-dev.net"} type sdkToTFModelTestCase struct { SDKResp *admin.StreamsTenant @@ -90,7 +90,7 @@ func TestStreamInstancesSDKToTFModel(t *testing.T) { { name: "Complete SDK response with configured page options", SDKResp: &admin.PaginatedApiStreamsTenant{ - Results: []admin.StreamsTenant{ + Results: &[]admin.StreamsTenant{ { Id: admin.PtrString(dummyStreamInstanceID), DataProcessRegion: &admin.StreamsDataProcessRegion{ @@ -128,7 +128,7 @@ func TestStreamInstancesSDKToTFModel(t *testing.T) { { name: "Without defining page options", SDKResp: &admin.PaginatedApiStreamsTenant{ - Results: []admin.StreamsTenant{}, + Results: &[]admin.StreamsTenant{}, TotalCount: admin.PtrInt(0), }, providedConfig: &streaminstance.TFStreamInstancesModel{ @@ -246,7 +246,7 @@ func tfRegionObject(t *testing.T, cloudProvider, region string) types.Object { return dataProcessRegion } -func tfHostnamesList(t *testing.T, hostnames []string) types.List { +func tfHostnamesList(t *testing.T, hostnames *[]string) types.List { t.Helper() resultList, diags := types.ListValueFrom(context.Background(), types.StringType, hostnames) if diags.HasError() {