diff --git a/CREATING_ISSUES.md b/CREATING_ISSUES.md index d3358ef066..31ae80ffec 100644 --- a/CREATING_ISSUES.md +++ b/CREATING_ISSUES.md @@ -141,6 +141,20 @@ which is highly recommended for large-scale migrations. **Solution:** Some fields may expect different types of identifiers, when in doubt check [our documentation](https://registry.terraform.io/providers/Snowflake-Labs/snowflake/latest/docs) for the field or the [official Snowflake documentation](https://docs.snowflake.com/) what type of identifier is needed. +### Incorrect identifier type (panic: interface conversion) +**Problem** When getting stack traces similar to: +```text +panic: interface conversion: sdk.ObjectIdentifier is sdk.AccountObjectIdentifier, not sdk.DatabaseObjectIdentifier +``` + +[GitHub issue reference](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2779) + +**Solution:** Some fields may expect different types of identifiers, when in doubt check [our documentation](https://registry.terraform.io/providers/Snowflake-Labs/snowflake/latest/docs) for the field or the [official Snowflake documentation](https://docs.snowflake.com/) what type of identifier is needed. Quick reference: +- AccountObjectIdentifier - `` +- DatabaseObjectIdentifier - `.` +- SchemaObjectIdentifier - `..` +- TableColumnIdentifier - `...` + ### Incorrect account identifier (snowflake_database.from_share) **Problem:** From 0.87.0 version, we are quoting incoming external account identifier correctly, which may break configurations that specified account identifier as `.` that worked previously by accident. diff --git a/pkg/acceptance/check_destroy.go b/pkg/acceptance/check_destroy.go index 989e26683d..1b9ca1784c 100644 --- a/pkg/acceptance/check_destroy.go +++ b/pkg/acceptance/check_destroy.go @@ -335,6 +335,41 @@ func CheckDatabaseRolePrivilegesRevoked(t *testing.T) func(*terraform.State) err } } +// CheckSharePrivilegesRevoked is a custom checks that should be later incorporated into generic CheckDestroy +func CheckSharePrivilegesRevoked(t *testing.T) func(*terraform.State) error { + t.Helper() + client := Client(t) + + return func(state *terraform.State) error { + for _, rs := range state.RootModule().Resources { + if rs.Type != "snowflake_grant_privileges_to_share" { + continue + } + ctx := context.Background() + + id := sdk.NewExternalObjectIdentifierFromFullyQualifiedName(rs.Primary.Attributes["to_share"]) + grants, err := client.Grants.Show(ctx, &sdk.ShowGrantOptions{ + To: &sdk.ShowGrantsTo{ + Share: &sdk.ShowGrantsToShare{ + Name: sdk.NewAccountObjectIdentifier(id.Name()), + }, + }, + }) + if err != nil { + return err + } + var grantedPrivileges []string + for _, grant := range grants { + grantedPrivileges = append(grantedPrivileges, grant.Privilege) + } + if len(grantedPrivileges) > 0 { + return fmt.Errorf("share (%s) is still granted with privileges: %v", id.FullyQualifiedName(), grantedPrivileges) + } + } + return nil + } +} + // CheckUserPasswordPolicyAttachmentDestroy is a custom checks that should be later incorporated into generic CheckDestroy func CheckUserPasswordPolicyAttachmentDestroy(t *testing.T) func(*terraform.State) error { t.Helper() diff --git a/pkg/acceptance/helpers/context_client.go b/pkg/acceptance/helpers/context_client.go index adb0a11c8e..a753263562 100644 --- a/pkg/acceptance/helpers/context_client.go +++ b/pkg/acceptance/helpers/context_client.go @@ -32,7 +32,7 @@ func (c *ContextClient) CurrentAccount(t *testing.T) string { return currentAccount } -func (c *ContextClient) CurrentRole(t *testing.T) string { +func (c *ContextClient) CurrentRole(t *testing.T) sdk.AccountObjectIdentifier { t.Helper() ctx := context.Background() @@ -52,7 +52,7 @@ func (c *ContextClient) CurrentRegion(t *testing.T) string { return currentRegion } -func (c *ContextClient) CurrentUser(t *testing.T) string { +func (c *ContextClient) CurrentUser(t *testing.T) sdk.AccountObjectIdentifier { t.Helper() ctx := context.Background() diff --git a/pkg/acceptance/helpers/database_role_client.go b/pkg/acceptance/helpers/database_role_client.go index 91fa6888a6..7ea5b4e624 100644 --- a/pkg/acceptance/helpers/database_role_client.go +++ b/pkg/acceptance/helpers/database_role_client.go @@ -62,7 +62,7 @@ func (c *DatabaseRoleClient) CleanupDatabaseRoleFunc(t *testing.T, id sdk.Databa return func() { // to prevent error when db was removed before the role - _, err := c.context.client.Databases.ShowByID(ctx, sdk.NewAccountObjectIdentifier(id.DatabaseName())) + _, err := c.context.client.Databases.ShowByID(ctx, id.DatabaseId()) if errors.Is(err, sdk.ErrObjectNotExistOrAuthorized) { return } diff --git a/pkg/acceptance/helpers/dynamic_table_client.go b/pkg/acceptance/helpers/dynamic_table_client.go index cae5cb1e7d..520f526b89 100644 --- a/pkg/acceptance/helpers/dynamic_table_client.go +++ b/pkg/acceptance/helpers/dynamic_table_client.go @@ -33,7 +33,7 @@ func (c *DynamicTableClient) CreateDynamicTable(t *testing.T, tableId sdk.Schema func (c *DynamicTableClient) CreateDynamicTableWithOptions(t *testing.T, schemaId sdk.DatabaseObjectIdentifier, name string, warehouseId sdk.AccountObjectIdentifier, tableId sdk.SchemaObjectIdentifier) (*sdk.DynamicTable, func()) { t.Helper() - id := sdk.NewSchemaObjectIdentifier(schemaId.DatabaseName(), schemaId.Name(), name) + id := sdk.NewSchemaObjectIdentifierInSchema(schemaId, name) targetLag := sdk.TargetLag{ MaximumDuration: sdk.String("2 minutes"), } diff --git a/pkg/acceptance/helpers/ids_generator.go b/pkg/acceptance/helpers/ids_generator.go index cc2e34f9e4..001d1d3359 100644 --- a/pkg/acceptance/helpers/ids_generator.go +++ b/pkg/acceptance/helpers/ids_generator.go @@ -33,8 +33,8 @@ func (c *IdsGenerator) AccountIdentifierWithLocator() sdk.AccountIdentifier { return sdk.NewAccountIdentifierFromAccountLocator(c.context.client.GetAccountLocator()) } -func (c *IdsGenerator) newSchemaObjectIdentifier(name string) sdk.SchemaObjectIdentifier { - return sdk.NewSchemaObjectIdentifier(c.context.database, c.context.schema, name) +func (c *IdsGenerator) NewSchemaObjectIdentifier(name string) sdk.SchemaObjectIdentifier { + return sdk.NewSchemaObjectIdentifierInSchema(c.SchemaId(), name) } func (c *IdsGenerator) RandomAccountObjectIdentifier() sdk.AccountObjectIdentifier { @@ -49,8 +49,16 @@ func (c *IdsGenerator) RandomAccountObjectIdentifierContaining(part string) sdk. return sdk.NewAccountObjectIdentifier(c.AlphaContaining(part)) } +func (c *IdsGenerator) RandomDatabaseObjectIdentifier() sdk.DatabaseObjectIdentifier { + return sdk.NewDatabaseObjectIdentifier(c.DatabaseId().Name(), c.Alpha()) +} + func (c *IdsGenerator) RandomSchemaObjectIdentifier() sdk.SchemaObjectIdentifier { - return c.newSchemaObjectIdentifier(c.Alpha()) + return c.RandomSchemaObjectIdentifierInSchema(c.SchemaId()) +} + +func (c *IdsGenerator) RandomSchemaObjectIdentifierInSchema(schemaId sdk.DatabaseObjectIdentifier) sdk.SchemaObjectIdentifier { + return sdk.NewSchemaObjectIdentifierInSchema(schemaId, c.Alpha()) } func (c *IdsGenerator) Alpha() string { @@ -66,7 +74,7 @@ func (c *IdsGenerator) AlphaContaining(part string) string { } func (c *IdsGenerator) AlphaWithPrefix(prefix string) string { - return c.withTestObjectSuffix(prefix + c.Alpha()) + return prefix + c.Alpha() } func (c *IdsGenerator) withTestObjectSuffix(text string) string { diff --git a/pkg/acceptance/helpers/masking_policy_client.go b/pkg/acceptance/helpers/masking_policy_client.go index bf56197ec0..740b62f7a9 100644 --- a/pkg/acceptance/helpers/masking_policy_client.go +++ b/pkg/acceptance/helpers/masking_policy_client.go @@ -64,8 +64,7 @@ func (c *MaskingPolicyClient) CreateMaskingPolicyWithOptions(t *testing.T, schem t.Helper() ctx := context.Background() - name := random.String() - id := sdk.NewSchemaObjectIdentifier(schemaId.DatabaseName(), schemaId.Name(), name) + id := c.ids.RandomSchemaObjectIdentifierInSchema(schemaId) err := c.client().Create(ctx, id, signature, returns, expression, options) require.NoError(t, err) diff --git a/pkg/acceptance/helpers/materialized_view_client.go b/pkg/acceptance/helpers/materialized_view_client.go new file mode 100644 index 0000000000..00f7f3382f --- /dev/null +++ b/pkg/acceptance/helpers/materialized_view_client.go @@ -0,0 +1,53 @@ +package helpers + +import ( + "context" + "testing" + + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk" + "github.com/stretchr/testify/require" +) + +type MaterializedViewClient struct { + context *TestClientContext + ids *IdsGenerator +} + +func NewMaterializedViewClient(context *TestClientContext, idsGenerator *IdsGenerator) *MaterializedViewClient { + return &MaterializedViewClient{ + context: context, + ids: idsGenerator, + } +} + +func (c *MaterializedViewClient) client() sdk.MaterializedViews { + return c.context.client.MaterializedViews +} + +func (c *MaterializedViewClient) CreateMaterializedView(t *testing.T, query string, orReplace bool) (*sdk.MaterializedView, func()) { + t.Helper() + return c.CreateMaterializedViewWithName(t, c.ids.RandomSchemaObjectIdentifier(), query, orReplace) +} + +func (c *MaterializedViewClient) CreateMaterializedViewWithName(t *testing.T, id sdk.SchemaObjectIdentifier, query string, orReplace bool) (*sdk.MaterializedView, func()) { + t.Helper() + ctx := context.Background() + + err := c.client().Create(ctx, sdk.NewCreateMaterializedViewRequest(id, query).WithOrReplace(sdk.Bool(orReplace))) + require.NoError(t, err) + + view, err := c.client().ShowByID(ctx, id) + require.NoError(t, err) + + return view, c.DropMaterializedViewFunc(t, id) +} + +func (c *MaterializedViewClient) DropMaterializedViewFunc(t *testing.T, id sdk.SchemaObjectIdentifier) func() { + t.Helper() + ctx := context.Background() + + return func() { + err := c.client().Drop(ctx, sdk.NewDropMaterializedViewRequest(id).WithIfExists(sdk.Bool(true))) + require.NoError(t, err) + } +} diff --git a/pkg/acceptance/helpers/password_policy_client.go b/pkg/acceptance/helpers/password_policy_client.go index 4cc01c7be3..53e6b4e4be 100644 --- a/pkg/acceptance/helpers/password_policy_client.go +++ b/pkg/acceptance/helpers/password_policy_client.go @@ -4,7 +4,6 @@ import ( "context" "testing" - "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance/helpers/random" "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk" "github.com/stretchr/testify/require" ) @@ -44,8 +43,7 @@ func (c *PasswordPolicyClient) CreatePasswordPolicyInSchemaWithOptions(t *testin t.Helper() ctx := context.Background() - name := random.AlphanumericN(12) - id := sdk.NewSchemaObjectIdentifier(schemaId.DatabaseName(), schemaId.Name(), name) + id := c.ids.RandomSchemaObjectIdentifierInSchema(schemaId) err := c.client().Create(ctx, id, options) require.NoError(t, err) diff --git a/pkg/acceptance/helpers/pipe_client.go b/pkg/acceptance/helpers/pipe_client.go index 0036dce393..38d00ae117 100644 --- a/pkg/acceptance/helpers/pipe_client.go +++ b/pkg/acceptance/helpers/pipe_client.go @@ -4,7 +4,6 @@ import ( "context" "testing" - "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance/helpers/random" "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk" "github.com/stretchr/testify/require" ) @@ -34,7 +33,7 @@ func (c *PipeClient) CreatePipeInSchema(t *testing.T, schemaId sdk.DatabaseObjec t.Helper() ctx := context.Background() - id := sdk.NewSchemaObjectIdentifier(schemaId.DatabaseName(), schemaId.Name(), random.AlphaN(20)) + id := c.ids.RandomSchemaObjectIdentifierInSchema(schemaId) err := c.client().Create(ctx, id, copyStatement, &sdk.CreatePipeOptions{}) require.NoError(t, err) diff --git a/pkg/acceptance/helpers/role_client.go b/pkg/acceptance/helpers/role_client.go index bff4f133e8..8df0492a85 100644 --- a/pkg/acceptance/helpers/role_client.go +++ b/pkg/acceptance/helpers/role_client.go @@ -24,18 +24,18 @@ func (c *RoleClient) client() sdk.Roles { return c.context.client.Roles } -func (c *RoleClient) UseRole(t *testing.T, roleName string) func() { +func (c *RoleClient) UseRole(t *testing.T, roleId sdk.AccountObjectIdentifier) func() { t.Helper() ctx := context.Background() currentRole, err := c.context.client.ContextFunctions.CurrentRole(ctx) require.NoError(t, err) - err = c.context.client.Sessions.UseRole(ctx, sdk.NewAccountObjectIdentifier(roleName)) + err = c.context.client.Sessions.UseRole(ctx, roleId) require.NoError(t, err) return func() { - err = c.context.client.Sessions.UseRole(ctx, sdk.NewAccountObjectIdentifier(currentRole)) + err = c.context.client.Sessions.UseRole(ctx, currentRole) require.NoError(t, err) } } @@ -53,9 +53,14 @@ func (c *RoleClient) CreateRoleWithName(t *testing.T, name string) (*sdk.Role, f func (c *RoleClient) CreateRoleGrantedToCurrentUser(t *testing.T) (*sdk.Role, func()) { t.Helper() + ctx := context.Background() role, roleCleanup := c.CreateRole(t) - c.GrantRoleToCurrentUser(t, role.ID()) + + currentUser, err := c.context.client.ContextFunctions.CurrentUser(ctx) + require.NoError(t, err) + + c.GrantRoleToUser(t, role.ID(), currentUser) return role, roleCleanup } @@ -80,15 +85,12 @@ func (c *RoleClient) DropRoleFunc(t *testing.T, id sdk.AccountObjectIdentifier) } } -func (c *RoleClient) GrantRoleToCurrentUser(t *testing.T, id sdk.AccountObjectIdentifier) { +func (c *RoleClient) GrantRoleToUser(t *testing.T, id sdk.AccountObjectIdentifier, userId sdk.AccountObjectIdentifier) { t.Helper() ctx := context.Background() - currentUser, err := c.context.client.ContextFunctions.CurrentUser(ctx) - require.NoError(t, err) - - err = c.client().Grant(ctx, sdk.NewGrantRoleRequest(id, sdk.GrantRole{ - User: sdk.Pointer(sdk.NewAccountObjectIdentifier(currentUser)), + err := c.client().Grant(ctx, sdk.NewGrantRoleRequest(id, sdk.GrantRole{ + User: sdk.Pointer(userId), })) require.NoError(t, err) } @@ -114,6 +116,31 @@ func (c *RoleClient) GrantOwnershipOnAccountObject(t *testing.T, roleId sdk.Acco require.NoError(t, err) } +// TODO: move later to grants client +func (c *RoleClient) GrantOwnershipOnSchemaObject(t *testing.T, roleId sdk.AccountObjectIdentifier, objectId sdk.SchemaObjectIdentifier, objectType sdk.ObjectType, outboundPrivileges sdk.OwnershipCurrentGrantsOutboundPrivileges) { + t.Helper() + ctx := context.Background() + + err := c.context.client.Grants.GrantOwnership( + ctx, + sdk.OwnershipGrantOn{ + Object: &sdk.Object{ + ObjectType: objectType, + Name: objectId, + }, + }, + sdk.OwnershipGrantTo{ + AccountRoleName: sdk.Pointer(roleId), + }, + &sdk.GrantOwnershipOptions{ + CurrentGrants: &sdk.OwnershipCurrentGrants{ + OutboundPrivileges: outboundPrivileges, + }, + }, + ) + require.NoError(t, err) +} + // TODO: move later to grants client func (c *RoleClient) GrantPrivilegeOnDatabaseToShare(t *testing.T, databaseId sdk.AccountObjectIdentifier, shareId sdk.AccountObjectIdentifier) { t.Helper() @@ -122,3 +149,18 @@ func (c *RoleClient) GrantPrivilegeOnDatabaseToShare(t *testing.T, databaseId sd err := c.context.client.Grants.GrantPrivilegeToShare(ctx, []sdk.ObjectPrivilege{sdk.ObjectPrivilegeReferenceUsage}, &sdk.ShareGrantOn{Database: databaseId}, shareId) require.NoError(t, err) } + +// TODO: move later to grants client +func (c *RoleClient) ShowGrantsTo(t *testing.T, roleId sdk.AccountObjectIdentifier) []sdk.Grant { + t.Helper() + ctx := context.Background() + + grants, err := c.context.client.Grants.Show(ctx, &sdk.ShowGrantOptions{ + To: &sdk.ShowGrantsTo{ + Role: roleId, + }, + }) + require.NoError(t, err) + + return grants +} diff --git a/pkg/acceptance/helpers/stage_client.go b/pkg/acceptance/helpers/stage_client.go index 3bfbb31da0..5505237709 100644 --- a/pkg/acceptance/helpers/stage_client.go +++ b/pkg/acceptance/helpers/stage_client.go @@ -7,7 +7,6 @@ import ( "path/filepath" "testing" - "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance/helpers/random" "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk" "github.com/stretchr/testify/require" ) @@ -58,7 +57,7 @@ func (c *StageClient) CreateStage(t *testing.T) (*sdk.Stage, func()) { func (c *StageClient) CreateStageInSchema(t *testing.T, schemaId sdk.DatabaseObjectIdentifier) (*sdk.Stage, func()) { t.Helper() - id := sdk.NewSchemaObjectIdentifier(schemaId.DatabaseName(), schemaId.Name(), random.AlphaN(8)) + id := c.ids.RandomSchemaObjectIdentifierInSchema(schemaId) return c.CreateStageWithRequest(t, sdk.NewCreateInternalStageRequest(id)) } diff --git a/pkg/acceptance/helpers/table_client.go b/pkg/acceptance/helpers/table_client.go index 0bfb819b4d..230b1de21b 100644 --- a/pkg/acceptance/helpers/table_client.go +++ b/pkg/acceptance/helpers/table_client.go @@ -46,7 +46,7 @@ func (c *TableClient) CreateTableInSchema(t *testing.T, schemaId sdk.DatabaseObj func (c *TableClient) CreateTableWithColumns(t *testing.T, schemaId sdk.DatabaseObjectIdentifier, name string, columns []sdk.TableColumnRequest) (*sdk.Table, func()) { t.Helper() - id := sdk.NewSchemaObjectIdentifier(schemaId.DatabaseName(), schemaId.Name(), name) + id := sdk.NewSchemaObjectIdentifierInSchema(schemaId, name) ctx := context.Background() dbCreateRequest := sdk.NewCreateTableRequest(id, columns) @@ -75,6 +75,14 @@ func (c *TableClient) DropTableFunc(t *testing.T, id sdk.SchemaObjectIdentifier) } } +func (c *TableClient) SetDataRetentionTime(t *testing.T, id sdk.SchemaObjectIdentifier, days int) { + t.Helper() + ctx := context.Background() + + err := c.client().Alter(ctx, sdk.NewAlterTableRequest(id).WithSet(sdk.NewTableSetRequest().WithDataRetentionTimeInDays(sdk.Int(days)))) + require.NoError(t, err) +} + // GetTableColumnsFor is based on https://docs.snowflake.com/en/sql-reference/info-schema/columns. // TODO: extract getting table columns as resource (like getting tag in system functions) func (c *TableClient) GetTableColumnsFor(t *testing.T, tableId sdk.SchemaObjectIdentifier) []InformationSchemaColumns { diff --git a/pkg/acceptance/helpers/tag_client.go b/pkg/acceptance/helpers/tag_client.go index 7288d13287..8ee7d7aa3d 100644 --- a/pkg/acceptance/helpers/tag_client.go +++ b/pkg/acceptance/helpers/tag_client.go @@ -4,7 +4,6 @@ import ( "context" "testing" - "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance/helpers/random" "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk" "github.com/stretchr/testify/require" ) @@ -34,7 +33,7 @@ func (c *TagClient) CreateTagInSchema(t *testing.T, schemaId sdk.DatabaseObjectI t.Helper() ctx := context.Background() - id := sdk.NewSchemaObjectIdentifier(schemaId.DatabaseName(), schemaId.Name(), random.AlphanumericN(12)) + id := c.ids.RandomSchemaObjectIdentifierInSchema(schemaId) err := c.client().Create(ctx, sdk.NewCreateTagRequest(id)) require.NoError(t, err) diff --git a/pkg/acceptance/helpers/test_client.go b/pkg/acceptance/helpers/test_client.go index 198aa38a79..36ce573cd1 100644 --- a/pkg/acceptance/helpers/test_client.go +++ b/pkg/acceptance/helpers/test_client.go @@ -21,6 +21,7 @@ type TestClient struct { FailoverGroup *FailoverGroupClient FileFormat *FileFormatClient MaskingPolicy *MaskingPolicyClient + MaterializedView *MaterializedViewClient NetworkPolicy *NetworkPolicyClient Parameter *ParameterClient PasswordPolicy *PasswordPolicyClient @@ -66,6 +67,7 @@ func NewTestClient(c *sdk.Client, database string, schema string, warehouse stri FailoverGroup: NewFailoverGroupClient(context, idsGenerator), FileFormat: NewFileFormatClient(context, idsGenerator), MaskingPolicy: NewMaskingPolicyClient(context, idsGenerator), + MaterializedView: NewMaterializedViewClient(context, idsGenerator), NetworkPolicy: NewNetworkPolicyClient(context, idsGenerator), Parameter: NewParameterClient(context), PasswordPolicy: NewPasswordPolicyClient(context, idsGenerator), diff --git a/pkg/acceptance/helpers/view_client.go b/pkg/acceptance/helpers/view_client.go index ee6f44bd1c..9c39c08888 100644 --- a/pkg/acceptance/helpers/view_client.go +++ b/pkg/acceptance/helpers/view_client.go @@ -39,6 +39,19 @@ func (c *ViewClient) CreateView(t *testing.T, query string) (*sdk.View, func()) return view, c.DropViewFunc(t, id) } +func (c *ViewClient) RecreateView(t *testing.T, id sdk.SchemaObjectIdentifier, query string) *sdk.View { + t.Helper() + ctx := context.Background() + + err := c.client().Create(ctx, sdk.NewCreateViewRequest(id, query).WithOrReplace(sdk.Bool(true))) + require.NoError(t, err) + + view, err := c.client().ShowByID(ctx, id) + require.NoError(t, err) + + return view +} + func (c *ViewClient) DropViewFunc(t *testing.T, id sdk.SchemaObjectIdentifier) func() { t.Helper() ctx := context.Background() diff --git a/pkg/acceptance/ids/snowflake_placeholders.go b/pkg/acceptance/ids/snowflake_placeholders.go new file mode 100644 index 0000000000..7c11b07a64 --- /dev/null +++ b/pkg/acceptance/ids/snowflake_placeholders.go @@ -0,0 +1,5 @@ +package ids + +import "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk" + +var DatabasePlaceholder = sdk.NewAccountObjectIdentifier("") diff --git a/pkg/acceptance/ids/storage_integrations.go b/pkg/acceptance/ids/storage_integrations.go new file mode 100644 index 0000000000..10c03731f7 --- /dev/null +++ b/pkg/acceptance/ids/storage_integrations.go @@ -0,0 +1,9 @@ +package ids + +import "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk" + +var ( + PrecreatedS3StorageIntegration = sdk.NewAccountObjectIdentifier("S3_STORAGE_INTEGRATION") + PrecreatedGcpStorageIntegration = sdk.NewAccountObjectIdentifier("GCP_STORAGE_INTEGRATION") + PrecreatedAzureStorageIntegration = sdk.NewAccountObjectIdentifier("AZURE_STORAGE_INTEGRATION") +) diff --git a/pkg/acceptance/testvars/application_roles.go b/pkg/acceptance/testvars/application_roles.go new file mode 100644 index 0000000000..877544dba5 --- /dev/null +++ b/pkg/acceptance/testvars/application_roles.go @@ -0,0 +1,6 @@ +package testvars + +var ( + ApplicationRole1 = "app_role_1" + ApplicationRole2 = "app_role_2" +) diff --git a/pkg/datasources/accounts.go b/pkg/datasources/accounts.go index 1eebbcb432..7f3079074e 100644 --- a/pkg/datasources/accounts.go +++ b/pkg/datasources/accounts.go @@ -5,7 +5,7 @@ import ( "log" "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/internal/provider" - + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/internal/snowflakeroles" "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) @@ -120,7 +120,7 @@ func ReadAccounts(d *schema.ResourceData, meta interface{}) error { client := meta.(*provider.Context).Client ctx := context.Background() - ok, err := client.ContextFunctions.IsRoleInSession(ctx, sdk.NewAccountObjectIdentifier("ORGADMIN")) + ok, err := client.ContextFunctions.IsRoleInSession(ctx, snowflakeroles.Orgadmin) if err != nil { return err } diff --git a/pkg/datasources/current_role.go b/pkg/datasources/current_role.go index 4a47bd183b..254bb70dbc 100644 --- a/pkg/datasources/current_role.go +++ b/pkg/datasources/current_role.go @@ -4,8 +4,8 @@ import ( "context" "log" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/helpers" "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/internal/provider" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) @@ -35,8 +35,8 @@ func ReadCurrentRole(d *schema.ResourceData, meta interface{}) error { return nil } - d.SetId(role) - err = d.Set("name", role) + d.SetId(helpers.EncodeSnowflakeID(role)) + err = d.Set("name", role.Name()) if err != nil { return err } diff --git a/pkg/datasources/grants_acceptance_test.go b/pkg/datasources/grants_acceptance_test.go index 2bc0f71167..90478754ee 100644 --- a/pkg/datasources/grants_acceptance_test.go +++ b/pkg/datasources/grants_acceptance_test.go @@ -188,9 +188,9 @@ func TestAcc_Grants_To_DatabaseRole(t *testing.T) { } func TestAcc_Grants_To_User(t *testing.T) { - user := acc.TestClient().Context.CurrentUser(t) + userId := acc.TestClient().Context.CurrentUser(t) configVariables := config.Variables{ - "user": config.StringVariable(user), + "user": config.StringVariable(userId.Name()), } resource.Test(t, resource.TestCase{ diff --git a/pkg/internal/snowflakeroles/snowflake_predefined_roles.go b/pkg/internal/snowflakeroles/snowflake_predefined_roles.go new file mode 100644 index 0000000000..065b624694 --- /dev/null +++ b/pkg/internal/snowflakeroles/snowflake_predefined_roles.go @@ -0,0 +1,8 @@ +package snowflakeroles + +import "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk" + +var ( + Orgadmin = sdk.NewAccountObjectIdentifier("ORGADMIN") + Accountadmin = sdk.NewAccountObjectIdentifier("ACCOUNTADMIN") +) diff --git a/pkg/resources/database.go b/pkg/resources/database.go index c19c0ca999..2b91dcc1ce 100644 --- a/pkg/resources/database.go +++ b/pkg/resources/database.go @@ -7,12 +7,11 @@ import ( "slices" "strconv" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/helpers" "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/internal/provider" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" - "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) var databaseSchema = map[string]*schema.Schema{ @@ -193,13 +192,12 @@ func CreateDatabase(d *schema.ResourceData, meta interface{}) error { func ReadDatabase(d *schema.ResourceData, meta interface{}) error { client := meta.(*provider.Context).Client ctx := context.Background() - name := d.Id() - id := sdk.NewAccountObjectIdentifier(name) + id := helpers.DecodeSnowflakeID(d.Id()).(sdk.AccountObjectIdentifier) database, err := client.Databases.ShowByID(ctx, id) if err != nil { d.SetId("") - log.Printf("Database %s not found, err = %s", name, err) + log.Printf("Database %s not found, err = %s", id.Name(), err) return nil } @@ -233,22 +231,22 @@ func ReadDatabase(d *schema.ResourceData, meta interface{}) error { } func UpdateDatabase(d *schema.ResourceData, meta interface{}) error { - name := d.Id() - id := sdk.NewAccountObjectIdentifier(name) + id := helpers.DecodeSnowflakeID(d.Id()).(sdk.AccountObjectIdentifier) client := meta.(*provider.Context).Client ctx := context.Background() if d.HasChange("name") { newName := d.Get("name").(string) + newId := sdk.NewAccountObjectIdentifier(newName) opts := &sdk.AlterDatabaseOptions{ - NewName: sdk.NewAccountObjectIdentifier(newName), + NewName: newId, } err := client.Databases.Alter(ctx, id, opts) if err != nil { return fmt.Errorf("error updating database name on %v err = %w", d.Id(), err) } - d.SetId(newName) - id = sdk.NewAccountObjectIdentifier(newName) + d.SetId(helpers.EncodeSnowflakeID(newId)) + id = newId } if d.HasChange("comment") { @@ -360,8 +358,7 @@ func UpdateDatabase(d *schema.ResourceData, meta interface{}) error { func DeleteDatabase(d *schema.ResourceData, meta interface{}) error { client := meta.(*provider.Context).Client ctx := context.Background() - name := d.Id() - id := sdk.NewAccountObjectIdentifier(name) + id := helpers.DecodeSnowflakeID(d.Id()).(sdk.AccountObjectIdentifier) err := client.Databases.Drop(ctx, id, &sdk.DropDatabaseOptions{ IfExists: sdk.Bool(true), }) diff --git a/pkg/resources/database_acceptance_test.go b/pkg/resources/database_acceptance_test.go index 7be17bad26..e002d31037 100644 --- a/pkg/resources/database_acceptance_test.go +++ b/pkg/resources/database_acceptance_test.go @@ -128,7 +128,7 @@ func TestAcc_DatabaseRemovedOutsideOfTerraform(t *testing.T) { Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("snowflake_database.db", "name", name), resource.TestCheckResourceAttr("snowflake_database.db", "comment", "test comment"), - testAccCheckDatabaseExistence(t, name, true), + testAccCheckDatabaseExistence(t, id, true), ), }, { @@ -143,7 +143,7 @@ func TestAcc_DatabaseRemovedOutsideOfTerraform(t *testing.T) { Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("snowflake_database.db", "name", name), resource.TestCheckResourceAttr("snowflake_database.db", "comment", "test comment"), - testAccCheckDatabaseExistence(t, name, true), + testAccCheckDatabaseExistence(t, id, true), ), }, }, @@ -372,10 +372,10 @@ resource "snowflake_database" "db" { } // TODO [SNOW-936093]: this is used mostly as check for unsafe execute, not as normal check destroy in other resources. Handle with the helpers cleanup. -func testAccCheckDatabaseExistence(t *testing.T, id string, shouldExist bool) func(state *terraform.State) error { +func testAccCheckDatabaseExistence(t *testing.T, id sdk.AccountObjectIdentifier, shouldExist bool) func(state *terraform.State) error { t.Helper() return func(state *terraform.State) error { - _, err := acc.TestClient().Database.Show(t, sdk.NewAccountObjectIdentifier(id)) + _, err := acc.TestClient().Database.Show(t, id) if shouldExist { if err != nil { return fmt.Errorf("error while retrieving database %s, err = %w", id, err) diff --git a/pkg/resources/dynamic_table_acceptance_test.go b/pkg/resources/dynamic_table_acceptance_test.go index 0bcdaa94d1..04d92f45a7 100644 --- a/pkg/resources/dynamic_table_acceptance_test.go +++ b/pkg/resources/dynamic_table_acceptance_test.go @@ -158,7 +158,7 @@ func TestAcc_DynamicTable_basic(t *testing.T) { func TestAcc_DynamicTable_issue2173(t *testing.T) { dynamicTableName := acc.TestClient().Ids.Alpha() tableName := dynamicTableName + "_table" - tableId := sdk.NewSchemaObjectIdentifier(acc.TestDatabaseName, acc.TestSchemaName, tableName) + tableId := acc.TestClient().Ids.NewSchemaObjectIdentifier(tableName) query := fmt.Sprintf(`select "ID" from %s`, tableId.FullyQualifiedName()) otherSchema := acc.TestClient().Ids.Alpha() otherSchemaId := sdk.NewDatabaseObjectIdentifier(acc.TestDatabaseName, otherSchema) diff --git a/pkg/resources/external_table_acceptance_test.go b/pkg/resources/external_table_acceptance_test.go index 9eff75faef..fb59f5729a 100644 --- a/pkg/resources/external_table_acceptance_test.go +++ b/pkg/resources/external_table_acceptance_test.go @@ -28,7 +28,8 @@ func TestAcc_ExternalTable_basic(t *testing.T) { t.Skipf("Skip because error %s; will be fixed in SNOW-1423486", "Error: 000606 (57P03): No active warehouse selected in the current session. Select an active warehouse with the 'use warehouse' command.") awsBucketURL, awsKeyId, awsSecretKey := getExternalTableTestEnvsOrSkipTest(t) - name := acc.TestClient().Ids.Alpha() + id := acc.TestClient().Ids.RandomSchemaObjectIdentifier() + name := id.Name() resourceName := "snowflake_external_table.test_table" innerDirectory := "/external_tables_test_data/" @@ -74,7 +75,7 @@ func TestAcc_ExternalTable_basic(t *testing.T) { }, { PreConfig: func() { - publishExternalTablesTestData(t, sdk.NewSchemaObjectIdentifier(acc.TestDatabaseName, acc.TestSchemaName, name), data) + publishExternalTablesTestData(t, id, data) }, ConfigDirectory: config.TestStepDirectory(), ConfigVariables: configVariables, @@ -248,7 +249,8 @@ func TestAcc_ExternalTable_CanCreateWithPartitions(t *testing.T) { func TestAcc_ExternalTable_DeltaLake(t *testing.T) { awsBucketURL, awsKeyId, awsSecretKey := getExternalTableTestEnvsOrSkipTest(t) - name := acc.TestClient().Ids.Alpha() + id := acc.TestClient().Ids.RandomSchemaObjectIdentifier() + name := id.Name() resourceName := "snowflake_external_table.test_table" innerDirectory := "/external_tables_test_data/" @@ -297,7 +299,6 @@ func TestAcc_ExternalTable_DeltaLake(t *testing.T) { func(state *terraform.State) error { client := acc.TestAccProvider.Meta().(*provider.Context).Client ctx := context.Background() - id := sdk.NewSchemaObjectIdentifier(acc.TestDatabaseName, acc.TestSchemaName, name) result, err := client.ExternalTables.ShowByID(ctx, id) if err != nil { return err @@ -325,7 +326,7 @@ func externalTableContainsData(name string, contains func(rows []map[string]*any return func(state *terraform.State) error { client := acc.TestAccProvider.Meta().(*provider.Context).Client ctx := context.Background() - id := sdk.NewSchemaObjectIdentifier(acc.TestDatabaseName, acc.TestSchemaName, name) + id := acc.TestClient().Ids.NewSchemaObjectIdentifier(name) rows, err := client.QueryUnsafe(ctx, fmt.Sprintf("select * from %s", id.FullyQualifiedName())) if err != nil { return err @@ -360,7 +361,7 @@ func expectTableToHaveColumnDataTypes(tableName string, expectedDataTypes []sdk. return func(s *terraform.State) error { client := acc.TestAccProvider.Meta().(*provider.Context).Client ctx := context.Background() - id := sdk.NewSchemaObjectIdentifier(acc.TestDatabaseName, acc.TestSchemaName, tableName) + id := acc.TestClient().Ids.NewSchemaObjectIdentifier(tableName) columnsDesc, err := client.ExternalTables.DescribeColumns(ctx, sdk.NewDescribeExternalTableColumnsRequest(id)) if err != nil { return err @@ -390,7 +391,7 @@ func expectTableDDLContains(tableName string, substr string) func(s *terraform.S return func(s *terraform.State) error { client := acc.TestAccProvider.Meta().(*provider.Context).Client ctx := context.Background() - id := sdk.NewSchemaObjectIdentifier(acc.TestDatabaseName, acc.TestSchemaName, tableName) + id := acc.TestClient().Ids.NewSchemaObjectIdentifier(tableName) rows, err := client.QueryUnsafe(ctx, fmt.Sprintf("select get_ddl('table', '%s')", id.FullyQualifiedName())) if err != nil { diff --git a/pkg/resources/failover_group.go b/pkg/resources/failover_group.go index a3bc18c2cb..6d51513345 100644 --- a/pkg/resources/failover_group.go +++ b/pkg/resources/failover_group.go @@ -8,8 +8,8 @@ import ( "strconv" "strings" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/helpers" "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/internal/provider" - "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) @@ -266,8 +266,7 @@ func CreateFailoverGroup(d *schema.ResourceData, meta interface{}) error { func ReadFailoverGroup(d *schema.ResourceData, meta interface{}) error { client := meta.(*provider.Context).Client ctx := context.Background() - name := d.Id() - id := sdk.NewAccountObjectIdentifier(name) + id := helpers.DecodeSnowflakeID(d.Id()).(sdk.AccountObjectIdentifier) failoverGroup, err := client.FailoverGroups.ShowByID(ctx, id) if err != nil { return err @@ -393,8 +392,7 @@ func ReadFailoverGroup(d *schema.ResourceData, meta interface{}) error { func UpdateFailoverGroup(d *schema.ResourceData, meta interface{}) error { client := meta.(*provider.Context).Client ctx := context.Background() - name := d.Id() - id := sdk.NewAccountObjectIdentifier(name) + id := helpers.DecodeSnowflakeID(d.Id()).(sdk.AccountObjectIdentifier) // alter failover group set ... opts := &sdk.AlterSourceFailoverGroupOptions{ @@ -503,7 +501,7 @@ func UpdateFailoverGroup(d *schema.ResourceData, meta interface{}) error { }, } if err := client.FailoverGroups.AlterSource(ctx, id, opts); err != nil { - return fmt.Errorf("error removing allowed databases for failover group %v err = %w", name, err) + return fmt.Errorf("error removing allowed databases for failover group %v err = %w", id.Name(), err) } } @@ -521,7 +519,7 @@ func UpdateFailoverGroup(d *schema.ResourceData, meta interface{}) error { }, } if err := client.FailoverGroups.AlterSource(ctx, id, opts); err != nil { - return fmt.Errorf("error removing allowed databases for failover group %v err = %w", name, err) + return fmt.Errorf("error removing allowed databases for failover group %v err = %w", id.Name(), err) } } } @@ -552,7 +550,7 @@ func UpdateFailoverGroup(d *schema.ResourceData, meta interface{}) error { }, } if err := client.FailoverGroups.AlterSource(ctx, id, opts); err != nil { - return fmt.Errorf("error removing allowed shares for failover group %v err = %w", name, err) + return fmt.Errorf("error removing allowed shares for failover group %v err = %w", id.Name(), err) } } @@ -570,7 +568,7 @@ func UpdateFailoverGroup(d *schema.ResourceData, meta interface{}) error { }, } if err := client.FailoverGroups.AlterSource(ctx, id, opts); err != nil { - return fmt.Errorf("error removing allowed shares for failover group %v err = %w", name, err) + return fmt.Errorf("error removing allowed shares for failover group %v err = %w", id.Name(), err) } } } @@ -609,7 +607,7 @@ func UpdateFailoverGroup(d *schema.ResourceData, meta interface{}) error { }, } if err := client.FailoverGroups.AlterSource(ctx, id, opts); err != nil { - return fmt.Errorf("error removing allowed accounts for failover group %v err = %w", name, err) + return fmt.Errorf("error removing allowed accounts for failover group %v err = %w", id.Name(), err) } } @@ -627,7 +625,7 @@ func UpdateFailoverGroup(d *schema.ResourceData, meta interface{}) error { }, } if err := client.FailoverGroups.AlterSource(ctx, id, opts); err != nil { - return fmt.Errorf("error removing allowed accounts for failover group %v err = %w", name, err) + return fmt.Errorf("error removing allowed accounts for failover group %v err = %w", id.Name(), err) } } } @@ -638,12 +636,11 @@ func UpdateFailoverGroup(d *schema.ResourceData, meta interface{}) error { // DeleteFailoverGroup implements schema.DeleteFunc. func DeleteFailoverGroup(d *schema.ResourceData, meta interface{}) error { client := meta.(*provider.Context).Client - name := d.Id() - id := sdk.NewAccountObjectIdentifier(name) + id := helpers.DecodeSnowflakeID(d.Id()).(sdk.AccountObjectIdentifier) ctx := context.Background() err := client.FailoverGroups.Drop(ctx, id, &sdk.DropFailoverGroupOptions{IfExists: sdk.Bool(true)}) if err != nil { - return fmt.Errorf("error deleting failover group %v err = %w", name, err) + return fmt.Errorf("error deleting failover group %v err = %w", id.Name(), err) } d.SetId("") diff --git a/pkg/resources/file_format.go b/pkg/resources/file_format.go index 6e632a5cfd..bb6a80bf18 100644 --- a/pkg/resources/file_format.go +++ b/pkg/resources/file_format.go @@ -767,7 +767,7 @@ func UpdateFileFormat(d *schema.ResourceData, meta interface{}) error { id := sdk.NewSchemaObjectIdentifier(fileFormatID.DatabaseName, fileFormatID.SchemaName, fileFormatID.FileFormatName) if d.HasChange("name") { - newId := sdk.NewSchemaObjectIdentifier(id.DatabaseName(), id.SchemaName(), d.Get("name").(string)) + newId := sdk.NewSchemaObjectIdentifierInSchema(id.SchemaId(), d.Get("name").(string)) err := client.FileFormats.Alter(ctx, id, &sdk.AlterFileFormatOptions{ Rename: &sdk.AlterFileFormatRenameOptions{ diff --git a/pkg/resources/grant_application_role_acceptance_test.go b/pkg/resources/grant_application_role_acceptance_test.go index bd0ba31674..dc2eddd605 100644 --- a/pkg/resources/grant_application_role_acceptance_test.go +++ b/pkg/resources/grant_application_role_acceptance_test.go @@ -5,8 +5,9 @@ import ( "testing" acc "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance" - "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance/testvars" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk" "github.com/hashicorp/terraform-plugin-testing/config" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/tfversion" @@ -36,15 +37,16 @@ func TestAcc_GrantApplicationRole_accountRole(t *testing.T) { parentRole, cleanupParentRole := acc.TestClient().Role.CreateRole(t) t.Cleanup(cleanupParentRole) resourceName := "snowflake_grant_application_role.g" - applicationRoleName := "app_role_1" + applicationRoleName := testvars.ApplicationRole1 acc.TestAccPreCheck(t) app := createApp(t) - applicationRoleNameFullyQualified := fmt.Sprintf("\"%s\".\"%s\"", app.Name, applicationRoleName) + applicationRoleNameFullyQualified := sdk.NewDatabaseObjectIdentifier(app.Name, applicationRoleName).FullyQualifiedName() m := func() map[string]config.Variable { return map[string]config.Variable{ "parent_account_role_name": config.StringVariable(parentRole.Name), "application_name": config.StringVariable(app.Name), + "application_role_name": config.StringVariable(applicationRoleName), } } resource.Test(t, resource.TestCase{ @@ -78,7 +80,7 @@ func TestAcc_GrantApplicationRole_accountRole(t *testing.T) { func TestAcc_GrantApplicationRole_application(t *testing.T) { resourceName := "snowflake_grant_application_role.g" - applicationRoleName := "app_role_1" + applicationRoleName := testvars.ApplicationRole1 acc.TestAccPreCheck(t) app := createApp(t) @@ -86,11 +88,12 @@ func TestAcc_GrantApplicationRole_application(t *testing.T) { m := func() map[string]config.Variable { return map[string]config.Variable{ - "application_name": config.StringVariable(app.Name), - "application_name2": config.StringVariable(app2.Name), + "application_name": config.StringVariable(app.Name), + "application_name2": config.StringVariable(app2.Name), + "application_role_name": config.StringVariable(applicationRoleName), } } - applicationRoleNameFullyQualified := fmt.Sprintf("\"%s\".\"%s\"", app.Name, applicationRoleName) + applicationRoleNameFullyQualified := sdk.NewDatabaseObjectIdentifier(app.Name, applicationRoleName).FullyQualifiedName() resource.Test(t, resource.TestCase{ TerraformVersionChecks: []tfversion.TerraformVersionCheck{ tfversion.RequireAbove(tfversion.Version1_5_0), diff --git a/pkg/resources/grant_ownership.go b/pkg/resources/grant_ownership.go index 2a4e3d9cce..ff7d9ecb29 100644 --- a/pkg/resources/grant_ownership.go +++ b/pkg/resources/grant_ownership.go @@ -302,7 +302,7 @@ func DeleteGrantOwnership(ctx context.Context, d *schema.ResourceData, meta any) ctx, *grantOn, sdk.OwnershipGrantTo{ - AccountRoleName: sdk.Pointer(sdk.NewAccountObjectIdentifier(accountRoleName)), + AccountRoleName: sdk.Pointer(accountRoleName), }, getOwnershipGrantOpts(id), ) diff --git a/pkg/resources/grant_ownership_acceptance_test.go b/pkg/resources/grant_ownership_acceptance_test.go index 9c04b2190b..7e6a256b8e 100644 --- a/pkg/resources/grant_ownership_acceptance_test.go +++ b/pkg/resources/grant_ownership_acceptance_test.go @@ -617,12 +617,8 @@ func TestAcc_GrantOwnership_TargetObjectRemovedOutsideTerraform(t *testing.T) { }, { PreConfig: func() { - grantOwnershipToTheCurrentRole(t, sdk.OwnershipGrantOn{ - Object: &sdk.Object{ - ObjectType: sdk.ObjectTypeDatabase, - Name: databaseId, - }, - }) + currentRole := acc.TestClient().Context.CurrentRole(t) + acc.TestClient().Role.GrantOwnershipOnAccountObject(t, currentRole, databaseId, sdk.ObjectTypeDatabase) cleanupDatabase() }, ConfigDirectory: acc.ConfigurationDirectory("TestAcc_GrantOwnership/OnObject_Database_ToAccountRole_NoDatabaseResource"), @@ -747,7 +743,7 @@ func TestAcc_GrantOwnership_RoleBasedAccessControlUseCase(t *testing.T) { accountRoleName := acc.TestClient().Ids.Alpha() databaseName := acc.TestClient().Ids.Alpha() schemaName := acc.TestClient().Ids.Alpha() - userName := acc.TestClient().Context.CurrentUser(t) + userId := acc.TestClient().Context.CurrentUser(t) resource.Test(t, resource.TestCase{ ProtoV6ProviderFactories: acc.TestAccProtoV6ProviderFactories, @@ -760,10 +756,10 @@ func TestAcc_GrantOwnership_RoleBasedAccessControlUseCase(t *testing.T) { // that are needed to grant the role to the current user before it can be used. // Additionally, only the Config field can specify a configuration with custom provider blocks. { - Config: roleBasedAccessControlUseCaseConfig(accountRoleName, databaseName, userName, schemaName, false), + Config: roleBasedAccessControlUseCaseConfig(accountRoleName, databaseName, userId.Name(), schemaName, false), }, { - Config: roleBasedAccessControlUseCaseConfig(accountRoleName, databaseName, userName, schemaName, true), + Config: roleBasedAccessControlUseCaseConfig(accountRoleName, databaseName, userId.Name(), schemaName, true), ConfigPlanChecks: resource.ConfigPlanChecks{ PostApplyPostRefresh: []plancheck.PlanCheck{ plancheck.ExpectEmptyPlan(), @@ -1207,21 +1203,3 @@ func checkResourceOwnershipIsGranted(opts *sdk.ShowGrantOptions, grantOn sdk.Obj return nil } } - -func grantOwnershipToTheCurrentRole(t *testing.T, on sdk.OwnershipGrantOn) { - t.Helper() - client := acc.Client(t) - - ctx := context.Background() - currentRole := acc.TestClient().Context.CurrentRole(t) - - err := client.Grants.GrantOwnership( - ctx, - on, - sdk.OwnershipGrantTo{ - AccountRoleName: sdk.Pointer(sdk.NewAccountObjectIdentifier(currentRole)), - }, - new(sdk.GrantOwnershipOptions), - ) - assert.NoError(t, err) -} diff --git a/pkg/resources/grant_privileges_to_account_role_acceptance_test.go b/pkg/resources/grant_privileges_to_account_role_acceptance_test.go index 74e178eeb8..97612ad71c 100644 --- a/pkg/resources/grant_privileges_to_account_role_acceptance_test.go +++ b/pkg/resources/grant_privileges_to_account_role_acceptance_test.go @@ -400,11 +400,10 @@ func TestAcc_GrantPrivilegesToAccountRole_OnSchemaObject_OnObject(t *testing.T) roleId := acc.TestClient().Ids.RandomAccountObjectIdentifier() roleName := roleId.Name() roleFullyQualifiedName := roleId.FullyQualifiedName() - tblName := "test_database_role_table_name" - tableName := sdk.NewSchemaObjectIdentifier(acc.TestDatabaseName, acc.TestSchemaName, tblName).FullyQualifiedName() + tableId := acc.TestClient().Ids.RandomSchemaObjectIdentifier() configVariables := config.Variables{ "name": config.StringVariable(roleFullyQualifiedName), - "table_name": config.StringVariable(tblName), + "table_name": config.StringVariable(tableId.Name()), "privileges": config.ListVariable( config.StringVariable(string(sdk.SchemaObjectPrivilegeInsert)), config.StringVariable(string(sdk.SchemaObjectPrivilegeUpdate)), @@ -437,9 +436,9 @@ func TestAcc_GrantPrivilegesToAccountRole_OnSchemaObject_OnObject(t *testing.T) resource.TestCheckResourceAttr(resourceName, "privileges.1", string(sdk.SchemaObjectPrivilegeUpdate)), resource.TestCheckResourceAttr(resourceName, "on_schema_object.#", "1"), resource.TestCheckResourceAttr(resourceName, "on_schema_object.0.object_type", string(sdk.ObjectTypeTable)), - resource.TestCheckResourceAttr(resourceName, "on_schema_object.0.object_name", tableName), + resource.TestCheckResourceAttr(resourceName, "on_schema_object.0.object_name", tableId.FullyQualifiedName()), resource.TestCheckResourceAttr(resourceName, "with_grant_option", "false"), - resource.TestCheckResourceAttr(resourceName, "id", fmt.Sprintf("%s|false|false|INSERT,UPDATE|OnSchemaObject|OnObject|TABLE|%s", roleFullyQualifiedName, tableName)), + resource.TestCheckResourceAttr(resourceName, "id", fmt.Sprintf("%s|false|false|INSERT,UPDATE|OnSchemaObject|OnObject|TABLE|%s", roleFullyQualifiedName, tableId.FullyQualifiedName())), ), }, { @@ -1259,7 +1258,8 @@ func TestAcc_GrantPrivilegesToAccountRole_ChangeWithGrantOptionsOutsideOfTerrafo roleId := acc.TestClient().Ids.RandomAccountObjectIdentifier() roleName := roleId.Name() roleFullyQualifiedName := roleId.FullyQualifiedName() - tableName := acc.TestClient().Ids.Alpha() + tableId := acc.TestClient().Ids.RandomSchemaObjectIdentifier() + tableName := tableId.Name() configVariables := config.Variables{ "name": config.StringVariable(roleFullyQualifiedName), @@ -1298,7 +1298,7 @@ func TestAcc_GrantPrivilegesToAccountRole_ChangeWithGrantOptionsOutsideOfTerrafo revokeAndGrantPrivilegesOnTableToAccountRole( t, roleId, - sdk.NewSchemaObjectIdentifier(acc.TestDatabaseName, acc.TestSchemaName, tableName), + tableId, []sdk.SchemaObjectPrivilege{sdk.SchemaObjectPrivilegeTruncate}, false, ) @@ -1320,7 +1320,8 @@ func TestAcc_GrantPrivilegesToAccountRole_ChangeWithGrantOptionsOutsideOfTerrafo roleId := acc.TestClient().Ids.RandomAccountObjectIdentifier() roleName := roleId.Name() roleFullyQualifiedName := roleId.FullyQualifiedName() - tableName := acc.TestClient().Ids.Alpha() + tableId := acc.TestClient().Ids.RandomSchemaObjectIdentifier() + tableName := tableId.Name() configVariables := config.Variables{ "name": config.StringVariable(roleFullyQualifiedName), @@ -1359,7 +1360,7 @@ func TestAcc_GrantPrivilegesToAccountRole_ChangeWithGrantOptionsOutsideOfTerrafo revokeAndGrantPrivilegesOnTableToAccountRole( t, roleId, - sdk.NewSchemaObjectIdentifier(acc.TestDatabaseName, acc.TestSchemaName, tableName), + tableId, []sdk.SchemaObjectPrivilege{sdk.SchemaObjectPrivilegeTruncate}, true, ) diff --git a/pkg/resources/grant_privileges_to_database_role_acceptance_test.go b/pkg/resources/grant_privileges_to_database_role_acceptance_test.go index 87dca6f751..8b174fd5c5 100644 --- a/pkg/resources/grant_privileges_to_database_role_acceptance_test.go +++ b/pkg/resources/grant_privileges_to_database_role_acceptance_test.go @@ -303,11 +303,16 @@ func TestAcc_GrantPrivilegesToDatabaseRole_OnFutureSchemasInDatabase(t *testing. } func TestAcc_GrantPrivilegesToDatabaseRole_OnSchemaObject_OnObject(t *testing.T) { - name := acc.TestClient().Ids.Alpha() - tblName := "test_database_role_table_name" + databaseRoleId := acc.TestClient().Ids.RandomDatabaseObjectIdentifier() + databaseRoleName := databaseRoleId.Name() + + tableId := acc.TestClient().Ids.RandomSchemaObjectIdentifier() + tableName := tableId.Name() + + resourceName := "snowflake_grant_privileges_to_database_role.test" configVariables := config.Variables{ - "name": config.StringVariable(name), - "table_name": config.StringVariable(tblName), + "name": config.StringVariable(databaseRoleName), + "table_name": config.StringVariable(tableName), "privileges": config.ListVariable( config.StringVariable(string(sdk.SchemaObjectPrivilegeInsert)), config.StringVariable(string(sdk.SchemaObjectPrivilegeUpdate)), @@ -316,10 +321,6 @@ func TestAcc_GrantPrivilegesToDatabaseRole_OnSchemaObject_OnObject(t *testing.T) "schema": config.StringVariable(acc.TestSchemaName), "with_grant_option": config.BoolVariable(false), } - resourceName := "snowflake_grant_privileges_to_database_role.test" - - databaseRoleName := sdk.NewDatabaseObjectIdentifier(acc.TestDatabaseName, name).FullyQualifiedName() - tableName := sdk.NewSchemaObjectIdentifier(acc.TestDatabaseName, acc.TestSchemaName, tblName).FullyQualifiedName() resource.Test(t, resource.TestCase{ ProtoV6ProviderFactories: acc.TestAccProtoV6ProviderFactories, @@ -331,21 +332,21 @@ func TestAcc_GrantPrivilegesToDatabaseRole_OnSchemaObject_OnObject(t *testing.T) Steps: []resource.TestStep{ { PreConfig: func() { - _, databaseRoleCleanup := acc.TestClient().DatabaseRole.CreateDatabaseRoleWithName(t, name) + _, databaseRoleCleanup := acc.TestClient().DatabaseRole.CreateDatabaseRoleWithName(t, databaseRoleName) t.Cleanup(databaseRoleCleanup) }, ConfigDirectory: acc.ConfigurationDirectory("TestAcc_GrantPrivilegesToDatabaseRole/OnSchemaObject_OnObject"), ConfigVariables: configVariables, Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(resourceName, "database_role_name", databaseRoleName), + resource.TestCheckResourceAttr(resourceName, "database_role_name", databaseRoleId.FullyQualifiedName()), resource.TestCheckResourceAttr(resourceName, "privileges.#", "2"), resource.TestCheckResourceAttr(resourceName, "privileges.0", string(sdk.SchemaObjectPrivilegeInsert)), resource.TestCheckResourceAttr(resourceName, "privileges.1", string(sdk.SchemaObjectPrivilegeUpdate)), resource.TestCheckResourceAttr(resourceName, "on_schema_object.#", "1"), resource.TestCheckResourceAttr(resourceName, "on_schema_object.0.object_type", string(sdk.ObjectTypeTable)), - resource.TestCheckResourceAttr(resourceName, "on_schema_object.0.object_name", tableName), + resource.TestCheckResourceAttr(resourceName, "on_schema_object.0.object_name", tableId.FullyQualifiedName()), resource.TestCheckResourceAttr(resourceName, "with_grant_option", "false"), - resource.TestCheckResourceAttr(resourceName, "id", fmt.Sprintf("%s|false|false|INSERT,UPDATE|OnSchemaObject|OnObject|TABLE|%s", databaseRoleName, tableName)), + resource.TestCheckResourceAttr(resourceName, "id", fmt.Sprintf("%s|false|false|INSERT,UPDATE|OnSchemaObject|OnObject|TABLE|%s", databaseRoleId.FullyQualifiedName(), tableId.FullyQualifiedName())), ), }, { diff --git a/pkg/resources/grant_privileges_to_share.go b/pkg/resources/grant_privileges_to_share.go index 73f05a30e3..bc7cd6573b 100644 --- a/pkg/resources/grant_privileges_to_share.go +++ b/pkg/resources/grant_privileges_to_share.go @@ -164,7 +164,7 @@ func CreateGrantPrivilegesToShare(ctx context.Context, d *schema.ResourceData, m id := createGrantPrivilegesToShareIdFromSchema(d) log.Printf("[DEBUG] created identifier from schema: %s", id.String()) - err := client.Grants.GrantPrivilegeToShare(ctx, getObjectPrivilegesFromSchema(d), getShareGrantOn(d), sdk.NewAccountObjectIdentifier(id.ShareName.Name())) + err := client.Grants.GrantPrivilegeToShare(ctx, getObjectPrivilegesFromSchema(d), getShareGrantOn(d), id.ShareName) if err != nil { return diag.Diagnostics{ diag.Diagnostic{ @@ -220,7 +220,7 @@ func UpdateGrantPrivilegesToShare(ctx context.Context, d *schema.ResourceData, m ctx, privilegesToAdd, grantOn, - sdk.NewAccountObjectIdentifier(id.ShareName.Name()), + id.ShareName, ) if err != nil { return diag.Diagnostics{ @@ -238,7 +238,7 @@ func UpdateGrantPrivilegesToShare(ctx context.Context, d *schema.ResourceData, m ctx, privilegesToRemove, grantOn, - sdk.NewAccountObjectIdentifier(id.ShareName.Name()), + id.ShareName, ) if err != nil { return diag.Diagnostics{ @@ -272,7 +272,7 @@ func DeleteGrantPrivilegesToShare(ctx context.Context, d *schema.ResourceData, m } } - err = client.Grants.RevokePrivilegeFromShare(ctx, getObjectPrivilegesFromSchema(d), getShareGrantOn(d), sdk.NewAccountObjectIdentifier(id.ShareName.Name())) + err = client.Grants.RevokePrivilegeFromShare(ctx, getObjectPrivilegesFromSchema(d), getShareGrantOn(d), id.ShareName) if err != nil { return diag.Diagnostics{ diag.Diagnostic{ diff --git a/pkg/resources/grant_privileges_to_share_acceptance_test.go b/pkg/resources/grant_privileges_to_share_acceptance_test.go index 6fea24a890..deae3d84aa 100644 --- a/pkg/resources/grant_privileges_to_share_acceptance_test.go +++ b/pkg/resources/grant_privileges_to_share_acceptance_test.go @@ -1,18 +1,14 @@ package resources_test import ( - "context" - "fmt" "regexp" "testing" - "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/internal/provider" - acc "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk" "github.com/hashicorp/terraform-plugin-testing/config" "github.com/hashicorp/terraform-plugin-testing/helper/resource" - "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-plugin-testing/tfversion" ) @@ -61,7 +57,7 @@ func TestAcc_GrantPrivilegesToShare_OnDatabase(t *testing.T) { { ConfigDirectory: acc.ConfigurationDirectory("TestAcc_GrantPrivilegesToShare/OnDatabase_NoGrant"), ConfigVariables: configVariables(false), - Check: testAccCheckSharePrivilegesRevoked(), + Check: acc.CheckSharePrivilegesRevoked(t), }, }, }) @@ -114,7 +110,7 @@ func TestAcc_GrantPrivilegesToShare_OnSchema(t *testing.T) { { ConfigDirectory: acc.ConfigurationDirectory("TestAcc_GrantPrivilegesToShare/OnSchema_NoGrant"), ConfigVariables: configVariables(false), - Check: testAccCheckSharePrivilegesRevoked(), + Check: acc.CheckSharePrivilegesRevoked(t), }, }, }) @@ -171,7 +167,7 @@ func TestAcc_GrantPrivilegesToShare_OnTable(t *testing.T) { { ConfigDirectory: acc.ConfigurationDirectory("TestAcc_GrantPrivilegesToShare/OnTable_NoGrant"), ConfigVariables: configVariables(false), - Check: testAccCheckSharePrivilegesRevoked(), + Check: acc.CheckSharePrivilegesRevoked(t), }, }, }) @@ -224,7 +220,7 @@ func TestAcc_GrantPrivilegesToShare_OnAllTablesInSchema(t *testing.T) { { ConfigDirectory: acc.ConfigurationDirectory("TestAcc_GrantPrivilegesToShare/OnAllTablesInSchema_NoGrant"), ConfigVariables: configVariables(false), - Check: testAccCheckSharePrivilegesRevoked(), + Check: acc.CheckSharePrivilegesRevoked(t), }, }, }) @@ -281,7 +277,7 @@ func TestAcc_GrantPrivilegesToShare_OnView(t *testing.T) { { ConfigDirectory: acc.ConfigurationDirectory("TestAcc_GrantPrivilegesToShare/OnView_NoGrant"), ConfigVariables: configVariables(false), - Check: testAccCheckSharePrivilegesRevoked(), + Check: acc.CheckSharePrivilegesRevoked(t), }, }, }) @@ -336,7 +332,7 @@ func TestAcc_GrantPrivilegesToShare_OnTag(t *testing.T) { { ConfigDirectory: acc.ConfigurationDirectory("TestAcc_GrantPrivilegesToShare/OnTag_NoGrant"), ConfigVariables: configVariables(false), - Check: testAccCheckSharePrivilegesRevoked(), + Check: acc.CheckSharePrivilegesRevoked(t), }, }, }) @@ -407,7 +403,7 @@ func TestAcc_GrantPrivilegesToShare_OnPrivilegeUpdate(t *testing.T) { { ConfigDirectory: acc.ConfigurationDirectory("TestAcc_GrantPrivilegesToShare/OnDatabase_NoGrant"), ConfigVariables: configVariables(false, []sdk.ObjectPrivilege{}), - Check: testAccCheckSharePrivilegesRevoked(), + Check: acc.CheckSharePrivilegesRevoked(t), }, }, }) @@ -458,7 +454,7 @@ func TestAcc_GrantPrivilegesToShare_OnDatabaseWithReferenceUsagePrivilege(t *tes { ConfigDirectory: acc.ConfigurationDirectory("TestAcc_GrantPrivilegesToShare/OnDatabase_NoGrant"), ConfigVariables: configVariables(false), - Check: testAccCheckSharePrivilegesRevoked(), + Check: acc.CheckSharePrivilegesRevoked(t), }, }, }) @@ -558,35 +554,3 @@ func TestAcc_GrantPrivilegesToShare_RemoveShareOutsideTerraform(t *testing.T) { }, }) } - -func testAccCheckSharePrivilegesRevoked() func(*terraform.State) error { - return func(state *terraform.State) error { - for _, rs := range state.RootModule().Resources { - if rs.Type != "snowflake_grant_privileges_to_share" { - continue - } - client := acc.TestAccProvider.Meta().(*provider.Context).Client - ctx := context.Background() - - id := sdk.NewExternalObjectIdentifierFromFullyQualifiedName(rs.Primary.Attributes["to_share"]) - grants, err := client.Grants.Show(ctx, &sdk.ShowGrantOptions{ - To: &sdk.ShowGrantsTo{ - Share: &sdk.ShowGrantsToShare{ - Name: sdk.NewAccountObjectIdentifier(id.Name()), - }, - }, - }) - if err != nil { - return err - } - var grantedPrivileges []string - for _, grant := range grants { - grantedPrivileges = append(grantedPrivileges, grant.Privilege) - } - if len(grantedPrivileges) > 0 { - return fmt.Errorf("share (%s) is still granted with privileges: %v", id.FullyQualifiedName(), grantedPrivileges) - } - } - return nil - } -} diff --git a/pkg/resources/masking_policy.go b/pkg/resources/masking_policy.go index 8206f1b2a0..46427f128c 100644 --- a/pkg/resources/masking_policy.go +++ b/pkg/resources/masking_policy.go @@ -253,7 +253,7 @@ func UpdateMaskingPolicy(d *schema.ResourceData, meta interface{}) error { ctx := context.Background() if d.HasChange("name") { - newID := sdk.NewSchemaObjectIdentifier(id.DatabaseName(), id.SchemaName(), d.Get("name").(string)) + newID := sdk.NewSchemaObjectIdentifierInSchema(id.SchemaId(), d.Get("name").(string)) err := client.MaskingPolicies.Alter(ctx, id, &sdk.AlterMaskingPolicyOptions{ NewName: &newID, diff --git a/pkg/resources/materialized_view.go b/pkg/resources/materialized_view.go index aad98d2bda..18c16b57c9 100644 --- a/pkg/resources/materialized_view.go +++ b/pkg/resources/materialized_view.go @@ -184,7 +184,7 @@ func UpdateMaterializedView(d *schema.ResourceData, meta interface{}) error { id := helpers.DecodeSnowflakeID(d.Id()).(sdk.SchemaObjectIdentifier) if d.HasChange("name") { - newId := sdk.NewSchemaObjectIdentifier(id.DatabaseName(), id.SchemaName(), d.Get("name").(string)) + newId := sdk.NewSchemaObjectIdentifierInSchema(id.SchemaId(), d.Get("name").(string)) err := client.MaterializedViews.Alter(ctx, sdk.NewAlterMaterializedViewRequest(id).WithRenameTo(&newId)) if err != nil { diff --git a/pkg/resources/materialized_view_acceptance_test.go b/pkg/resources/materialized_view_acceptance_test.go index 76b1bff4ec..6b24a143ac 100644 --- a/pkg/resources/materialized_view_acceptance_test.go +++ b/pkg/resources/materialized_view_acceptance_test.go @@ -1,7 +1,6 @@ package resources_test import ( - "context" "fmt" "testing" @@ -11,17 +10,17 @@ import ( "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/tfversion" - "github.com/stretchr/testify/require" ) func TestAcc_MaterializedView(t *testing.T) { - tableName := acc.TestClient().Ids.Alpha() - viewName := acc.TestClient().Ids.Alpha() + tableId := acc.TestClient().Ids.RandomSchemaObjectIdentifier() + viewId := acc.TestClient().Ids.RandomSchemaObjectIdentifier() + viewName := viewId.Name() - queryEscaped := fmt.Sprintf("SELECT ID, DATA FROM \\\"%s\\\"", tableName) - query := fmt.Sprintf(`SELECT ID, DATA FROM "%s"`, tableName) - otherQueryEscaped := fmt.Sprintf("SELECT ID, DATA FROM \\\"%s\\\" WHERE ID LIKE 'foo%%'", tableName) - otherQuery := fmt.Sprintf(`SELECT ID, DATA FROM "%s" WHERE ID LIKE 'foo%%'`, tableName) + queryEscaped := fmt.Sprintf("SELECT ID, DATA FROM \\\"%s\\\"", tableId.Name()) + query := fmt.Sprintf(`SELECT ID, DATA FROM "%s"`, tableId.Name()) + otherQueryEscaped := fmt.Sprintf("SELECT ID, DATA FROM \\\"%s\\\" WHERE ID LIKE 'foo%%'", tableId.Name()) + otherQuery := fmt.Sprintf(`SELECT ID, DATA FROM "%s" WHERE ID LIKE 'foo%%'`, tableId.Name()) resource.Test(t, resource.TestCase{ ProtoV6ProviderFactories: acc.TestAccProtoV6ProviderFactories, @@ -32,7 +31,7 @@ func TestAcc_MaterializedView(t *testing.T) { CheckDestroy: acc.CheckDestroy(t, resources.MaterializedView), Steps: []resource.TestStep{ { - Config: materializedViewConfig(acc.TestWarehouseName, tableName, viewName, queryEscaped, acc.TestDatabaseName, acc.TestSchemaName, "Terraform test resource", true, false), + Config: materializedViewConfig(acc.TestWarehouseName, tableId, viewId, queryEscaped, "Terraform test resource", true, false), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("snowflake_materialized_view.test", "name", viewName), resource.TestCheckResourceAttr("snowflake_materialized_view.test", "statement", query), @@ -45,7 +44,7 @@ func TestAcc_MaterializedView(t *testing.T) { }, // update parameters { - Config: materializedViewConfig(acc.TestWarehouseName, tableName, viewName, queryEscaped, acc.TestDatabaseName, acc.TestSchemaName, "other comment", false, false), + Config: materializedViewConfig(acc.TestWarehouseName, tableId, viewId, queryEscaped, "other comment", false, false), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("snowflake_materialized_view.test", "name", viewName), resource.TestCheckResourceAttr("snowflake_materialized_view.test", "statement", query), @@ -58,7 +57,7 @@ func TestAcc_MaterializedView(t *testing.T) { }, // change statement { - Config: materializedViewConfig(acc.TestWarehouseName, tableName, viewName, otherQueryEscaped, acc.TestDatabaseName, acc.TestSchemaName, "other comment", false, false), + Config: materializedViewConfig(acc.TestWarehouseName, tableId, viewId, otherQueryEscaped, "other comment", false, false), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("snowflake_materialized_view.test", "name", viewName), resource.TestCheckResourceAttr("snowflake_materialized_view.test", "statement", otherQuery), @@ -72,9 +71,9 @@ func TestAcc_MaterializedView(t *testing.T) { // change statement externally { PreConfig: func() { - alterMaterializedViewQueryExternally(t, sdk.NewSchemaObjectIdentifier(acc.TestDatabaseName, acc.TestSchemaName, viewName), query, acc.TestWarehouseName) + acc.TestClient().MaterializedView.CreateMaterializedViewWithName(t, viewId, query, true) }, - Config: materializedViewConfig(acc.TestWarehouseName, tableName, viewName, otherQueryEscaped, acc.TestDatabaseName, acc.TestSchemaName, "other comment", false, false), + Config: materializedViewConfig(acc.TestWarehouseName, tableId, viewId, otherQueryEscaped, "other comment", false, false), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("snowflake_materialized_view.test", "name", viewName), resource.TestCheckResourceAttr("snowflake_materialized_view.test", "statement", otherQuery), @@ -97,12 +96,13 @@ func TestAcc_MaterializedView(t *testing.T) { } func TestAcc_MaterializedView_Tags(t *testing.T) { - tableName := acc.TestClient().Ids.Alpha() - viewName := acc.TestClient().Ids.Alpha() + tableId := acc.TestClient().Ids.RandomSchemaObjectIdentifier() + viewId := acc.TestClient().Ids.RandomSchemaObjectIdentifier() + viewName := viewId.Name() tag1Name := acc.TestClient().Ids.Alpha() tag2Name := acc.TestClient().Ids.Alpha() - queryEscaped := fmt.Sprintf("SELECT ID FROM \\\"%s\\\"", tableName) + queryEscaped := fmt.Sprintf("SELECT ID FROM \\\"%s\\\"", tableId.Name()) resource.Test(t, resource.TestCase{ ProtoV6ProviderFactories: acc.TestAccProtoV6ProviderFactories, @@ -114,7 +114,7 @@ func TestAcc_MaterializedView_Tags(t *testing.T) { Steps: []resource.TestStep{ // create tags { - Config: materializedViewConfigWithTags(acc.TestWarehouseName, tableName, viewName, queryEscaped, acc.TestDatabaseName, acc.TestSchemaName, "test_tag", tag1Name, tag2Name), + Config: materializedViewConfigWithTags(acc.TestWarehouseName, tableId, viewId, queryEscaped, "test_tag", tag1Name, tag2Name), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("snowflake_materialized_view.test", "name", viewName), resource.TestCheckResourceAttr("snowflake_materialized_view.test", "tag.#", "1"), @@ -123,7 +123,7 @@ func TestAcc_MaterializedView_Tags(t *testing.T) { }, // update tags { - Config: materializedViewConfigWithTags(acc.TestWarehouseName, tableName, viewName, queryEscaped, acc.TestDatabaseName, acc.TestSchemaName, "test_tag_2", tag1Name, tag2Name), + Config: materializedViewConfigWithTags(acc.TestWarehouseName, tableId, viewId, queryEscaped, "test_tag_2", tag1Name, tag2Name), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("snowflake_materialized_view.test", "name", viewName), resource.TestCheckResourceAttr("snowflake_materialized_view.test", "tag.#", "1"), @@ -142,11 +142,11 @@ func TestAcc_MaterializedView_Tags(t *testing.T) { } func TestAcc_MaterializedView_Rename(t *testing.T) { - tableName := acc.TestClient().Ids.Alpha() - viewName := acc.TestClient().Ids.Alpha() - newViewName := acc.TestClient().Ids.Alpha() + tableId := acc.TestClient().Ids.RandomSchemaObjectIdentifier() + viewId := acc.TestClient().Ids.RandomSchemaObjectIdentifier() + newViewId := acc.TestClient().Ids.RandomSchemaObjectIdentifier() - queryEscaped := fmt.Sprintf("SELECT ID FROM \\\"%s\\\"", tableName) + queryEscaped := fmt.Sprintf("SELECT ID FROM \\\"%s\\\"", tableId.Name()) resource.Test(t, resource.TestCase{ ProtoV6ProviderFactories: acc.TestAccProtoV6ProviderFactories, @@ -157,28 +157,28 @@ func TestAcc_MaterializedView_Rename(t *testing.T) { CheckDestroy: acc.CheckDestroy(t, resources.MaterializedView), Steps: []resource.TestStep{ { - Config: materializedViewConfig(acc.TestWarehouseName, tableName, viewName, queryEscaped, acc.TestDatabaseName, acc.TestSchemaName, "Terraform test resource", true, false), + Config: materializedViewConfig(acc.TestWarehouseName, tableId, viewId, queryEscaped, "Terraform test resource", true, false), Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("snowflake_materialized_view.test", "name", viewName), + resource.TestCheckResourceAttr("snowflake_materialized_view.test", "name", viewId.Name()), ), }, // rename with one param change { - Config: materializedViewConfig(acc.TestWarehouseName, tableName, newViewName, queryEscaped, acc.TestDatabaseName, acc.TestSchemaName, "Terraform test resource", false, false), + Config: materializedViewConfig(acc.TestWarehouseName, tableId, newViewId, queryEscaped, "Terraform test resource", false, false), Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("snowflake_materialized_view.test", "name", newViewName), + resource.TestCheckResourceAttr("snowflake_materialized_view.test", "name", newViewId.Name()), ), }, }, }) } -func materializedViewConfig(warehouseName string, tableName string, viewName string, q string, databaseName string, schemaName string, comment string, isSecure bool, orReplace bool) string { +func materializedViewConfig(warehouseName string, tableId sdk.SchemaObjectIdentifier, viewId sdk.SchemaObjectIdentifier, q string, comment string, isSecure bool, orReplace bool) string { return fmt.Sprintf(` resource "snowflake_table" "test" { - name = "%s" - database = "%s" - schema = "%s" + name = "%[1]s" + database = "%[2]s" + schema = "%[3]s" column { name = "ID" @@ -192,23 +192,23 @@ resource "snowflake_table" "test" { } resource "snowflake_materialized_view" "test" { - name = "%s" - comment = "%s" - database = "%s" - schema = "%s" - warehouse = "%s" - is_secure = %t - or_replace = %t - statement = "%s" + name = "%[4]s" + comment = "%[5]s" + database = "%[2]s" + schema = "%[3]s" + warehouse = "%[6]s" + is_secure = %[7]t + or_replace = %[8]t + statement = "%[9]s" depends_on = [ snowflake_table.test ] } -`, tableName, databaseName, schemaName, viewName, comment, databaseName, schemaName, warehouseName, isSecure, orReplace, q) +`, tableId.Name(), viewId.DatabaseName(), viewId.SchemaName(), viewId.Name(), comment, warehouseName, isSecure, orReplace, q) } -func materializedViewConfigWithTags(warehouseName string, tableName string, viewName string, q string, databaseName string, schemaName string, tag string, tag1Name string, tag2Name string) string { +func materializedViewConfigWithTags(warehouseName string, tableId sdk.SchemaObjectIdentifier, viewId sdk.SchemaObjectIdentifier, q string, tag string, tag1Name string, tag2Name string) string { return fmt.Sprintf(` resource "snowflake_table" "test" { name = "%[1]s" @@ -251,18 +251,5 @@ resource "snowflake_materialized_view" "test" { snowflake_table.test ] } -`, tableName, databaseName, schemaName, viewName, warehouseName, q, tag, tag1Name, tag2Name) -} - -func alterMaterializedViewQueryExternally(t *testing.T, id sdk.SchemaObjectIdentifier, query string, warehouse string) { - t.Helper() - - client := acc.Client(t) - ctx := context.Background() - - err := client.Sessions.UseWarehouse(ctx, sdk.NewAccountObjectIdentifier(warehouse)) - require.NoError(t, err) - - err = client.MaterializedViews.Create(ctx, sdk.NewCreateMaterializedViewRequest(id, query).WithOrReplace(sdk.Bool(true))) - require.NoError(t, err) +`, tableId.Name(), viewId.DatabaseName(), viewId.SchemaName(), viewId.Name(), warehouseName, q, tag, tag1Name, tag2Name) } diff --git a/pkg/resources/network_policy.go b/pkg/resources/network_policy.go index 9d5f6446a8..66aa2e4bd7 100644 --- a/pkg/resources/network_policy.go +++ b/pkg/resources/network_policy.go @@ -6,10 +6,9 @@ import ( "log" "strings" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/helpers" "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/internal/provider" - "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) @@ -97,19 +96,19 @@ func CreateNetworkPolicy(d *schema.ResourceData, meta interface{}) error { // ReadNetworkPolicy implements schema.ReadFunc. func ReadNetworkPolicy(d *schema.ResourceData, meta interface{}) error { - policyName := d.Id() + id := helpers.DecodeSnowflakeID(d.Id()).(sdk.AccountObjectIdentifier) client := meta.(*provider.Context).Client ctx := context.Background() - networkPolicy, err := client.NetworkPolicies.ShowByID(ctx, sdk.NewAccountObjectIdentifier(policyName)) + networkPolicy, err := client.NetworkPolicies.ShowByID(ctx, id) if networkPolicy == nil || err != nil { // If not found, mark resource to be removed from state file during apply or refresh - log.Printf("[DEBUG] network policy (%s) not found", d.Id()) + log.Printf("[DEBUG] network policy (%s) not found", id.Name()) d.SetId("") return nil } - policyDescriptions, err := client.NetworkPolicies.Describe(ctx, sdk.NewAccountObjectIdentifier(policyName)) + policyDescriptions, err := client.NetworkPolicies.Describe(ctx, id) if err != nil { return err } @@ -140,10 +139,10 @@ func ReadNetworkPolicy(d *schema.ResourceData, meta interface{}) error { // UpdateNetworkPolicy implements schema.UpdateFunc. func UpdateNetworkPolicy(d *schema.ResourceData, meta interface{}) error { - name := d.Id() + id := helpers.DecodeSnowflakeID(d.Id()).(sdk.AccountObjectIdentifier) client := meta.(*provider.Context).Client ctx := context.Background() - baseReq := sdk.NewAlterNetworkPolicyRequest(sdk.NewAccountObjectIdentifier(name)) + baseReq := sdk.NewAlterNetworkPolicyRequest(id) if d.HasChange("comment") { comment := d.Get("comment") @@ -152,13 +151,13 @@ func UpdateNetworkPolicy(d *schema.ResourceData, meta interface{}) error { unsetReq := sdk.NewNetworkPolicyUnsetRequest().WithComment(sdk.Bool(true)) err := client.NetworkPolicies.Alter(ctx, baseReq.WithUnset(unsetReq)) if err != nil { - return fmt.Errorf("error unsetting comment for network policy %v err = %w", name, err) + return fmt.Errorf("error unsetting comment for network policy %v err = %w", id.Name(), err) } } else { setReq := sdk.NewNetworkPolicySetRequest().WithComment(sdk.String(comment.(string))) err := client.NetworkPolicies.Alter(ctx, baseReq.WithSet(setReq)) if err != nil { - return fmt.Errorf("error updating comment for network policy %v err = %w", name, err) + return fmt.Errorf("error updating comment for network policy %v err = %w", id.Name(), err) } } } @@ -172,7 +171,7 @@ func UpdateNetworkPolicy(d *schema.ResourceData, meta interface{}) error { setReq := sdk.NewNetworkPolicySetRequest().WithAllowedIpList(sdk.NewAllowedIPListRequest().WithAllowedIPList(ipRequests)) err := client.NetworkPolicies.Alter(ctx, baseReq.WithSet(setReq)) if err != nil { - return fmt.Errorf("error updating ALLOWED_IP_LIST for network policy %v err = %w", name, err) + return fmt.Errorf("error updating ALLOWED_IP_LIST for network policy %v err = %w", id.Name(), err) } } @@ -185,7 +184,7 @@ func UpdateNetworkPolicy(d *schema.ResourceData, meta interface{}) error { setReq := sdk.NewNetworkPolicySetRequest().WithBlockedIpList(sdk.NewBlockedIPListRequest().WithBlockedIPList(ipRequests)) err := client.NetworkPolicies.Alter(ctx, baseReq.WithSet(setReq)) if err != nil { - return fmt.Errorf("error updating BLOCKED_IP_LIST for network policy %v err = %w", name, err) + return fmt.Errorf("error updating BLOCKED_IP_LIST for network policy %v err = %w", id.Name(), err) } } @@ -194,13 +193,13 @@ func UpdateNetworkPolicy(d *schema.ResourceData, meta interface{}) error { // DeleteNetworkPolicy implements schema.DeleteFunc. func DeleteNetworkPolicy(d *schema.ResourceData, meta interface{}) error { - name := d.Id() + id := helpers.DecodeSnowflakeID(d.Id()).(sdk.AccountObjectIdentifier) client := meta.(*provider.Context).Client ctx := context.Background() - err := client.NetworkPolicies.Drop(ctx, sdk.NewDropNetworkPolicyRequest(sdk.NewAccountObjectIdentifier(name))) + err := client.NetworkPolicies.Drop(ctx, sdk.NewDropNetworkPolicyRequest(id)) if err != nil { - return fmt.Errorf("error deleting network policy %v err = %w", name, err) + return fmt.Errorf("error deleting network policy %v err = %w", id.Name(), err) } d.SetId("") diff --git a/pkg/resources/password_policy.go b/pkg/resources/password_policy.go index b83fd017e8..7035fc3895 100644 --- a/pkg/resources/password_policy.go +++ b/pkg/resources/password_policy.go @@ -267,7 +267,7 @@ func UpdatePasswordPolicy(d *schema.ResourceData, meta interface{}) error { objectIdentifier := helpers.DecodeSnowflakeID(d.Id()).(sdk.SchemaObjectIdentifier) if d.HasChange("name") { - newId := sdk.NewSchemaObjectIdentifier(objectIdentifier.DatabaseName(), objectIdentifier.SchemaName(), d.Get("name").(string)) + newId := sdk.NewSchemaObjectIdentifierInSchema(objectIdentifier.SchemaId(), d.Get("name").(string)) err := client.PasswordPolicies.Alter(ctx, objectIdentifier, &sdk.AlterPasswordPolicyOptions{ NewName: &newId, diff --git a/pkg/resources/procedure_acceptance_test.go b/pkg/resources/procedure_acceptance_test.go index e8f35ac4ef..ed406cb8d6 100644 --- a/pkg/resources/procedure_acceptance_test.go +++ b/pkg/resources/procedure_acceptance_test.go @@ -198,7 +198,8 @@ func TestAcc_Procedure_complex(t *testing.T) { } func TestAcc_Procedure_migrateFromVersion085(t *testing.T) { - name := acc.TestClient().Ids.Alpha() + id := acc.TestClient().Ids.RandomSchemaObjectIdentifier() + name := id.Name() resourceName := "snowflake_procedure.p" resource.Test(t, resource.TestCase{ @@ -231,7 +232,7 @@ func TestAcc_Procedure_migrateFromVersion085(t *testing.T) { PreApply: []plancheck.PlanCheck{plancheck.ExpectEmptyPlan()}, }, Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(resourceName, "id", sdk.NewSchemaObjectIdentifier(acc.TestDatabaseName, acc.TestSchemaName, name).FullyQualifiedName()), + resource.TestCheckResourceAttr(resourceName, "id", id.FullyQualifiedName()), resource.TestCheckResourceAttr(resourceName, "name", name), resource.TestCheckResourceAttr(resourceName, "database", acc.TestDatabaseName), resource.TestCheckResourceAttr(resourceName, "schema", acc.TestSchemaName), diff --git a/pkg/resources/schema.go b/pkg/resources/schema.go index fb8bf1fffd..686a20e328 100644 --- a/pkg/resources/schema.go +++ b/pkg/resources/schema.go @@ -107,7 +107,7 @@ func ReadSchema(d *schema.ResourceData, meta interface{}) error { ctx := context.Background() id := helpers.DecodeSnowflakeID(d.Id()).(sdk.DatabaseObjectIdentifier) - database, err := client.Databases.ShowByID(ctx, sdk.NewAccountObjectIdentifier(id.DatabaseName())) + database, err := client.Databases.ShowByID(ctx, id.DatabaseId()) if err != nil { d.SetId("") } diff --git a/pkg/resources/schema_acceptance_test.go b/pkg/resources/schema_acceptance_test.go index 819bdf8119..8538e6821a 100644 --- a/pkg/resources/schema_acceptance_test.go +++ b/pkg/resources/schema_acceptance_test.go @@ -310,7 +310,8 @@ func TestAcc_Schema_DefaultDataRetentionTime_SetOutsideOfTerraform(t *testing.T) } func TestAcc_Schema_RemoveDatabaseOutsideOfTerraform(t *testing.T) { - schemaName := acc.TestClient().Ids.Alpha() + schemaId := acc.TestClient().Ids.RandomDatabaseObjectIdentifier() + schemaName := schemaId.Name() configVariables := map[string]config.Variable{ "schema_name": config.StringVariable(schemaName), "database_name": config.StringVariable(acc.TestDatabaseName), @@ -330,7 +331,7 @@ func TestAcc_Schema_RemoveDatabaseOutsideOfTerraform(t *testing.T) { }, { PreConfig: func() { - acc.TestClient().Schema.DropSchemaFunc(t, sdk.NewDatabaseObjectIdentifier(acc.TestDatabaseName, schemaName))() + acc.TestClient().Schema.DropSchemaFunc(t, schemaId)() }, RefreshState: true, ExpectNonEmptyPlan: true, @@ -383,15 +384,15 @@ func TestAcc_Schema_RemoveSchemaOutsideOfTerraform(t *testing.T) { }) } -func checkDatabaseAndSchemaDataRetentionTime(t *testing.T, id sdk.DatabaseObjectIdentifier, expectedDatabaseRetentionsDays int, expectedSchemaRetentionDays int) func(state *terraform.State) error { +func checkDatabaseAndSchemaDataRetentionTime(t *testing.T, schemaId sdk.DatabaseObjectIdentifier, expectedDatabaseRetentionsDays int, expectedSchemaRetentionDays int) func(state *terraform.State) error { t.Helper() return func(state *terraform.State) error { - schema, err := acc.TestClient().Schema.Show(t, id) + schema, err := acc.TestClient().Schema.Show(t, schemaId) if err != nil { return err } - database, err := acc.TestClient().Database.Show(t, sdk.NewAccountObjectIdentifier(id.DatabaseName())) + database, err := acc.TestClient().Database.Show(t, schemaId.DatabaseId()) if err != nil { return err } diff --git a/pkg/resources/share.go b/pkg/resources/share.go index d6c3d5efe1..fe4a3872d0 100644 --- a/pkg/resources/share.go +++ b/pkg/resources/share.go @@ -7,12 +7,11 @@ import ( "strings" "time" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/helpers" "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/internal/provider" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk" "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) var shareSchema = map[string]*schema.Schema{ @@ -157,7 +156,7 @@ func setShareAccounts(ctx context.Context, client *sdk.Client, shareID sdk.Accou // ReadShare implements schema.ReadFunc. func ReadShare(d *schema.ResourceData, meta interface{}) error { client := meta.(*provider.Context).Client - id := sdk.NewAccountObjectIdentifier(d.Id()) + id := helpers.DecodeSnowflakeID(d.Id()).(sdk.AccountObjectIdentifier) ctx := context.Background() share, err := client.Shares.ShowByID(ctx, id) @@ -202,6 +201,7 @@ func accountIdentifiersFromSlice(accounts []string) []sdk.AccountIdentifier { // UpdateShare implements schema.UpdateFunc. func UpdateShare(d *schema.ResourceData, meta interface{}) error { + id := helpers.DecodeSnowflakeID(d.Id()).(sdk.AccountObjectIdentifier) client := meta.(*provider.Context).Client ctx := context.Background() if d.HasChange("accounts") { @@ -210,7 +210,7 @@ func UpdateShare(d *schema.ResourceData, meta interface{}) error { newAccounts := expandStringList(n.([]interface{})) if len(newAccounts) == 0 { accountIdentifiers := accountIdentifiersFromSlice(oldAccounts) - err := client.Shares.Alter(ctx, sdk.NewAccountObjectIdentifier(d.Id()), &sdk.AlterShareOptions{ + err := client.Shares.Alter(ctx, id, &sdk.AlterShareOptions{ Remove: &sdk.ShareRemove{ Accounts: accountIdentifiers, }, @@ -220,7 +220,7 @@ func UpdateShare(d *schema.ResourceData, meta interface{}) error { } } else { accountIdentifiers := accountIdentifiersFromSlice(newAccounts) - err := setShareAccounts(ctx, client, sdk.NewAccountObjectIdentifier(d.Id()), accountIdentifiers) + err := setShareAccounts(ctx, client, id, accountIdentifiers) if err != nil { return err } @@ -228,7 +228,7 @@ func UpdateShare(d *schema.ResourceData, meta interface{}) error { } if d.HasChange("comment") { comment := d.Get("comment").(string) - err := client.Shares.Alter(ctx, sdk.NewAccountObjectIdentifier(d.Id()), &sdk.AlterShareOptions{ + err := client.Shares.Alter(ctx, id, &sdk.AlterShareOptions{ Set: &sdk.ShareSet{ Comment: sdk.String(comment), }, @@ -243,9 +243,10 @@ func UpdateShare(d *schema.ResourceData, meta interface{}) error { // DeleteShare implements schema.DeleteFunc. func DeleteShare(d *schema.ResourceData, meta interface{}) error { + id := helpers.DecodeSnowflakeID(d.Id()).(sdk.AccountObjectIdentifier) client := meta.(*provider.Context).Client ctx := context.Background() - err := client.Shares.Drop(ctx, sdk.NewAccountObjectIdentifier(d.Id()), &sdk.DropShareOptions{IfExists: sdk.Bool(true)}) + err := client.Shares.Drop(ctx, id, &sdk.DropShareOptions{IfExists: sdk.Bool(true)}) if err != nil { return fmt.Errorf("error deleting share (%v) err = %w", d.Id(), err) } diff --git a/pkg/resources/stage_acceptance_test.go b/pkg/resources/stage_acceptance_test.go index c68c60597a..c6f97e53f2 100644 --- a/pkg/resources/stage_acceptance_test.go +++ b/pkg/resources/stage_acceptance_test.go @@ -7,6 +7,7 @@ import ( acc "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance" "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance/helpers/random" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance/ids" "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance/testenvs" "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/provider/resources" "github.com/hashicorp/terraform-plugin-testing/config" @@ -60,7 +61,7 @@ func TestAcc_Stage_CreateAndAlter(t *testing.T) { copyOptionsWithQuotes := "ON_ERROR = 'CONTINUE'" changedUrl := awsBucketUrl + "/some-path" - changedStorageIntegration := "S3_STORAGE_INTEGRATION" + changedStorageIntegration := ids.PrecreatedS3StorageIntegration changedEncryption := "TYPE = 'AWS_SSE_S3'" changedFileFormat := "TYPE = JSON NULL_IF = []" changedComment := random.Comment() @@ -111,12 +112,12 @@ func TestAcc_Stage_CreateAndAlter(t *testing.T) { }, { ConfigDirectory: config.TestNameDirectory(), - ConfigVariables: configVariables(changedUrl, changedStorageIntegration, credentials, changedEncryption, changedFileFormat, changedComment, copyOptionsWithoutQuotes), + ConfigVariables: configVariables(changedUrl, changedStorageIntegration.Name(), credentials, changedEncryption, changedFileFormat, changedComment, copyOptionsWithoutQuotes), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "database", databaseName), resource.TestCheckResourceAttr(resourceName, "schema", schemaName), resource.TestCheckResourceAttr(resourceName, "name", name), - resource.TestCheckResourceAttr(resourceName, "storage_integration", changedStorageIntegration), + resource.TestCheckResourceAttr(resourceName, "storage_integration", changedStorageIntegration.Name()), resource.TestCheckResourceAttr(resourceName, "credentials", credentials), resource.TestCheckResourceAttr(resourceName, "encryption", changedEncryption), resource.TestCheckResourceAttr(resourceName, "file_format", changedFileFormat), @@ -130,7 +131,7 @@ func TestAcc_Stage_CreateAndAlter(t *testing.T) { }, { ConfigDirectory: config.TestNameDirectory(), - ConfigVariables: configVariables(changedUrl, changedStorageIntegration, credentials, changedEncryption, changedFileFormat, changedComment, copyOptionsWithoutQuotes), + ConfigVariables: configVariables(changedUrl, changedStorageIntegration.Name(), credentials, changedEncryption, changedFileFormat, changedComment, copyOptionsWithoutQuotes), Destroy: true, }, { diff --git a/pkg/resources/table.go b/pkg/resources/table.go index 8073c31d24..3b09f11627 100644 --- a/pkg/resources/table.go +++ b/pkg/resources/table.go @@ -693,7 +693,7 @@ func UpdateTable(d *schema.ResourceData, meta interface{}) error { id := helpers.DecodeSnowflakeID(d.Id()).(sdk.SchemaObjectIdentifier) if d.HasChange("name") { - newId := sdk.NewSchemaObjectIdentifier(id.DatabaseName(), id.SchemaName(), d.Get("name").(string)) + newId := sdk.NewSchemaObjectIdentifierInSchema(id.SchemaId(), d.Get("name").(string)) err := client.Tables.Alter(ctx, sdk.NewAlterTableRequest(id).WithNewName(&newId)) if err != nil { diff --git a/pkg/resources/table_acceptance_test.go b/pkg/resources/table_acceptance_test.go index 45bed45199..9bdbfde50e 100644 --- a/pkg/resources/table_acceptance_test.go +++ b/pkg/resources/table_acceptance_test.go @@ -17,7 +17,6 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-plugin-testing/tfversion" - "github.com/stretchr/testify/require" ) func TestAcc_TableWithSeparateDataRetentionObjectParameterWithoutLifecycle(t *testing.T) { @@ -1445,7 +1444,7 @@ func TestAcc_Table_MaskingPolicy(t *testing.T) { Config: tableWithMaskingPolicy(accName, acc.TestDatabaseName, acc.TestSchemaName, "policy1"), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("snowflake_table.test_table", "name", accName), - resource.TestCheckResourceAttr("snowflake_table.test_table", "column.0.masking_policy", sdk.NewSchemaObjectIdentifier(acc.TestDatabaseName, acc.TestSchemaName, fmt.Sprintf("%s1", accName)).FullyQualifiedName()), + resource.TestCheckResourceAttr("snowflake_table.test_table", "column.0.masking_policy", acc.TestClient().Ids.NewSchemaObjectIdentifier(fmt.Sprintf("%s1", accName)).FullyQualifiedName()), ), }, // this step proves https://github.com/Snowflake-Labs/terraform-provider-snowflake/pull/2186 @@ -1453,7 +1452,7 @@ func TestAcc_Table_MaskingPolicy(t *testing.T) { Config: tableWithMaskingPolicy(accName, acc.TestDatabaseName, acc.TestSchemaName, "policy2"), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("snowflake_table.test_table", "name", accName), - resource.TestCheckResourceAttr("snowflake_table.test_table", "column.0.masking_policy", sdk.NewSchemaObjectIdentifier(acc.TestDatabaseName, acc.TestSchemaName, fmt.Sprintf("%s2", accName)).FullyQualifiedName()), + resource.TestCheckResourceAttr("snowflake_table.test_table", "column.0.masking_policy", acc.TestClient().Ids.NewSchemaObjectIdentifier(fmt.Sprintf("%s2", accName)).FullyQualifiedName()), ), }, }, @@ -1604,7 +1603,9 @@ func TestAcc_Table_DefaultDataRetentionTime_SetOutsideOfTerraform(t *testing.T) ), }, { - PreConfig: setTableDataRetentionTime(t, id, 20), + PreConfig: func() { + acc.TestClient().Table.SetDataRetentionTime(t, id, 20) + }, ConfigDirectory: acc.ConfigurationDirectory("TestAcc_Table_DefaultDataRetentionTime/WithDatabaseDataRetentionSet"), ConfigVariables: configWithDatabaseDataRetentionSet(5), Check: resource.ComposeTestCheckFunc( @@ -1860,7 +1861,7 @@ func checkDatabaseSchemaAndTableDataRetentionTime(id sdk.SchemaObjectIdentifier, client := acc.TestAccProvider.Meta().(*provider.Context).Client ctx := context.Background() - database, err := client.Databases.ShowByID(ctx, sdk.NewAccountObjectIdentifier(id.DatabaseName())) + database, err := client.Databases.ShowByID(ctx, id.DatabaseId()) if err != nil { return err } @@ -1869,7 +1870,7 @@ func checkDatabaseSchemaAndTableDataRetentionTime(id sdk.SchemaObjectIdentifier, return fmt.Errorf("invalid database retention time, expected: %d, got: %d", expectedDatabaseRetentionDays, database.RetentionTime) } - s, err := client.Schemas.ShowByID(ctx, sdk.NewDatabaseObjectIdentifier(id.DatabaseName(), id.SchemaName())) + s, err := client.Schemas.ShowByID(ctx, id.SchemaId()) if err != nil { return err } @@ -1905,18 +1906,6 @@ func checkDatabaseSchemaAndTableDataRetentionTime(id sdk.SchemaObjectIdentifier, } } -func setTableDataRetentionTime(t *testing.T, id sdk.SchemaObjectIdentifier, days int) func() { - t.Helper() - - return func() { - client := acc.Client(t) - ctx := context.Background() - - err := client.Tables.Alter(ctx, sdk.NewAlterTableRequest(id).WithSet(sdk.NewTableSetRequest().WithDataRetentionTimeInDays(sdk.Int(days)))) - require.NoError(t, err) - } -} - // proves https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2733 is fixed func TestAcc_Table_gh2733(t *testing.T) { name := acc.TestClient().Ids.Alpha() diff --git a/pkg/resources/table_constraint_acceptance_test.go b/pkg/resources/table_constraint_acceptance_test.go index 9d1f65c371..8d09287322 100644 --- a/pkg/resources/table_constraint_acceptance_test.go +++ b/pkg/resources/table_constraint_acceptance_test.go @@ -89,7 +89,8 @@ resource "snowflake_table_constraint" "fk" { // It is connected with https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2629. // Provider defaults will be reworked during resources redesign. func TestAcc_TableConstraint_pk(t *testing.T) { - tableName := acc.TestClient().Ids.Alpha() + tableId := acc.TestClient().Ids.RandomSchemaObjectIdentifier() + tableName := tableId.Name() constraintName := fmt.Sprintf("%s_pk", tableName) resource.Test(t, resource.TestCase{ @@ -105,7 +106,7 @@ func TestAcc_TableConstraint_pk(t *testing.T) { Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("snowflake_table_constraint.pk", "type", "PRIMARY KEY"), resource.TestCheckResourceAttr("snowflake_table_constraint.pk", "comment", "hello pk"), - checkPrimaryKeyExists(sdk.NewSchemaObjectIdentifier(acc.TestDatabaseName, acc.TestSchemaName, tableName), constraintName), + checkPrimaryKeyExists(tableId, constraintName), ), }, }, diff --git a/pkg/resources/tag_association_acceptance_test.go b/pkg/resources/tag_association_acceptance_test.go index 587b16247a..420116c57d 100644 --- a/pkg/resources/tag_association_acceptance_test.go +++ b/pkg/resources/tag_association_acceptance_test.go @@ -146,14 +146,14 @@ func TestAcc_TagAssociationIssue1202(t *testing.T) { } func TestAcc_TagAssociationIssue1909(t *testing.T) { - tagName := acc.TestClient().Ids.Alpha() + tagId := acc.TestClient().Ids.RandomSchemaObjectIdentifier() + tagName := tagId.Name() tableName := acc.TestClient().Ids.Alpha() tableName2 := acc.TestClient().Ids.Alpha() columnName := "test.column" resourceName := "snowflake_tag_association.test" objectID := sdk.NewTableColumnIdentifier(acc.TestDatabaseName, acc.TestSchemaName, tableName, columnName) objectID2 := sdk.NewTableColumnIdentifier(acc.TestDatabaseName, acc.TestSchemaName, tableName2, columnName) - tagID := sdk.NewSchemaObjectIdentifier(acc.TestDatabaseName, acc.TestSchemaName, tagName) m := func() map[string]config.Variable { return map[string]config.Variable{ "tag_name": config.StringVariable(tagName), @@ -179,8 +179,8 @@ func TestAcc_TagAssociationIssue1909(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "object_type", "COLUMN"), resource.TestCheckResourceAttr(resourceName, "tag_id", fmt.Sprintf("%s|%s|%s", acc.TestDatabaseName, acc.TestSchemaName, tagName)), resource.TestCheckResourceAttr(resourceName, "tag_value", "v1"), - testAccCheckTableColumnTagAssociation(tagID, objectID, "v1"), - testAccCheckTableColumnTagAssociation(tagID, objectID2, "v1"), + testAccCheckTableColumnTagAssociation(tagId, objectID, "v1"), + testAccCheckTableColumnTagAssociation(tagId, objectID2, "v1"), ), }, }, diff --git a/pkg/resources/task.go b/pkg/resources/task.go index 6199ae00ef..11cace7614 100644 --- a/pkg/resources/task.go +++ b/pkg/resources/task.go @@ -485,7 +485,7 @@ func UpdateTask(d *schema.ResourceData, meta interface{}) error { toRemove := make([]sdk.SchemaObjectIdentifier, 0) for _, dep := range oldAfter { if !slices.Contains(newAfter, dep) { - toRemove = append(toRemove, sdk.NewSchemaObjectIdentifier(taskId.DatabaseName(), taskId.SchemaName(), dep)) + toRemove = append(toRemove, sdk.NewSchemaObjectIdentifierInSchema(taskId.SchemaId(), dep)) } } if len(toRemove) > 0 { @@ -498,7 +498,7 @@ func UpdateTask(d *schema.ResourceData, meta interface{}) error { toAdd := make([]sdk.SchemaObjectIdentifier, 0) for _, dep := range newAfter { if !slices.Contains(oldAfter, dep) { - toAdd = append(toAdd, sdk.NewSchemaObjectIdentifier(taskId.DatabaseName(), taskId.SchemaName(), dep)) + toAdd = append(toAdd, sdk.NewSchemaObjectIdentifierInSchema(taskId.SchemaId(), dep)) } } if len(toAdd) > 0 { diff --git a/pkg/resources/testdata/TestAcc_GrantApplicationRole/account_role/test.tf b/pkg/resources/testdata/TestAcc_GrantApplicationRole/account_role/test.tf index 9c30ace9ec..6bf7dd53e9 100644 --- a/pkg/resources/testdata/TestAcc_GrantApplicationRole/account_role/test.tf +++ b/pkg/resources/testdata/TestAcc_GrantApplicationRole/account_role/test.tf @@ -1,5 +1,5 @@ locals { - application_role_identifier = "\"${var.application_name}\".\"app_role_1\"" + application_role_identifier = "\"${var.application_name}\".\"${var.application_role_name}\"" } resource "snowflake_grant_application_role" "g" { diff --git a/pkg/resources/testdata/TestAcc_GrantApplicationRole/account_role/variables.tf b/pkg/resources/testdata/TestAcc_GrantApplicationRole/account_role/variables.tf index 4bf89421b8..76b98d1412 100644 --- a/pkg/resources/testdata/TestAcc_GrantApplicationRole/account_role/variables.tf +++ b/pkg/resources/testdata/TestAcc_GrantApplicationRole/account_role/variables.tf @@ -5,3 +5,7 @@ variable "parent_account_role_name" { variable "application_name" { type = string } + +variable "application_role_name" { + type = string +} diff --git a/pkg/resources/testdata/TestAcc_GrantApplicationRole/application/test.tf b/pkg/resources/testdata/TestAcc_GrantApplicationRole/application/test.tf index 2013b03833..3605109597 100644 --- a/pkg/resources/testdata/TestAcc_GrantApplicationRole/application/test.tf +++ b/pkg/resources/testdata/TestAcc_GrantApplicationRole/application/test.tf @@ -1,5 +1,5 @@ locals { - application_role_identifier = "\"${var.application_name}\".\"app_role_1\"" + application_role_identifier = "\"${var.application_name}\".\"${var.application_role_name}\"" } resource "snowflake_grant_application_role" "g" { diff --git a/pkg/resources/testdata/TestAcc_GrantApplicationRole/application/variables.tf b/pkg/resources/testdata/TestAcc_GrantApplicationRole/application/variables.tf index 386d3898ee..77f0e8bdf3 100644 --- a/pkg/resources/testdata/TestAcc_GrantApplicationRole/application/variables.tf +++ b/pkg/resources/testdata/TestAcc_GrantApplicationRole/application/variables.tf @@ -5,3 +5,7 @@ variable "application_name" { variable "application_name2" { type = string } + +variable "application_role_name" { + type = string +} diff --git a/pkg/resources/unsafe_execute_acceptance_test.go b/pkg/resources/unsafe_execute_acceptance_test.go index 2cf8abc7f0..735874cb9d 100644 --- a/pkg/resources/unsafe_execute_acceptance_test.go +++ b/pkg/resources/unsafe_execute_acceptance_test.go @@ -2,15 +2,14 @@ package resources_test import ( "context" - "crypto/rand" "errors" "fmt" - "math/big" "regexp" "strings" "testing" acc "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk" "github.com/hashicorp/terraform-plugin-testing/config" "github.com/hashicorp/terraform-plugin-testing/helper/resource" @@ -22,9 +21,12 @@ import ( ) func TestAcc_UnsafeExecute_basic(t *testing.T) { - id := acc.TestClient().Ids.RandomAccountObjectIdentifierWithPrefix("UNSAFE_EXECUTE_TEST_DATABASE_").Name() - idLowerCase := strings.ToLower(acc.TestClient().Ids.RandomAccountObjectIdentifierWithPrefix("UNSAFE_EXECUTE_TEST_DATABASE_").Name()) - idLowerCaseEscaped := fmt.Sprintf(`"%s"`, idLowerCase) + id := acc.TestClient().Ids.RandomAccountObjectIdentifierWithPrefix("UNSAFE_EXECUTE_TEST_DATABASE_") + name := id.Name() + secondId := acc.TestClient().Ids.RandomAccountObjectIdentifierWithPrefix("UNSAFE_EXECUTE_TEST_DATABASE_") + nameLowerCase := strings.ToLower(secondId.Name()) + secondIdLowerCased := sdk.NewAccountObjectIdentifier(nameLowerCase) + nameLowerCaseEscaped := fmt.Sprintf(`"%s"`, nameLowerCase) createDatabaseStatement := func(id string) string { return fmt.Sprintf("create database %s", id) } dropDatabaseStatement := func(id string) string { return fmt.Sprintf("drop database %s", id) } @@ -46,13 +48,13 @@ func TestAcc_UnsafeExecute_basic(t *testing.T) { Steps: []resource.TestStep{ { ConfigDirectory: acc.ConfigurationDirectory("TestAcc_UnsafeExecute_commonSetup"), - ConfigVariables: createConfigVariables(id), + ConfigVariables: createConfigVariables(name), ConfigPlanChecks: resource.ConfigPlanChecks{ PreApply: []plancheck.PlanCheck{plancheck.ExpectNonEmptyPlan()}, }, Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(resourceName, "execute", createDatabaseStatement(id)), - resource.TestCheckResourceAttr(resourceName, "revert", dropDatabaseStatement(id)), + resource.TestCheckResourceAttr(resourceName, "execute", createDatabaseStatement(name)), + resource.TestCheckResourceAttr(resourceName, "revert", dropDatabaseStatement(name)), resource.TestCheckNoResourceAttr(resourceName, "query"), resource.TestCheckNoResourceAttr(resourceName, "query_results.#"), resource.TestCheckResourceAttrSet(resourceName, "id"), @@ -68,21 +70,21 @@ func TestAcc_UnsafeExecute_basic(t *testing.T) { TerraformVersionChecks: []tfversion.TerraformVersionCheck{ tfversion.RequireAbove(tfversion.Version1_5_0), }, - CheckDestroy: testAccCheckDatabaseExistence(t, idLowerCase, false), + CheckDestroy: testAccCheckDatabaseExistence(t, secondIdLowerCased, false), Steps: []resource.TestStep{ { ConfigDirectory: acc.ConfigurationDirectory("TestAcc_UnsafeExecute_commonSetup"), - ConfigVariables: createConfigVariables(idLowerCaseEscaped), + ConfigVariables: createConfigVariables(nameLowerCaseEscaped), ConfigPlanChecks: resource.ConfigPlanChecks{ PreApply: []plancheck.PlanCheck{plancheck.ExpectNonEmptyPlan()}, }, Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(resourceName, "execute", createDatabaseStatement(idLowerCaseEscaped)), - resource.TestCheckResourceAttr(resourceName, "revert", dropDatabaseStatement(idLowerCaseEscaped)), + resource.TestCheckResourceAttr(resourceName, "execute", createDatabaseStatement(nameLowerCaseEscaped)), + resource.TestCheckResourceAttr(resourceName, "revert", dropDatabaseStatement(nameLowerCaseEscaped)), resource.TestCheckNoResourceAttr(resourceName, "query"), resource.TestCheckNoResourceAttr(resourceName, "query_results.#"), resource.TestCheckResourceAttrSet(resourceName, "id"), - testAccCheckDatabaseExistence(t, idLowerCase, true), + testAccCheckDatabaseExistence(t, secondIdLowerCased, true), ), }, }, @@ -90,7 +92,8 @@ func TestAcc_UnsafeExecute_basic(t *testing.T) { } func TestAcc_UnsafeExecute_withRead(t *testing.T) { - id := acc.TestClient().Ids.RandomAccountObjectIdentifierWithPrefix("UNSAFE_EXECUTE_TEST_DATABASE_").Name() + id := acc.TestClient().Ids.RandomAccountObjectIdentifierWithPrefix("UNSAFE_EXECUTE_TEST_DATABASE_") + name := id.Name() createDatabaseStatement := func(id string) string { return fmt.Sprintf("create database %s", id) } dropDatabaseStatement := func(id string) string { return fmt.Sprintf("drop database %s", id) } showDatabaseStatement := func(id string) string { return fmt.Sprintf("show databases like '%%%s%%'", id) } @@ -114,18 +117,18 @@ func TestAcc_UnsafeExecute_withRead(t *testing.T) { Steps: []resource.TestStep{ { ConfigDirectory: acc.ConfigurationDirectory("TestAcc_UnsafeExecute_withRead"), - ConfigVariables: createConfigVariables(id), + ConfigVariables: createConfigVariables(name), ConfigPlanChecks: resource.ConfigPlanChecks{ PreApply: []plancheck.PlanCheck{plancheck.ExpectNonEmptyPlan()}, }, Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(resourceName, "execute", createDatabaseStatement(id)), - resource.TestCheckResourceAttr(resourceName, "revert", dropDatabaseStatement(id)), - resource.TestCheckResourceAttr(resourceName, "query", showDatabaseStatement(id)), + resource.TestCheckResourceAttr(resourceName, "execute", createDatabaseStatement(name)), + resource.TestCheckResourceAttr(resourceName, "revert", dropDatabaseStatement(name)), + resource.TestCheckResourceAttr(resourceName, "query", showDatabaseStatement(name)), resource.TestCheckResourceAttrSet(resourceName, "id"), testAccCheckDatabaseExistence(t, id, true), resource.TestCheckResourceAttrSet(resourceName, "query_results.#"), - resource.TestCheckResourceAttr(resourceName, "query_results.0.name", id), + resource.TestCheckResourceAttr(resourceName, "query_results.0.name", name), resource.TestCheckResourceAttrSet(resourceName, "query_results.0.created_on"), resource.TestCheckResourceAttr(resourceName, "query_results.0.budget", ""), resource.TestCheckResourceAttr(resourceName, "query_results.0.comment", ""), @@ -136,7 +139,8 @@ func TestAcc_UnsafeExecute_withRead(t *testing.T) { } func TestAcc_UnsafeExecute_readRemoved(t *testing.T) { - id := acc.TestClient().Ids.RandomAccountObjectIdentifierWithPrefix("UNSAFE_EXECUTE_TEST_DATABASE_").Name() + id := acc.TestClient().Ids.RandomAccountObjectIdentifierWithPrefix("UNSAFE_EXECUTE_TEST_DATABASE_") + name := id.Name() createDatabaseStatement := func(id string) string { return fmt.Sprintf("create database %s", id) } dropDatabaseStatement := func(id string) string { return fmt.Sprintf("drop database %s", id) } showDatabaseStatement := func(id string) string { return fmt.Sprintf("show databases like '%%%s%%'", id) } @@ -153,23 +157,23 @@ func TestAcc_UnsafeExecute_readRemoved(t *testing.T) { { ConfigDirectory: acc.ConfigurationDirectory("TestAcc_UnsafeExecute_withRead"), ConfigVariables: map[string]config.Variable{ - "execute": config.StringVariable(createDatabaseStatement(id)), - "revert": config.StringVariable(dropDatabaseStatement(id)), - "query": config.StringVariable(showDatabaseStatement(id)), + "execute": config.StringVariable(createDatabaseStatement(name)), + "revert": config.StringVariable(dropDatabaseStatement(name)), + "query": config.StringVariable(showDatabaseStatement(name)), }, ConfigPlanChecks: resource.ConfigPlanChecks{ PreApply: []plancheck.PlanCheck{plancheck.ExpectNonEmptyPlan()}, }, Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(resourceName, "query", showDatabaseStatement(id)), + resource.TestCheckResourceAttr(resourceName, "query", showDatabaseStatement(name)), resource.TestCheckResourceAttrSet(resourceName, "query_results.#"), ), }, { ConfigDirectory: acc.ConfigurationDirectory("TestAcc_UnsafeExecute_withRead"), ConfigVariables: map[string]config.Variable{ - "execute": config.StringVariable(createDatabaseStatement(id)), - "revert": config.StringVariable(dropDatabaseStatement(id)), + "execute": config.StringVariable(createDatabaseStatement(name)), + "revert": config.StringVariable(dropDatabaseStatement(name)), "query": config.StringVariable(""), }, ConfigPlanChecks: resource.ConfigPlanChecks{ @@ -185,7 +189,8 @@ func TestAcc_UnsafeExecute_readRemoved(t *testing.T) { } func TestAcc_UnsafeExecute_badQuery(t *testing.T) { - id := acc.TestClient().Ids.RandomAccountObjectIdentifierWithPrefix("UNSAFE_EXECUTE_TEST_DATABASE_").Name() + id := acc.TestClient().Ids.RandomAccountObjectIdentifierWithPrefix("UNSAFE_EXECUTE_TEST_DATABASE_") + name := id.Name() createDatabaseStatement := func(id string) string { return fmt.Sprintf("create database %s", id) } dropDatabaseStatement := func(id string) string { return fmt.Sprintf("drop database %s", id) } showDatabaseStatement := func(id string) string { return fmt.Sprintf("show databases like '%%%s%%'", id) } @@ -202,16 +207,16 @@ func TestAcc_UnsafeExecute_badQuery(t *testing.T) { { ConfigDirectory: acc.ConfigurationDirectory("TestAcc_UnsafeExecute_withRead"), ConfigVariables: map[string]config.Variable{ - "execute": config.StringVariable(createDatabaseStatement(id)), - "revert": config.StringVariable(dropDatabaseStatement(id)), + "execute": config.StringVariable(createDatabaseStatement(name)), + "revert": config.StringVariable(dropDatabaseStatement(name)), "query": config.StringVariable("bad query"), }, ConfigPlanChecks: resource.ConfigPlanChecks{ PreApply: []plancheck.PlanCheck{plancheck.ExpectNonEmptyPlan()}, }, Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(resourceName, "execute", createDatabaseStatement(id)), - resource.TestCheckResourceAttr(resourceName, "revert", dropDatabaseStatement(id)), + resource.TestCheckResourceAttr(resourceName, "execute", createDatabaseStatement(name)), + resource.TestCheckResourceAttr(resourceName, "revert", dropDatabaseStatement(name)), resource.TestCheckResourceAttr(resourceName, "query", "bad query"), resource.TestCheckNoResourceAttr(resourceName, "query_results.#"), testAccCheckDatabaseExistence(t, id, true), @@ -220,17 +225,17 @@ func TestAcc_UnsafeExecute_badQuery(t *testing.T) { { ConfigDirectory: acc.ConfigurationDirectory("TestAcc_UnsafeExecute_withRead"), ConfigVariables: map[string]config.Variable{ - "execute": config.StringVariable(createDatabaseStatement(id)), - "revert": config.StringVariable(dropDatabaseStatement(id)), - "query": config.StringVariable(showDatabaseStatement(id)), + "execute": config.StringVariable(createDatabaseStatement(name)), + "revert": config.StringVariable(dropDatabaseStatement(name)), + "query": config.StringVariable(showDatabaseStatement(name)), }, ConfigPlanChecks: resource.ConfigPlanChecks{ PreApply: []plancheck.PlanCheck{plancheck.ExpectNonEmptyPlan()}, }, Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(resourceName, "query", showDatabaseStatement(id)), + resource.TestCheckResourceAttr(resourceName, "query", showDatabaseStatement(name)), resource.TestCheckResourceAttrSet(resourceName, "query_results.#"), - resource.TestCheckResourceAttr(resourceName, "query_results.0.name", id), + resource.TestCheckResourceAttr(resourceName, "query_results.0.name", name), testAccCheckDatabaseExistence(t, id, true), ), }, @@ -269,8 +274,10 @@ func TestAcc_UnsafeExecute_invalidExecuteStatement(t *testing.T) { } func TestAcc_UnsafeExecute_invalidRevertStatement(t *testing.T) { - id := acc.TestClient().Ids.RandomAccountObjectIdentifierWithPrefix("UNSAFE_EXECUTE_TEST_DATABASE_").Name() - updatedId := acc.TestClient().Ids.RandomAccountObjectIdentifierWithPrefix("UNSAFE_EXECUTE_TEST_DATABASE_").Name() + id := acc.TestClient().Ids.RandomAccountObjectIdentifierWithPrefix("UNSAFE_EXECUTE_TEST_DATABASE_") + name := id.Name() + updatedId := acc.TestClient().Ids.RandomAccountObjectIdentifierWithPrefix("UNSAFE_EXECUTE_TEST_DATABASE_") + updatedName := updatedId.Name() createDatabaseStatement := func(id string) string { return fmt.Sprintf("create database %s", id) } dropDatabaseStatement := func(id string) string { return fmt.Sprintf("drop database %s", id) } invalidDropStatement := "drop database" @@ -298,14 +305,14 @@ func TestAcc_UnsafeExecute_invalidRevertStatement(t *testing.T) { { ConfigDirectory: acc.ConfigurationDirectory("TestAcc_UnsafeExecute_commonSetup"), ConfigVariables: map[string]config.Variable{ - "execute": config.StringVariable(createDatabaseStatement(id)), + "execute": config.StringVariable(createDatabaseStatement(name)), "revert": config.StringVariable(invalidDropStatement), }, ConfigPlanChecks: resource.ConfigPlanChecks{ PreApply: []plancheck.PlanCheck{plancheck.ExpectNonEmptyPlan()}, }, Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(resourceName, "execute", createDatabaseStatement(id)), + resource.TestCheckResourceAttr(resourceName, "execute", createDatabaseStatement(name)), resource.TestCheckResourceAttr(resourceName, "revert", invalidDropStatement), resource.TestCheckResourceAttrSet(resourceName, "id"), testAccCheckDatabaseExistence(t, id, true), @@ -314,7 +321,7 @@ func TestAcc_UnsafeExecute_invalidRevertStatement(t *testing.T) { { ConfigDirectory: acc.ConfigurationDirectory("TestAcc_UnsafeExecute_commonSetup"), ConfigVariables: map[string]config.Variable{ - "execute": config.StringVariable(createDatabaseStatement(updatedId)), + "execute": config.StringVariable(createDatabaseStatement(updatedName)), "revert": config.StringVariable(invalidDropStatement), }, ConfigPlanChecks: resource.ConfigPlanChecks{ @@ -325,15 +332,15 @@ func TestAcc_UnsafeExecute_invalidRevertStatement(t *testing.T) { { ConfigDirectory: acc.ConfigurationDirectory("TestAcc_UnsafeExecute_commonSetup"), ConfigVariables: map[string]config.Variable{ - "execute": config.StringVariable(createDatabaseStatement(id)), - "revert": config.StringVariable(dropDatabaseStatement(id)), + "execute": config.StringVariable(createDatabaseStatement(name)), + "revert": config.StringVariable(dropDatabaseStatement(name)), }, ConfigPlanChecks: resource.ConfigPlanChecks{ PreApply: []plancheck.PlanCheck{plancheck.ExpectNonEmptyPlan()}, }, Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(resourceName, "execute", createDatabaseStatement(id)), - resource.TestCheckResourceAttr(resourceName, "revert", dropDatabaseStatement(id)), + resource.TestCheckResourceAttr(resourceName, "execute", createDatabaseStatement(name)), + resource.TestCheckResourceAttr(resourceName, "revert", dropDatabaseStatement(name)), resource.TestCheckResourceAttrSet(resourceName, "id"), testAccCheckDatabaseExistence(t, id, true), testAccCheckDatabaseExistence(t, updatedId, false), @@ -342,15 +349,15 @@ func TestAcc_UnsafeExecute_invalidRevertStatement(t *testing.T) { { ConfigDirectory: acc.ConfigurationDirectory("TestAcc_UnsafeExecute_commonSetup"), ConfigVariables: map[string]config.Variable{ - "execute": config.StringVariable(createDatabaseStatement(updatedId)), - "revert": config.StringVariable(dropDatabaseStatement(updatedId)), + "execute": config.StringVariable(createDatabaseStatement(updatedName)), + "revert": config.StringVariable(dropDatabaseStatement(updatedName)), }, ConfigPlanChecks: resource.ConfigPlanChecks{ PreApply: []plancheck.PlanCheck{plancheck.ExpectNonEmptyPlan()}, }, Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(resourceName, "execute", createDatabaseStatement(updatedId)), - resource.TestCheckResourceAttr(resourceName, "revert", dropDatabaseStatement(updatedId)), + resource.TestCheckResourceAttr(resourceName, "execute", createDatabaseStatement(updatedName)), + resource.TestCheckResourceAttr(resourceName, "revert", dropDatabaseStatement(updatedName)), resource.TestCheckResourceAttrSet(resourceName, "id"), testAccCheckDatabaseExistence(t, id, false), testAccCheckDatabaseExistence(t, updatedId, true), @@ -361,9 +368,10 @@ func TestAcc_UnsafeExecute_invalidRevertStatement(t *testing.T) { } func TestAcc_UnsafeExecute_revertUpdated(t *testing.T) { - id := acc.TestClient().Ids.RandomAccountObjectIdentifierWithPrefix("UNSAFE_EXECUTE_TEST_DATABASE_").Name() - execute := fmt.Sprintf("create database %s", id) - revert := fmt.Sprintf("drop database %s", id) + id := acc.TestClient().Ids.RandomAccountObjectIdentifierWithPrefix("UNSAFE_EXECUTE_TEST_DATABASE_") + name := id.Name() + execute := fmt.Sprintf("create database %s", name) + revert := fmt.Sprintf("drop database %s", name) notMatchingRevert := "select 1" var savedId string @@ -424,13 +432,15 @@ func TestAcc_UnsafeExecute_revertUpdated(t *testing.T) { } func TestAcc_UnsafeExecute_executeUpdated(t *testing.T) { - id := acc.TestClient().Ids.RandomAccountObjectIdentifierWithPrefix("UNSAFE_EXECUTE_TEST_DATABASE_").Name() - execute := fmt.Sprintf("create database %s", id) - revert := fmt.Sprintf("drop database %s", id) + id := acc.TestClient().Ids.RandomAccountObjectIdentifierWithPrefix("UNSAFE_EXECUTE_TEST_DATABASE_") + name := id.Name() + execute := fmt.Sprintf("create database %s", name) + revert := fmt.Sprintf("drop database %s", name) - newId := fmt.Sprintf("%s_2", id) - newExecute := fmt.Sprintf("create database %s", newId) - newRevert := fmt.Sprintf("drop database %s", newId) + newId := acc.TestClient().Ids.RandomAccountObjectIdentifierWithPrefix("UNSAFE_EXECUTE_TEST_DATABASE_") + newName := newId.Name() + newExecute := fmt.Sprintf("create database %s", newName) + newRevert := fmt.Sprintf("drop database %s", newName) var savedId string @@ -502,11 +512,11 @@ func TestAcc_UnsafeExecute_executeUpdated(t *testing.T) { } func TestAcc_UnsafeExecute_grants(t *testing.T) { - id := acc.TestClient().Ids.RandomAccountObjectIdentifierWithPrefix("UNSAFE_EXECUTE_TEST_DATABASE_").Name() - roleId := generateUnsafeExecuteTestRoleName(t) + id := acc.TestClient().Ids.RandomAccountObjectIdentifierWithPrefix("UNSAFE_EXECUTE_TEST_DATABASE_") + roleId := acc.TestClient().Ids.RandomAccountObjectIdentifierWithPrefix("UNSAFE_EXECUTE_TEST_ROLE_") privilege := sdk.AccountObjectPrivilegeCreateSchema - execute := fmt.Sprintf("GRANT %s ON DATABASE %s TO ROLE %s", privilege, id, roleId) - revert := fmt.Sprintf("REVOKE %s ON DATABASE %s FROM ROLE %s", privilege, id, roleId) + execute := fmt.Sprintf("GRANT %s ON DATABASE %s TO ROLE %s", privilege, id.Name(), roleId.Name()) + revert := fmt.Sprintf("REVOKE %s ON DATABASE %s FROM ROLE %s", privilege, id.Name(), roleId.Name()) resourceName := "snowflake_unsafe_execute.test" createConfigVariables := func(execute string, revert string) map[string]config.Variable { @@ -560,10 +570,10 @@ func TestAcc_UnsafeExecute_grants(t *testing.T) { func TestAcc_UnsafeExecute_grantsComplex(t *testing.T) { t.Skip("Skipping TestAcc_UnsafeExecute_grantsComplex because of https://github.com/hashicorp/terraform-plugin-sdk/issues/536 issue") - dbId1 := acc.TestClient().Ids.RandomAccountObjectIdentifierWithPrefix("UNSAFE_EXECUTE_TEST_DATABASE_").Name() - dbId2 := acc.TestClient().Ids.RandomAccountObjectIdentifierWithPrefix("UNSAFE_EXECUTE_TEST_DATABASE_").Name() - roleId1 := generateUnsafeExecuteTestRoleName(t) - roleId2 := generateUnsafeExecuteTestRoleName(t) + dbId1 := acc.TestClient().Ids.RandomAccountObjectIdentifierWithPrefix("UNSAFE_EXECUTE_TEST_DATABASE_") + dbId2 := acc.TestClient().Ids.RandomAccountObjectIdentifierWithPrefix("UNSAFE_EXECUTE_TEST_DATABASE_") + roleId1 := acc.TestClient().Ids.RandomAccountObjectIdentifierWithPrefix("UNSAFE_EXECUTE_TEST_ROLE_") + roleId2 := acc.TestClient().Ids.RandomAccountObjectIdentifierWithPrefix("UNSAFE_EXECUTE_TEST_ROLE_") privilege1 := sdk.AccountObjectPrivilegeCreateSchema privilege2 := sdk.AccountObjectPrivilegeModify privilege3 := sdk.AccountObjectPrivilegeUsage @@ -573,12 +583,12 @@ func TestAcc_UnsafeExecute_grantsComplex(t *testing.T) { createConfigVariables := func() map[string]config.Variable { return map[string]config.Variable{ "database_grants": config.ListVariable(config.ObjectVariable(map[string]config.Variable{ - "database_name": config.StringVariable(dbId1), - "role_id": config.StringVariable(roleId1), + "database_name": config.StringVariable(dbId1.Name()), + "role_id": config.StringVariable(roleId1.Name()), "privileges": config.ListVariable(config.StringVariable(privilege1.String()), config.StringVariable(privilege2.String())), }), config.ObjectVariable(map[string]config.Variable{ - "database_name": config.StringVariable(dbId2), - "role_id": config.StringVariable(roleId2), + "database_name": config.StringVariable(dbId2.Name()), + "role_id": config.StringVariable(roleId2.Name()), "privileges": config.ListVariable(config.StringVariable(privilege2.String()), config.StringVariable(privilege3.String())), })), } @@ -693,62 +703,43 @@ output "unsafe" { `, queryNumber) } -// generateUnsafeExecuteTestRoleName returns capitalized name on purpose. -// Using small caps without escaping creates problem with later using sdk client which uses identifier that is escaped by default. -func generateUnsafeExecuteTestRoleName(t *testing.T) string { - t.Helper() - id, err := rand.Int(rand.Reader, big.NewInt(10000)) - if err != nil { - t.Fatalf("Failed to generate role id: %v", err) - } - return fmt.Sprintf("UNSAFE_EXECUTE_TEST_ROLE_%d", id) -} - -func createResourcesForExecuteUnsafeTestCaseForGrants(t *testing.T, dbId string, roleId string) { +func createResourcesForExecuteUnsafeTestCaseForGrants(t *testing.T, dbId sdk.AccountObjectIdentifier, roleId sdk.AccountObjectIdentifier) { t.Helper() client := acc.Client(t) ctx := context.Background() - err := client.Databases.Create(ctx, sdk.NewAccountObjectIdentifier(dbId), &sdk.CreateDatabaseOptions{}) + err := client.Databases.Create(ctx, dbId, &sdk.CreateDatabaseOptions{}) require.NoError(t, err) - err = client.Roles.Create(ctx, sdk.NewCreateRoleRequest(sdk.NewAccountObjectIdentifier(roleId))) + err = client.Roles.Create(ctx, sdk.NewCreateRoleRequest(roleId)) require.NoError(t, err) } -func dropResourcesForUnsafeExecuteTestCaseForGrants(t *testing.T, dbId string, roleId string) { +func dropResourcesForUnsafeExecuteTestCaseForGrants(t *testing.T, dbId sdk.AccountObjectIdentifier, roleId sdk.AccountObjectIdentifier) { t.Helper() client := acc.Client(t) ctx := context.Background() - err := client.Databases.Drop(ctx, sdk.NewAccountObjectIdentifier(dbId), &sdk.DropDatabaseOptions{}) + err := client.Databases.Drop(ctx, dbId, &sdk.DropDatabaseOptions{}) assert.NoError(t, err) - err = client.Roles.Drop(ctx, sdk.NewDropRoleRequest(sdk.NewAccountObjectIdentifier(roleId))) + err = client.Roles.Drop(ctx, sdk.NewDropRoleRequest(roleId)) assert.NoError(t, err) } -func verifyGrantExists(t *testing.T, roleId string, privilege sdk.AccountObjectPrivilege, shouldExist bool) func(state *terraform.State) error { +func verifyGrantExists(t *testing.T, roleId sdk.AccountObjectIdentifier, privilege sdk.AccountObjectPrivilege, shouldExist bool) func(state *terraform.State) error { t.Helper() return func(state *terraform.State) error { - client := acc.Client(t) - ctx := context.Background() - - grants, err := client.Grants.Show(ctx, &sdk.ShowGrantOptions{ - To: &sdk.ShowGrantsTo{ - Role: sdk.NewAccountObjectIdentifier(roleId), - }, - }) - require.NoError(t, err) + grants := acc.TestClient().Role.ShowGrantsTo(t, roleId) if shouldExist { require.Equal(t, 1, len(grants)) assert.Equal(t, privilege.String(), grants[0].Privilege) assert.Equal(t, sdk.ObjectTypeDatabase, grants[0].GrantedOn) assert.Equal(t, sdk.ObjectTypeRole, grants[0].GrantedTo) - assert.Equal(t, sdk.NewAccountObjectIdentifier(roleId).FullyQualifiedName(), grants[0].GranteeName.FullyQualifiedName()) + assert.Equal(t, roleId.FullyQualifiedName(), grants[0].GranteeName.FullyQualifiedName()) } else { require.Equal(t, 0, len(grants)) } diff --git a/pkg/resources/user_password_policy_attachment_acceptance_test.go b/pkg/resources/user_password_policy_attachment_acceptance_test.go index ee89ecbcfe..82879446fd 100644 --- a/pkg/resources/user_password_policy_attachment_acceptance_test.go +++ b/pkg/resources/user_password_policy_attachment_acceptance_test.go @@ -6,17 +6,20 @@ import ( acc "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance" - "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func TestAcc_UserPasswordPolicyAttachment(t *testing.T) { // TODO [SNOW-1423486]: unskip t.Skipf("Skip because error %s; will be fixed in SNOW-1423486", "Error: 000606 (57P03): No active warehouse selected in the current session. Select an active warehouse with the 'use warehouse' command.") - userName := acc.TestClient().Ids.Alpha() - NewUserName := acc.TestClient().Ids.Alpha() - passwordPolicyName := acc.TestClient().Ids.Alpha() - newPasswordPolicyName := acc.TestClient().Ids.Alpha() + userId := acc.TestClient().Ids.RandomAccountObjectIdentifier() + userName := userId.Name() + newUserId := acc.TestClient().Ids.RandomAccountObjectIdentifier() + newUserName := newUserId.Name() + passwordPolicyId := acc.TestClient().Ids.RandomSchemaObjectIdentifier() + passwordPolicyName := passwordPolicyId.Name() + newPasswordPolicyId := acc.TestClient().Ids.RandomSchemaObjectIdentifier() + newPasswordPolicyName := newPasswordPolicyId.Name() resource.Test(t, resource.TestCase{ ProtoV6ProviderFactories: acc.TestAccProtoV6ProviderFactories, @@ -28,17 +31,17 @@ func TestAcc_UserPasswordPolicyAttachment(t *testing.T) { Config: userPasswordPolicyAttachmentConfig(userName, acc.TestDatabaseName, acc.TestSchemaName, passwordPolicyName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("snowflake_user_password_policy_attachment.ppa", "user_name", userName), - resource.TestCheckResourceAttr("snowflake_user_password_policy_attachment.ppa", "password_policy_name", sdk.NewSchemaObjectIdentifier(acc.TestDatabaseName, acc.TestSchemaName, passwordPolicyName).FullyQualifiedName()), - resource.TestCheckResourceAttr("snowflake_user_password_policy_attachment.ppa", "id", fmt.Sprintf("%s|%s", sdk.NewAccountObjectIdentifier(userName).FullyQualifiedName(), sdk.NewSchemaObjectIdentifier(acc.TestDatabaseName, acc.TestSchemaName, passwordPolicyName).FullyQualifiedName())), + resource.TestCheckResourceAttr("snowflake_user_password_policy_attachment.ppa", "password_policy_name", passwordPolicyId.FullyQualifiedName()), + resource.TestCheckResourceAttr("snowflake_user_password_policy_attachment.ppa", "id", fmt.Sprintf("%s|%s", userId.FullyQualifiedName(), passwordPolicyId.FullyQualifiedName())), ), }, // UPDATE { - Config: userPasswordPolicyAttachmentConfig(NewUserName, acc.TestDatabaseName, acc.TestSchemaName, newPasswordPolicyName), + Config: userPasswordPolicyAttachmentConfig(newUserName, acc.TestDatabaseName, acc.TestSchemaName, newPasswordPolicyName), Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("snowflake_user_password_policy_attachment.ppa", "user_name", NewUserName), - resource.TestCheckResourceAttr("snowflake_user_password_policy_attachment.ppa", "password_policy_name", sdk.NewSchemaObjectIdentifier(acc.TestDatabaseName, acc.TestSchemaName, newPasswordPolicyName).FullyQualifiedName()), - resource.TestCheckResourceAttr("snowflake_user_password_policy_attachment.ppa", "id", fmt.Sprintf("%s|%s", sdk.NewAccountObjectIdentifier(NewUserName).FullyQualifiedName(), sdk.NewSchemaObjectIdentifier(acc.TestDatabaseName, acc.TestSchemaName, newPasswordPolicyName).FullyQualifiedName())), + resource.TestCheckResourceAttr("snowflake_user_password_policy_attachment.ppa", "user_name", newUserName), + resource.TestCheckResourceAttr("snowflake_user_password_policy_attachment.ppa", "password_policy_name", newPasswordPolicyId.FullyQualifiedName()), + resource.TestCheckResourceAttr("snowflake_user_password_policy_attachment.ppa", "id", fmt.Sprintf("%s|%s", userId.FullyQualifiedName(), newPasswordPolicyId.FullyQualifiedName())), ), }, // IMPORT diff --git a/pkg/resources/user_public_keys.go b/pkg/resources/user_public_keys.go index 7c6001f158..6f97a1e9a6 100644 --- a/pkg/resources/user_public_keys.go +++ b/pkg/resources/user_public_keys.go @@ -8,8 +8,8 @@ import ( "log" "strings" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/helpers" "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/internal/provider" - "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk" "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/snowflake" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -63,14 +63,13 @@ func UserPublicKeys() *schema.Resource { } } -func checkUserExists(db *sql.DB, name string) (bool, error) { +func checkUserExists(client *sdk.Client, userId sdk.AccountObjectIdentifier) (bool, error) { ctx := context.Background() - client := sdk.NewClientFromDB(db) // First check if user exists - _, err := client.Users.Describe(ctx, sdk.NewAccountObjectIdentifier(name)) + _, err := client.Users.Describe(ctx, userId) if errors.Is(err, sdk.ErrObjectNotExistOrAuthorized) { - log.Printf("[DEBUG] user (%s) not found", name) + log.Printf("[DEBUG] user (%s) not found", userId.Name()) return false, nil } if err != nil { @@ -82,10 +81,9 @@ func checkUserExists(db *sql.DB, name string) (bool, error) { func ReadUserPublicKeys(d *schema.ResourceData, meta interface{}) error { client := meta.(*provider.Context).Client - db := client.GetConn().DB - id := d.Id() + id := helpers.DecodeSnowflakeID(d.Id()).(sdk.AccountObjectIdentifier) - exists, err := checkUserExists(db, id) + exists, err := checkUserExists(client, id) if err != nil { return err } diff --git a/pkg/resources/view.go b/pkg/resources/view.go index c8197a4d59..7d1e6c7233 100644 --- a/pkg/resources/view.go +++ b/pkg/resources/view.go @@ -222,7 +222,7 @@ func UpdateView(d *schema.ResourceData, meta interface{}) error { } if d.HasChange("name") { - newId := sdk.NewSchemaObjectIdentifier(id.DatabaseName(), id.SchemaName(), d.Get("name").(string)) + newId := sdk.NewSchemaObjectIdentifierInSchema(id.SchemaId(), d.Get("name").(string)) err := client.Views.Alter(ctx, sdk.NewAlterViewRequest(id).WithRenameTo(&newId)) if err != nil { diff --git a/pkg/resources/view_acceptance_test.go b/pkg/resources/view_acceptance_test.go index d535479cd2..a2a4baa8d6 100644 --- a/pkg/resources/view_acceptance_test.go +++ b/pkg/resources/view_acceptance_test.go @@ -1,25 +1,24 @@ package resources_test import ( - "context" "fmt" "regexp" "testing" - "github.com/hashicorp/terraform-plugin-testing/plancheck" - acc "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/internal/snowflakeroles" "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/provider/resources" "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk" "github.com/hashicorp/terraform-plugin-testing/config" "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-plugin-testing/tfversion" - "github.com/stretchr/testify/require" ) func TestAcc_View(t *testing.T) { - accName := acc.TestClient().Ids.Alpha() + viewId := acc.TestClient().Ids.RandomSchemaObjectIdentifier() + accName := viewId.Name() query := "SELECT ROLE_NAME, ROLE_OWNER FROM INFORMATION_SCHEMA.APPLICABLE_ROLES" otherQuery := "SELECT ROLE_NAME, ROLE_OWNER FROM INFORMATION_SCHEMA.APPLICABLE_ROLES where ROLE_OWNER like 'foo%%'" @@ -96,7 +95,7 @@ func TestAcc_View(t *testing.T) { // change statement externally { PreConfig: func() { - alterViewQueryExternally(t, sdk.NewSchemaObjectIdentifier(acc.TestDatabaseName, acc.TestSchemaName, accName), query) + acc.TestClient().View.RecreateView(t, viewId, query) }, ConfigDirectory: acc.ConfigurationDirectory("TestAcc_View_basic"), ConfigVariables: m3, @@ -419,7 +418,8 @@ func TestAcc_View_copyGrants(t *testing.T) { } func TestAcc_View_Issue2640(t *testing.T) { - viewName := acc.TestClient().Ids.Alpha() + viewId := acc.TestClient().Ids.RandomSchemaObjectIdentifier() + viewName := viewId.Name() part1 := "SELECT ROLE_NAME, ROLE_OWNER FROM INFORMATION_SCHEMA.APPLICABLE_ROLES" part2 := "SELECT ROLE_OWNER, ROLE_NAME FROM INFORMATION_SCHEMA.APPLICABLE_ROLES" roleName := acc.TestClient().Ids.Alpha() @@ -444,9 +444,9 @@ func TestAcc_View_Issue2640(t *testing.T) { // try to import secure view without being its owner (proves https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2640) { PreConfig: func() { - _, roleCleanup := acc.TestClient().Role.CreateRoleWithName(t, roleName) + role, roleCleanup := acc.TestClient().Role.CreateRoleWithName(t, roleName) t.Cleanup(roleCleanup) - alterViewOwnershipExternally(t, viewName, roleName) + acc.TestClient().Role.GrantOwnershipOnSchemaObject(t, role.ID(), viewId, sdk.ObjectTypeView, sdk.Revoke) }, ResourceName: "snowflake_view.test", ImportState: true, @@ -455,7 +455,7 @@ func TestAcc_View_Issue2640(t *testing.T) { // import with the proper role { PreConfig: func() { - alterViewOwnershipExternally(t, viewName, "ACCOUNTADMIN") + acc.TestClient().Role.GrantOwnershipOnSchemaObject(t, snowflakeroles.Accountadmin, viewId, sdk.ObjectTypeView, sdk.Revoke) }, ResourceName: "snowflake_view.test", ImportState: true, @@ -566,38 +566,3 @@ SQL } `, databaseName, schemaName, name, part1, part2) } - -func alterViewQueryExternally(t *testing.T, id sdk.SchemaObjectIdentifier, query string) { - t.Helper() - - client := acc.Client(t) - ctx := context.Background() - - err := client.Views.Create(ctx, sdk.NewCreateViewRequest(id, query).WithOrReplace(sdk.Bool(true))) - require.NoError(t, err) -} - -func alterViewOwnershipExternally(t *testing.T, viewName string, roleName string) { - t.Helper() - - viewId := sdk.NewSchemaObjectIdentifier(acc.TestDatabaseName, acc.TestSchemaName, viewName) - roleId := sdk.NewAccountObjectIdentifier(roleName) - - client := acc.Client(t) - ctx := context.Background() - - on := sdk.OwnershipGrantOn{ - Object: &sdk.Object{ - ObjectType: sdk.ObjectTypeView, - Name: viewId, - }, - } - to := sdk.OwnershipGrantTo{ - AccountRoleName: &roleId, - } - currentGrants := sdk.OwnershipCurrentGrants{ - OutboundPrivileges: sdk.Revoke, - } - err := client.Grants.GrantOwnership(ctx, on, to, &sdk.GrantOwnershipOptions{CurrentGrants: ¤tGrants}) - require.NoError(t, err) -} diff --git a/pkg/resources/view_grant_acceptance_test.go b/pkg/resources/view_grant_acceptance_test.go index 2df7b5a6b4..fb21ddddbd 100644 --- a/pkg/resources/view_grant_acceptance_test.go +++ b/pkg/resources/view_grant_acceptance_test.go @@ -183,7 +183,7 @@ func viewGrantConfig(name string, grantType grantType, privilege string, databas var viewNameConfig string switch grantType { case normal: - viewNameConfig = "view_name = snowflake_view.test.name" + viewNameConfig = "view_name = \"${snowflake_view.test.name}\"" case onFuture: viewNameConfig = "on_future = true" case onAll: diff --git a/pkg/sdk/alerts_test.go b/pkg/sdk/alerts_test.go index e9c4040f2c..a7183eae2f 100644 --- a/pkg/sdk/alerts_test.go +++ b/pkg/sdk/alerts_test.go @@ -173,16 +173,15 @@ func TestAlertShow(t *testing.T) { }) t.Run("with like and in database", func(t *testing.T) { - databaseIdentifier := NewAccountObjectIdentifier(id.DatabaseName()) opts := &ShowAlertOptions{ Like: &Like{ Pattern: String(id.Name()), }, In: &In{ - Database: databaseIdentifier, + Database: id.DatabaseId(), }, } - assertOptsValidAndSQLEquals(t, opts, "SHOW ALERTS LIKE '%s' IN DATABASE %s", id.Name(), databaseIdentifier.FullyQualifiedName()) + assertOptsValidAndSQLEquals(t, opts, "SHOW ALERTS LIKE '%s' IN DATABASE %s", id.Name(), id.DatabaseId().FullyQualifiedName()) }) t.Run("with like and in schema", func(t *testing.T) { diff --git a/pkg/sdk/api_integrations_gen_test.go b/pkg/sdk/api_integrations_gen_test.go index e6f24eeb76..9d8618910c 100644 --- a/pkg/sdk/api_integrations_gen_test.go +++ b/pkg/sdk/api_integrations_gen_test.go @@ -63,7 +63,7 @@ func TestApiIntegrations_Create(t *testing.T) { t.Run("validation: valid identifier for [opts.name]", func(t *testing.T) { opts := defaultOpts() - opts.name = NewAccountObjectIdentifier("") + opts.name = emptyAccountObjectIdentifier assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) @@ -139,7 +139,7 @@ func TestApiIntegrations_Alter(t *testing.T) { t.Run("validation: valid identifier for [opts.name]", func(t *testing.T) { opts := defaultOpts() - opts.name = NewAccountObjectIdentifier("") + opts.name = emptyAccountObjectIdentifier assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) @@ -319,7 +319,7 @@ func TestApiIntegrations_Drop(t *testing.T) { t.Run("validation: valid identifier for [opts.name]", func(t *testing.T) { opts := defaultOpts() - opts.name = NewAccountObjectIdentifier("") + opts.name = emptyAccountObjectIdentifier assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) @@ -374,7 +374,7 @@ func TestApiIntegrations_Describe(t *testing.T) { t.Run("validation: valid identifier for [opts.name]", func(t *testing.T) { opts := defaultOpts() - opts.name = NewAccountObjectIdentifier("") + opts.name = emptyAccountObjectIdentifier assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) diff --git a/pkg/sdk/application_packages_gen_test.go b/pkg/sdk/application_packages_gen_test.go index bbefe0a49c..c0ff080156 100644 --- a/pkg/sdk/application_packages_gen_test.go +++ b/pkg/sdk/application_packages_gen_test.go @@ -18,7 +18,7 @@ func TestApplicationPackages_Create(t *testing.T) { t.Run("validation: incorrect identifier", func(t *testing.T) { opts := defaultOpts() - opts.name = NewAccountObjectIdentifier("") + opts.name = emptyAccountObjectIdentifier assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) @@ -58,7 +58,7 @@ func TestApplicationPackages_Alter(t *testing.T) { t.Run("validation: incorrect identifier", func(t *testing.T) { opts := defaultOpts() - opts.name = NewAccountObjectIdentifier("") + opts.name = emptyAccountObjectIdentifier assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) @@ -225,7 +225,7 @@ func TestApplicationPackages_Drop(t *testing.T) { t.Run("validation: incorrect identifier", func(t *testing.T) { opts := defaultOpts() - opts.name = NewAccountObjectIdentifier("") + opts.name = emptyAccountObjectIdentifier assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) diff --git a/pkg/sdk/application_roles_gen.go b/pkg/sdk/application_roles_gen.go index a05ad5a65b..6574e5f73c 100644 --- a/pkg/sdk/application_roles_gen.go +++ b/pkg/sdk/application_roles_gen.go @@ -15,7 +15,7 @@ type ApplicationRoles interface { Grant(ctx context.Context, request *GrantApplicationRoleRequest) error Revoke(ctx context.Context, request *RevokeApplicationRoleRequest) error Show(ctx context.Context, request *ShowApplicationRoleRequest) ([]ApplicationRole, error) - ShowByID(ctx context.Context, applicationName AccountObjectIdentifier, id DatabaseObjectIdentifier) (*ApplicationRole, error) + ShowByID(ctx context.Context, id DatabaseObjectIdentifier) (*ApplicationRole, error) } // GrantApplicationRoleOptions is based on https://docs.snowflake.com/en/sql-reference/sql/grant-application-role. diff --git a/pkg/sdk/application_roles_gen_test.go b/pkg/sdk/application_roles_gen_test.go index e4f466eaea..65f1b86b4b 100644 --- a/pkg/sdk/application_roles_gen_test.go +++ b/pkg/sdk/application_roles_gen_test.go @@ -126,7 +126,7 @@ func TestApplicationRoles_Show(t *testing.T) { t.Run("validation: valid identifier for [opts.ApplicationName]", func(t *testing.T) { opts := defaultOpts() - opts.ApplicationName = NewAccountObjectIdentifier("") + opts.ApplicationName = emptyAccountObjectIdentifier assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) diff --git a/pkg/sdk/application_roles_impl_gen.go b/pkg/sdk/application_roles_impl_gen.go index 31c304fe38..c173ccbfe8 100644 --- a/pkg/sdk/application_roles_impl_gen.go +++ b/pkg/sdk/application_roles_impl_gen.go @@ -32,8 +32,8 @@ func (v *applicationRoles) Show(ctx context.Context, request *ShowApplicationRol return resultList, nil } -func (v *applicationRoles) ShowByID(ctx context.Context, applicationName AccountObjectIdentifier, id DatabaseObjectIdentifier) (*ApplicationRole, error) { - request := NewShowApplicationRoleRequest().WithApplicationName(applicationName) +func (v *applicationRoles) ShowByID(ctx context.Context, id DatabaseObjectIdentifier) (*ApplicationRole, error) { + request := NewShowApplicationRoleRequest().WithApplicationName(id.DatabaseId()) applicationRoles, err := v.Show(ctx, request) if err != nil { return nil, err diff --git a/pkg/sdk/applications_gen_test.go b/pkg/sdk/applications_gen_test.go index 4da7597560..96ecbb1888 100644 --- a/pkg/sdk/applications_gen_test.go +++ b/pkg/sdk/applications_gen_test.go @@ -24,7 +24,7 @@ func TestApplications_Create(t *testing.T) { t.Run("validation: incorrect identifier", func(t *testing.T) { opts := defaultOpts() - opts.name = NewAccountObjectIdentifier("") + opts.name = emptyAccountObjectIdentifier assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) @@ -108,7 +108,7 @@ func TestApplications_Alter(t *testing.T) { t.Run("validation: incorrect identifier", func(t *testing.T) { opts := defaultOpts() - opts.name = NewAccountObjectIdentifier("") + opts.name = emptyAccountObjectIdentifier assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) @@ -244,7 +244,7 @@ func TestApplications_Drop(t *testing.T) { t.Run("validation: incorrect identifier", func(t *testing.T) { opts := defaultOpts() - opts.name = NewAccountObjectIdentifier("") + opts.name = emptyAccountObjectIdentifier assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) @@ -272,7 +272,7 @@ func TestApplications_Describe(t *testing.T) { t.Run("validation: incorrect identifier", func(t *testing.T) { opts := defaultOpts() - opts.name = NewAccountObjectIdentifier("") + opts.name = emptyAccountObjectIdentifier assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) diff --git a/pkg/sdk/context_functions.go b/pkg/sdk/context_functions.go index 714f3fbf7d..b21d69d862 100644 --- a/pkg/sdk/context_functions.go +++ b/pkg/sdk/context_functions.go @@ -12,11 +12,11 @@ import ( type ContextFunctions interface { // Session functions. CurrentAccount(ctx context.Context) (string, error) - CurrentRole(ctx context.Context) (string, error) + CurrentRole(ctx context.Context) (AccountObjectIdentifier, error) CurrentSecondaryRoles(ctx context.Context) (*CurrentSecondaryRoles, error) CurrentRegion(ctx context.Context) (string, error) CurrentSession(ctx context.Context) (string, error) - CurrentUser(ctx context.Context) (string, error) + CurrentUser(ctx context.Context) (AccountObjectIdentifier, error) CurrentSessionDetails(ctx context.Context) (*CurrentSessionDetails, error) // Session Object functions. @@ -70,15 +70,15 @@ func (c *contextFunctions) CurrentAccount(ctx context.Context) (string, error) { return s.CurrentAccount, nil } -func (c *contextFunctions) CurrentRole(ctx context.Context) (string, error) { +func (c *contextFunctions) CurrentRole(ctx context.Context) (AccountObjectIdentifier, error) { s := &struct { CurrentRole string `db:"CURRENT_ROLE"` }{} err := c.client.queryOne(ctx, s, "SELECT CURRENT_ROLE() as CURRENT_ROLE") if err != nil { - return "", err + return NewAccountObjectIdentifier(""), err } - return s.CurrentRole, nil + return NewAccountObjectIdentifier(s.CurrentRole), nil } type CurrentSecondaryRoles struct { @@ -148,15 +148,15 @@ func (c *contextFunctions) CurrentSession(ctx context.Context) (string, error) { return s.CurrentSession, nil } -func (c *contextFunctions) CurrentUser(ctx context.Context) (string, error) { +func (c *contextFunctions) CurrentUser(ctx context.Context) (AccountObjectIdentifier, error) { s := &struct { CurrentUser string `db:"CURRENT_USER"` }{} err := c.client.queryOne(ctx, s, "SELECT CURRENT_USER() as CURRENT_USER") if err != nil { - return "", err + return NewAccountObjectIdentifier(""), err } - return s.CurrentUser, nil + return NewAccountObjectIdentifier(s.CurrentUser), nil } func (c *contextFunctions) CurrentSessionDetails(ctx context.Context) (*CurrentSessionDetails, error) { diff --git a/pkg/sdk/database_role_impl.go b/pkg/sdk/database_role_impl.go index 7876bc63bf..72f8320965 100644 --- a/pkg/sdk/database_role_impl.go +++ b/pkg/sdk/database_role_impl.go @@ -40,7 +40,7 @@ func (v *databaseRoles) Show(ctx context.Context, request *ShowDatabaseRoleReque } func (v *databaseRoles) ShowByID(ctx context.Context, id DatabaseObjectIdentifier) (*DatabaseRole, error) { - request := NewShowDatabaseRoleRequest(NewAccountObjectIdentifier(id.DatabaseName())).WithLike(id.Name()) + request := NewShowDatabaseRoleRequest(id.DatabaseId()).WithLike(id.Name()) databaseRoles, err := v.Show(ctx, request) if err != nil { return nil, err diff --git a/pkg/sdk/database_role_test.go b/pkg/sdk/database_role_test.go index 81eceaa2c8..695a060ab0 100644 --- a/pkg/sdk/database_role_test.go +++ b/pkg/sdk/database_role_test.go @@ -203,7 +203,7 @@ func TestDatabaseRolesShow(t *testing.T) { t.Run("validation: incorrect identifier", func(t *testing.T) { opts := defaultOpts() - opts.Database = NewAccountObjectIdentifier("") + opts.Database = emptyAccountObjectIdentifier assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) @@ -349,7 +349,7 @@ func TestDatabaseRoles_GrantToShare(t *testing.T) { t.Run("validation: invalid share identifier", func(t *testing.T) { opts := setUpOpts() - opts.Share = NewAccountObjectIdentifier("") + opts.Share = emptyAccountObjectIdentifier assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) @@ -384,7 +384,7 @@ func TestDatabaseRoles_RevokeFromShare(t *testing.T) { t.Run("validation: invalid share identifier", func(t *testing.T) { opts := setUpOpts() - opts.Share = NewAccountObjectIdentifier("") + opts.Share = emptyAccountObjectIdentifier assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) diff --git a/pkg/sdk/external_functions_gen_test.go b/pkg/sdk/external_functions_gen_test.go index 5fc3921751..f4bfd77691 100644 --- a/pkg/sdk/external_functions_gen_test.go +++ b/pkg/sdk/external_functions_gen_test.go @@ -32,7 +32,7 @@ func TestExternalFunctions_Create(t *testing.T) { opts = defaultOpts() opts.As = "as" - integration := NewAccountObjectIdentifier("") + integration := emptyAccountObjectIdentifier opts.ApiIntegration = &integration rt := NewSchemaObjectIdentifier("", "", "") opts.RequestTranslator = &rt diff --git a/pkg/sdk/grants_impl.go b/pkg/sdk/grants_impl.go index 1058c2a29e..1be95f66c7 100644 --- a/pkg/sdk/grants_impl.go +++ b/pkg/sdk/grants_impl.go @@ -282,7 +282,6 @@ func (v *grants) grantOwnershipOnPipe(ctx context.Context, pipeId SchemaObjectId if err != nil { return err } - currentRoleName := NewAccountObjectIdentifier(currentRole) currentGrants, err := v.client.Grants.Show(ctx, &ShowGrantOptions{ On: &ShowGrantsOn{ @@ -298,7 +297,7 @@ func (v *grants) grantOwnershipOnPipe(ctx context.Context, pipeId SchemaObjectId isGrantedWithPrivilege := func(privilege string) bool { return slices.ContainsFunc(currentGrants, func(grant Grant) bool { - return grant.GranteeName == currentRoleName && + return grant.GranteeName == currentRole && grant.GrantedOn == ObjectTypePipe && grant.Privilege == privilege }) @@ -377,7 +376,6 @@ func (v *grants) grantOwnershipOnTask(ctx context.Context, taskId SchemaObjectId if err != nil { return err } - currentRoleName := NewAccountObjectIdentifier(currentRole) currentTask, err := v.client.Tasks.ShowByID(ctx, taskId) if err != nil { @@ -398,7 +396,7 @@ func (v *grants) grantOwnershipOnTask(ctx context.Context, taskId SchemaObjectId isGrantedWithPrivilege := func(collection []Grant, grantedOn ObjectType, privilege string) bool { return slices.ContainsFunc(collection, func(grant Grant) bool { - return grant.GranteeName == currentRoleName && + return grant.GranteeName == currentRole && grant.GrantedOn == grantedOn && grant.Privilege == privilege }) @@ -407,7 +405,7 @@ func (v *grants) grantOwnershipOnTask(ctx context.Context, taskId SchemaObjectId isGrantedWithWarehouseUsage := isGrantedWithPrivilege(currentGrantsOnTaskWarehouse, ObjectTypeWarehouse, AccountObjectPrivilegeUsage.String()) canSuspendTask := canOperateOnTask || isGrantedWithPrivilege(currentGrantsOnObject, ObjectTypeTask, "OWNERSHIP") canResumeTask := isGrantedWithWarehouseUsage && canOperateOnTask && isGrantedWithPrivilege(currentGrantsOnAccount, ObjectTypeAccount, GlobalPrivilegeExecuteTask.String()) - canResumeTaskAfterOwnershipTransfer := canResumeTask && ((opts.CurrentGrants != nil && opts.CurrentGrants.OutboundPrivileges == Copy) || (opts.To.AccountRoleName != nil && opts.To.AccountRoleName.Name() == currentRoleName.Name())) + canResumeTaskAfterOwnershipTransfer := canResumeTask && ((opts.CurrentGrants != nil && opts.CurrentGrants.OutboundPrivileges == Copy) || (opts.To.AccountRoleName != nil && opts.To.AccountRoleName.Name() == currentRole.Name())) var tasksToResume []SchemaObjectIdentifier if canSuspendTask { diff --git a/pkg/sdk/identifier_helpers.go b/pkg/sdk/identifier_helpers.go index ff8e9ce0a5..056fda4c5b 100644 --- a/pkg/sdk/identifier_helpers.go +++ b/pkg/sdk/identifier_helpers.go @@ -201,6 +201,10 @@ func (i DatabaseObjectIdentifier) DatabaseName() string { return i.databaseName } +func (i DatabaseObjectIdentifier) DatabaseId() AccountObjectIdentifier { + return NewAccountObjectIdentifier(i.databaseName) +} + func (i DatabaseObjectIdentifier) Name() string { return i.name } @@ -219,6 +223,10 @@ type SchemaObjectIdentifier struct { arguments []DataType } +func NewSchemaObjectIdentifierInSchema(schemaId DatabaseObjectIdentifier, name string) SchemaObjectIdentifier { + return NewSchemaObjectIdentifier(schemaId.DatabaseName(), schemaId.Name(), name) +} + func NewSchemaObjectIdentifier(databaseName, schemaName, name string) SchemaObjectIdentifier { return SchemaObjectIdentifier{ databaseName: strings.Trim(databaseName, `"`), @@ -278,10 +286,14 @@ func (i SchemaObjectIdentifier) Arguments() []DataType { return i.arguments } -func (i SchemaObjectIdentifier) SchemaIdentifier() DatabaseObjectIdentifier { +func (i SchemaObjectIdentifier) SchemaId() DatabaseObjectIdentifier { return NewDatabaseObjectIdentifier(i.databaseName, i.schemaName) } +func (i SchemaObjectIdentifier) DatabaseId() AccountObjectIdentifier { + return NewAccountObjectIdentifier(i.databaseName) +} + func (i SchemaObjectIdentifier) FullyQualifiedName() string { if i.schemaName == "" && i.databaseName == "" && i.name == "" { return "" diff --git a/pkg/sdk/managed_accounts_gen_test.go b/pkg/sdk/managed_accounts_gen_test.go index 9d6c441366..c668a359a3 100644 --- a/pkg/sdk/managed_accounts_gen_test.go +++ b/pkg/sdk/managed_accounts_gen_test.go @@ -23,7 +23,7 @@ func TestManagedAccounts_Create(t *testing.T) { t.Run("validation: valid identifier for [opts.name]", func(t *testing.T) { opts := defaultOpts() - opts.name = NewAccountObjectIdentifier("") + opts.name = emptyAccountObjectIdentifier assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) @@ -68,7 +68,7 @@ func TestManagedAccounts_Drop(t *testing.T) { t.Run("validation: valid identifier for [opts.name]", func(t *testing.T) { opts := defaultOpts() - opts.name = NewAccountObjectIdentifier("") + opts.name = emptyAccountObjectIdentifier assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) diff --git a/pkg/sdk/network_policies_gen_test.go b/pkg/sdk/network_policies_gen_test.go index ddc0dec04d..4d87d79902 100644 --- a/pkg/sdk/network_policies_gen_test.go +++ b/pkg/sdk/network_policies_gen_test.go @@ -29,7 +29,7 @@ func TestNetworkPolicies_Create(t *testing.T) { t.Run("validation: valid identifier for [opts.name]", func(t *testing.T) { opts := defaultOpts() - opts.name = NewAccountObjectIdentifier("") + opts.name = emptyAccountObjectIdentifier assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) @@ -57,7 +57,7 @@ func TestNetworkPolicies_Alter(t *testing.T) { t.Run("validation: valid identifier for [opts.name]", func(t *testing.T) { opts := defaultOpts() - opts.name = NewAccountObjectIdentifier("") + opts.name = emptyAccountObjectIdentifier assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) @@ -255,7 +255,7 @@ func TestNetworkPolicies_Drop(t *testing.T) { t.Run("validation: valid identifier for [opts.name]", func(t *testing.T) { opts := defaultOpts() - opts.name = NewAccountObjectIdentifier("") + opts.name = emptyAccountObjectIdentifier assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) @@ -300,7 +300,7 @@ func TestNetworkPolicies_Describe(t *testing.T) { t.Run("validation: valid identifier for [opts.name]", func(t *testing.T) { opts := defaultOpts() - opts.name = NewAccountObjectIdentifier("") + opts.name = emptyAccountObjectIdentifier assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) diff --git a/pkg/sdk/notification_integrations_gen_test.go b/pkg/sdk/notification_integrations_gen_test.go index 6754dca05e..7a71f2aea4 100644 --- a/pkg/sdk/notification_integrations_gen_test.go +++ b/pkg/sdk/notification_integrations_gen_test.go @@ -58,7 +58,7 @@ func TestNotificationIntegrations_Create(t *testing.T) { t.Run("validation: valid identifier for [opts.name]", func(t *testing.T) { opts := defaultOpts() - opts.name = NewAccountObjectIdentifier("") + opts.name = emptyAccountObjectIdentifier assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) @@ -191,7 +191,7 @@ func TestNotificationIntegrations_Alter(t *testing.T) { t.Run("validation: valid identifier for [opts.name]", func(t *testing.T) { opts := defaultOpts() - opts.name = NewAccountObjectIdentifier("") + opts.name = emptyAccountObjectIdentifier assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) @@ -389,7 +389,7 @@ func TestNotificationIntegrations_Drop(t *testing.T) { t.Run("validation: valid identifier for [opts.name]", func(t *testing.T) { opts := defaultOpts() - opts.name = NewAccountObjectIdentifier("") + opts.name = emptyAccountObjectIdentifier assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) @@ -444,7 +444,7 @@ func TestNotificationIntegrations_Describe(t *testing.T) { t.Run("validation: valid identifier for [opts.name]", func(t *testing.T) { opts := defaultOpts() - opts.name = NewAccountObjectIdentifier("") + opts.name = emptyAccountObjectIdentifier assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) diff --git a/pkg/sdk/pipes_impl.go b/pkg/sdk/pipes_impl.go index b29c4c20a6..5dd0627182 100644 --- a/pkg/sdk/pipes_impl.go +++ b/pkg/sdk/pipes_impl.go @@ -48,7 +48,7 @@ func (v *pipes) ShowByID(ctx context.Context, id SchemaObjectIdentifier) (*Pipe, Pattern: String(id.Name()), }, In: &In{ - Schema: id.SchemaIdentifier(), + Schema: id.SchemaId(), }, }) if err != nil { diff --git a/pkg/sdk/procedures_gen_test.go b/pkg/sdk/procedures_gen_test.go index f6acd11cae..bbd7e85a07 100644 --- a/pkg/sdk/procedures_gen_test.go +++ b/pkg/sdk/procedures_gen_test.go @@ -649,7 +649,7 @@ func TestProcedures_CreateAndCallForJava(t *testing.T) { t.Run("validation: incorrect identifier", func(t *testing.T) { opts := defaultOpts() - opts.Name = NewAccountObjectIdentifier("") + opts.Name = emptyAccountObjectIdentifier assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) @@ -770,7 +770,7 @@ func TestProcedures_CreateAndCallForScala(t *testing.T) { t.Run("validation: incorrect identifier", func(t *testing.T) { opts := defaultOpts() - opts.Name = NewAccountObjectIdentifier("") + opts.Name = emptyAccountObjectIdentifier assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) @@ -893,7 +893,7 @@ func TestProcedures_CreateAndCallForPython(t *testing.T) { t.Run("validation: incorrect identifier", func(t *testing.T) { opts := defaultOpts() - opts.Name = NewAccountObjectIdentifier("") + opts.Name = emptyAccountObjectIdentifier assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) @@ -1015,7 +1015,7 @@ func TestProcedures_CreateAndCallForJavaScript(t *testing.T) { t.Run("validation: incorrect identifier", func(t *testing.T) { opts := defaultOpts() - opts.Name = NewAccountObjectIdentifier("") + opts.Name = emptyAccountObjectIdentifier assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) @@ -1077,7 +1077,7 @@ func TestProcedures_CreateAndCallForSQL(t *testing.T) { t.Run("validation: incorrect identifier", func(t *testing.T) { opts := defaultOpts() - opts.Name = NewAccountObjectIdentifier("") + opts.Name = emptyAccountObjectIdentifier assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) diff --git a/pkg/sdk/replication_functions_test.go b/pkg/sdk/replication_functions_test.go index 1de9bac45a..2424ca793c 100644 --- a/pkg/sdk/replication_functions_test.go +++ b/pkg/sdk/replication_functions_test.go @@ -17,7 +17,7 @@ func TestReplicationFunctions_ShowReplicationDatabases(t *testing.T) { t.Run("validation: valid identifier for [opts.WithPrimary]", func(t *testing.T) { opts := defaultOpts() - opts.WithPrimary = Pointer(NewExternalObjectIdentifier(NewAccountIdentifierFromAccountLocator(""), NewAccountObjectIdentifier(""))) + opts.WithPrimary = Pointer(NewExternalObjectIdentifier(NewAccountIdentifierFromAccountLocator(""), emptyAccountObjectIdentifier)) assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) diff --git a/pkg/sdk/roles_test.go b/pkg/sdk/roles_test.go index 2e723e7f48..7ae9455ae9 100644 --- a/pkg/sdk/roles_test.go +++ b/pkg/sdk/roles_test.go @@ -30,7 +30,7 @@ func TestRolesCreate(t *testing.T) { t.Run("validation: invalid identifier", func(t *testing.T) { opts := &CreateRoleOptions{ - name: NewAccountObjectIdentifier(""), + name: emptyAccountObjectIdentifier, } assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) @@ -63,7 +63,7 @@ func TestRolesDrop(t *testing.T) { t.Run("validation: invalid identifier", func(t *testing.T) { opts := &DropRoleOptions{ - name: NewAccountObjectIdentifier(""), + name: emptyAccountObjectIdentifier, } assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) @@ -125,7 +125,7 @@ func TestRolesAlter(t *testing.T) { t.Run("validation: invalid identifier", func(t *testing.T) { opts := &AlterRoleOptions{ - name: NewAccountObjectIdentifier(""), + name: emptyAccountObjectIdentifier, UnsetComment: Bool(true), } assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) @@ -180,7 +180,7 @@ func TestRolesShow(t *testing.T) { }) t.Run("validation: invalid class name", func(t *testing.T) { - class := NewAccountObjectIdentifier("") + class := emptyAccountObjectIdentifier opts := &ShowRoleOptions{ InClass: &RolesInClass{ Class: &class, @@ -213,13 +213,13 @@ func TestRolesGrant(t *testing.T) { t.Run("validation: invalid object identifier and no grant option", func(t *testing.T) { opts := &GrantRoleOptions{ - name: NewAccountObjectIdentifier(""), + name: emptyAccountObjectIdentifier, } assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier, errOneOf("GrantRoleOptions.Grant", "Role", "User")) }) t.Run("validation: invalid object identifier for granted role", func(t *testing.T) { - id := NewAccountObjectIdentifier("") + id := emptyAccountObjectIdentifier opts := &GrantRoleOptions{ name: randomAccountObjectIdentifier(), Grant: GrantRole{ @@ -230,7 +230,7 @@ func TestRolesGrant(t *testing.T) { }) t.Run("validation: invalid object identifier for granted user", func(t *testing.T) { - id := NewAccountObjectIdentifier("") + id := emptyAccountObjectIdentifier opts := &GrantRoleOptions{ name: randomAccountObjectIdentifier(), Grant: GrantRole{ @@ -264,7 +264,7 @@ func TestRolesRevoke(t *testing.T) { t.Run("validation: invalid object identifier and no option set", func(t *testing.T) { opts := &RevokeRoleOptions{ - name: NewAccountObjectIdentifier(""), + name: emptyAccountObjectIdentifier, } assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier, errOneOf("RevokeRoleOptions.Revoke", "Role", "User")) }) diff --git a/pkg/sdk/schemas.go b/pkg/sdk/schemas.go index 57fbf1c18d..30f6e34c90 100644 --- a/pkg/sdk/schemas.go +++ b/pkg/sdk/schemas.go @@ -391,7 +391,7 @@ func (v *schemas) ShowByID(ctx context.Context, id DatabaseObjectIdentifier) (*S schemas, err := v.client.Schemas.Show(ctx, &ShowSchemaOptions{ In: &SchemaIn{ Database: Bool(true), - Name: NewAccountObjectIdentifier(id.DatabaseName()), + Name: id.DatabaseId(), }, Like: &Like{ Pattern: String(id.Name()), diff --git a/pkg/sdk/storage_integration_gen_test.go b/pkg/sdk/storage_integration_gen_test.go index 05a4acbb62..2863dc49e0 100644 --- a/pkg/sdk/storage_integration_gen_test.go +++ b/pkg/sdk/storage_integration_gen_test.go @@ -24,7 +24,7 @@ func TestStorageIntegrations_Create(t *testing.T) { t.Run("validation: valid identifier for [opts.name]", func(t *testing.T) { opts := defaultOpts() - opts.name = NewAccountObjectIdentifier("") + opts.name = emptyAccountObjectIdentifier assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) @@ -104,7 +104,7 @@ func TestStorageIntegrations_Alter(t *testing.T) { t.Run("validation: valid identifier for [opts.name]", func(t *testing.T) { opts := defaultOpts() - opts.name = NewAccountObjectIdentifier("") + opts.name = emptyAccountObjectIdentifier assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) @@ -219,7 +219,7 @@ func TestStorageIntegrations_Drop(t *testing.T) { t.Run("validation: valid identifier for [opts.name]", func(t *testing.T) { opts := defaultOpts() - opts.name = NewAccountObjectIdentifier("") + opts.name = emptyAccountObjectIdentifier assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) @@ -274,7 +274,7 @@ func TestStorageIntegrations_Describe(t *testing.T) { t.Run("validation: valid identifier for [opts.name]", func(t *testing.T) { opts := defaultOpts() - opts.name = NewAccountObjectIdentifier("") + opts.name = emptyAccountObjectIdentifier assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) }) diff --git a/pkg/sdk/tags_test.go b/pkg/sdk/tags_test.go index a3cbf10e6a..179bf16b12 100644 --- a/pkg/sdk/tags_test.go +++ b/pkg/sdk/tags_test.go @@ -184,8 +184,8 @@ func TestTagAlter(t *testing.T) { }, } } - mp1ID := NewSchemaObjectIdentifier(id.DatabaseName(), id.SchemaName(), "policy1") - mp2ID := NewSchemaObjectIdentifier(id.DatabaseName(), id.SchemaName(), "policy2") + mp1ID := NewSchemaObjectIdentifierInSchema(id.SchemaId(), "policy1") + mp2ID := NewSchemaObjectIdentifierInSchema(id.SchemaId(), "policy2") defaultMaskingPolicies := func() []TagMaskingPolicy { return []TagMaskingPolicy{ { @@ -199,7 +199,7 @@ func TestTagAlter(t *testing.T) { t.Run("alter with rename to", func(t *testing.T) { opts := defaultOpts() - opts.Rename = &TagRename{Name: NewSchemaObjectIdentifier(id.DatabaseName(), id.SchemaName(), random.StringN(12))} + opts.Rename = &TagRename{Name: NewSchemaObjectIdentifierInSchema(id.SchemaId(), random.StringN(12))} assertOptsValidAndSQLEquals(t, opts, `ALTER TAG %s RENAME TO %s`, id.FullyQualifiedName(), opts.Rename.Name.FullyQualifiedName()) }) diff --git a/pkg/sdk/test_ids_test.go b/pkg/sdk/test_ids_test.go new file mode 100644 index 0000000000..7a67683a27 --- /dev/null +++ b/pkg/sdk/test_ids_test.go @@ -0,0 +1,4 @@ +package sdk + +// TODO: Add to the generator +var emptyAccountObjectIdentifier = NewAccountObjectIdentifier("") diff --git a/pkg/sdk/testint/accounts_integration_test.go b/pkg/sdk/testint/accounts_integration_test.go index 165e4191ee..e0af25a74e 100644 --- a/pkg/sdk/testint/accounts_integration_test.go +++ b/pkg/sdk/testint/accounts_integration_test.go @@ -6,6 +6,7 @@ import ( "time" "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance/helpers/random" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/internal/snowflakeroles" "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk" "github.com/avast/retry-go" "github.com/stretchr/testify/assert" @@ -15,7 +16,7 @@ import ( func TestInt_AccountShow(t *testing.T) { client := testClient(t) ctx := testContext(t) - ok := testClientHelper().Context.IsRoleInSession(t, sdk.NewAccountObjectIdentifier("ORGADMIN")) + ok := testClientHelper().Context.IsRoleInSession(t, snowflakeroles.Orgadmin) if !ok { t.Skip("ORGADMIN role is not in current session") } @@ -35,18 +36,18 @@ func TestInt_AccountShow(t *testing.T) { func TestInt_AccountShowByID(t *testing.T) { client := testClient(t) ctx := testContext(t) - ok := testClientHelper().Context.IsRoleInSession(t, sdk.NewAccountObjectIdentifier("ORGADMIN")) + ok := testClientHelper().Context.IsRoleInSession(t, snowflakeroles.Orgadmin) if !ok { t.Skip("ORGADMIN role is not in current session") } - _, err := client.Accounts.ShowByID(ctx, sdk.NewAccountObjectIdentifier("NOT_EXISTING_ACCOUNT")) + _, err := client.Accounts.ShowByID(ctx, NonExistingAccountObjectIdentifier) require.ErrorIs(t, err, sdk.ErrObjectNotExistOrAuthorized) } func TestInt_AccountCreate(t *testing.T) { client := testClient(t) ctx := testContext(t) - ok := testClientHelper().Context.IsRoleInSession(t, sdk.NewAccountObjectIdentifier("ORGADMIN")) + ok := testClientHelper().Context.IsRoleInSession(t, snowflakeroles.Orgadmin) if !ok { t.Skip("ORGADMIN role is not in current session") } @@ -155,7 +156,7 @@ func TestInt_AccountCreate(t *testing.T) { func TestInt_AccountAlter(t *testing.T) { client := testClient(t) ctx := testContext(t) - ok := testClientHelper().Context.IsRoleInSession(t, sdk.NewAccountObjectIdentifier("ACCOUNTADMIN")) + ok := testClientHelper().Context.IsRoleInSession(t, snowflakeroles.Accountadmin) if !ok { t.Skip("ACCOUNTADMIN role is not in current session") } diff --git a/pkg/sdk/testint/api_integrations_gen_integration_test.go b/pkg/sdk/testint/api_integrations_gen_integration_test.go index b6b55f15b6..bd89521c69 100644 --- a/pkg/sdk/testint/api_integrations_gen_integration_test.go +++ b/pkg/sdk/testint/api_integrations_gen_integration_test.go @@ -398,7 +398,7 @@ func TestInt_ApiIntegrations(t *testing.T) { }) t.Run("drop api integration: non-existing", func(t *testing.T) { - id := sdk.NewAccountObjectIdentifier("does_not_exist") + id := NonExistingAccountObjectIdentifier err := client.ApiIntegrations.Drop(ctx, sdk.NewDropApiIntegrationRequest(id)) assert.ErrorIs(t, err, sdk.ErrObjectNotExistOrAuthorized) @@ -478,7 +478,7 @@ func TestInt_ApiIntegrations(t *testing.T) { }) t.Run("describe api integration: non-existing", func(t *testing.T) { - id := sdk.NewAccountObjectIdentifier("does_not_exist") + id := NonExistingAccountObjectIdentifier _, err := client.ApiIntegrations.Describe(ctx, id) assert.ErrorIs(t, err, sdk.ErrObjectNotExistOrAuthorized) diff --git a/pkg/sdk/testint/application_roles_gen_integration_test.go b/pkg/sdk/testint/application_roles_gen_integration_test.go index af51a50dd7..2d4e3e429e 100644 --- a/pkg/sdk/testint/application_roles_gen_integration_test.go +++ b/pkg/sdk/testint/application_roles_gen_integration_test.go @@ -4,6 +4,7 @@ import ( "context" "testing" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance/testvars" "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk" "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk/internal/collections" "github.com/stretchr/testify/assert" @@ -22,6 +23,7 @@ func TestInt_ApplicationRoles(t *testing.T) { client := testClient(t) ctx := testContext(t) + // TODO [SNOW-1431726]: Move to helpers createApp := func(t *testing.T) *sdk.Application { t.Helper() @@ -70,11 +72,11 @@ func TestInt_ApplicationRoles(t *testing.T) { } t.Run("show by id - same name in different schemas", func(t *testing.T) { - name := "app_role_1" + name := testvars.ApplicationRole1 id := sdk.NewDatabaseObjectIdentifier(application.Name, name) ctx := context.Background() - appRole, err := client.ApplicationRoles.ShowByID(ctx, sdk.NewAccountObjectIdentifier(application.Name), id) + appRole, err := client.ApplicationRoles.ShowByID(ctx, id) require.NoError(t, err) assertApplicationRole(t, appRole, name, "some comment") @@ -89,15 +91,15 @@ func TestInt_ApplicationRoles(t *testing.T) { appRoles, err := client.ApplicationRoles.Show(ctx, req) require.NoError(t, err) - assertApplicationRoles(t, appRoles, "app_role_1", "some comment") - assertApplicationRoles(t, appRoles, "app_role_2", "some comment2") + assertApplicationRoles(t, appRoles, testvars.ApplicationRole1, "some comment") + assertApplicationRoles(t, appRoles, testvars.ApplicationRole2, "some comment2") }) t.Run("show grants to application - grant to role", func(t *testing.T) { role, cleanupRole := testClientHelper().Role.CreateRole(t) t.Cleanup(cleanupRole) - id := sdk.NewDatabaseObjectIdentifier(application.Name, "app_role_1") + id := sdk.NewDatabaseObjectIdentifier(application.Name, testvars.ApplicationRole1) // grant the application role to the role kindOfRole := sdk.NewKindOfRoleRequest().WithRoleName(sdk.Pointer(role.ID())) gr := sdk.NewGrantApplicationRoleRequest(id).WithTo(*kindOfRole) @@ -121,7 +123,7 @@ func TestInt_ApplicationRoles(t *testing.T) { t.Run("show grants to application - grant to application", func(t *testing.T) { application2 := createApp(t) - id := sdk.NewDatabaseObjectIdentifier(application.Name, "app_role_1") + id := sdk.NewDatabaseObjectIdentifier(application.Name, testvars.ApplicationRole1) // grant the application role to the application kindOfRole := sdk.NewKindOfRoleRequest().WithApplicationName(sdk.Pointer(application2.ID())) gr := sdk.NewGrantApplicationRoleRequest(id).WithTo(*kindOfRole) @@ -143,7 +145,7 @@ func TestInt_ApplicationRoles(t *testing.T) { }) t.Run("show grants to application role", func(t *testing.T) { - name := "app_role_1" + name := testvars.ApplicationRole1 id := sdk.NewDatabaseObjectIdentifier(application.Name, name) ctx := context.Background() @@ -157,7 +159,7 @@ func TestInt_ApplicationRoles(t *testing.T) { }) t.Run("show grants of application role", func(t *testing.T) { - name := "app_role_1" + name := testvars.ApplicationRole1 id := sdk.NewDatabaseObjectIdentifier(application.Name, name) ctx := context.Background() diff --git a/pkg/sdk/testint/context_functions_integration_test.go b/pkg/sdk/testint/context_functions_integration_test.go index e280c3fe86..7dd2a2624a 100644 --- a/pkg/sdk/testint/context_functions_integration_test.go +++ b/pkg/sdk/testint/context_functions_integration_test.go @@ -22,7 +22,7 @@ func TestInt_CurrentRole(t *testing.T) { ctx := testContext(t) role, err := client.ContextFunctions.CurrentRole(ctx) require.NoError(t, err) - assert.NotEmpty(t, role) + assert.NotEmpty(t, role.Name()) } func TestInt_CurrentRegion(t *testing.T) { @@ -46,7 +46,7 @@ func TestInt_CurrentUser(t *testing.T) { ctx := testContext(t) user, err := client.ContextFunctions.CurrentUser(ctx) require.NoError(t, err) - assert.NotEmpty(t, user) + assert.NotEmpty(t, user.Name()) } func TestInt_CurrentSessionDetails(t *testing.T) { @@ -110,7 +110,7 @@ func TestInt_IsRoleInSession(t *testing.T) { ctx := testContext(t) currentRole, err := client.ContextFunctions.CurrentRole(ctx) require.NoError(t, err) - role, err := client.ContextFunctions.IsRoleInSession(ctx, sdk.NewAccountObjectIdentifier(currentRole)) + role, err := client.ContextFunctions.IsRoleInSession(ctx, currentRole) require.NoError(t, err) assert.True(t, role) } @@ -119,14 +119,13 @@ func TestInt_RolesUse(t *testing.T) { client := testClient(t) ctx := testContext(t) currentRole, err := client.ContextFunctions.CurrentRole(ctx) - currentRoleID := sdk.NewAccountObjectIdentifier(currentRole) require.NoError(t, err) role, cleanup := testClientHelper().Role.CreateRole(t) t.Cleanup(cleanup) - require.NotEqual(t, currentRole, role.Name) + require.NotEqual(t, currentRole.Name(), role.Name) - err = client.Roles.Grant(ctx, sdk.NewGrantRoleRequest(role.ID(), sdk.GrantRole{Role: ¤tRoleID})) + err = client.Roles.Grant(ctx, sdk.NewGrantRoleRequest(role.ID(), sdk.GrantRole{Role: ¤tRole})) require.NoError(t, err) err = client.Sessions.UseRole(ctx, role.ID()) @@ -135,9 +134,9 @@ func TestInt_RolesUse(t *testing.T) { activeRole, err := client.ContextFunctions.CurrentRole(ctx) require.NoError(t, err) - assert.Equal(t, activeRole, role.Name) + assert.Equal(t, activeRole.Name(), role.Name) - err = client.Sessions.UseRole(ctx, currentRoleID) + err = client.Sessions.UseRole(ctx, currentRole) require.NoError(t, err) } @@ -149,13 +148,12 @@ func TestInt_RolesUseSecondaryRoles(t *testing.T) { role, cleanup := testClientHelper().Role.CreateRole(t) t.Cleanup(cleanup) - require.NotEqual(t, currentRole, role.Name) + require.NotEqual(t, currentRole.Name(), role.Name) user, err := client.ContextFunctions.CurrentUser(ctx) require.NoError(t, err) - userID := sdk.NewAccountObjectIdentifier(user) - err = client.Roles.Grant(ctx, sdk.NewGrantRoleRequest(role.ID(), sdk.GrantRole{User: &userID})) + err = client.Roles.Grant(ctx, sdk.NewGrantRoleRequest(role.ID(), sdk.GrantRole{User: &user})) require.NoError(t, err) err = client.Sessions.UseRole(ctx, role.ID()) @@ -172,7 +170,7 @@ func TestInt_RolesUseSecondaryRoles(t *testing.T) { names[i] = v.Name() } assert.Equal(t, sdk.SecondaryRolesAll, r.Value) - assert.Contains(t, names, currentRole) + assert.Contains(t, names, currentRole.Name()) err = client.Sessions.UseSecondaryRoles(ctx, sdk.SecondaryRolesNone) require.NoError(t, err) @@ -184,7 +182,7 @@ func TestInt_RolesUseSecondaryRoles(t *testing.T) { assert.Equal(t, 0, len(secondaryRolesAfter.Roles)) t.Cleanup(func() { - err = client.Sessions.UseRole(ctx, sdk.NewAccountObjectIdentifier(currentRole)) + err = client.Sessions.UseRole(ctx, currentRole) require.NoError(t, err) }) } diff --git a/pkg/sdk/testint/failover_groups_integration_test.go b/pkg/sdk/testint/failover_groups_integration_test.go index 0ff27469cf..521ddec23b 100644 --- a/pkg/sdk/testint/failover_groups_integration_test.go +++ b/pkg/sdk/testint/failover_groups_integration_test.go @@ -841,7 +841,7 @@ func TestInt_FailoverGroupsShow(t *testing.T) { }) t.Run("when searching a non-existent failover group", func(t *testing.T) { - _, err := client.FailoverGroups.ShowByID(ctx, sdk.NewAccountObjectIdentifier("does-not-exist")) + _, err := client.FailoverGroups.ShowByID(ctx, NonExistingAccountObjectIdentifier) require.ErrorIs(t, err, sdk.ErrObjectNotExistOrAuthorized) }) } diff --git a/pkg/sdk/testint/grants_integration_test.go b/pkg/sdk/testint/grants_integration_test.go index 615e69d3f5..6f7b546283 100644 --- a/pkg/sdk/testint/grants_integration_test.go +++ b/pkg/sdk/testint/grants_integration_test.go @@ -826,7 +826,7 @@ func TestInt_GrantOwnership(t *testing.T) { copyStatement := createPipeCopyStatement(t, table, stage) - checkOwnershipOnObjectToRole := func(t *testing.T, on sdk.OwnershipGrantOn, role string) { + checkOwnershipOnObjectToRole := func(t *testing.T, on sdk.OwnershipGrantOn, role sdk.AccountObjectIdentifier) { t.Helper() if on.Object == nil { t.Error("only on.Object check is supported") @@ -838,12 +838,12 @@ func TestInt_GrantOwnership(t *testing.T) { }) require.NoError(t, err) _, err = collections.FindOne(grants, func(grant sdk.Grant) bool { - return grant.Privilege == "OWNERSHIP" && grant.GranteeName.Name() == role + return grant.Privilege == "OWNERSHIP" && grant.GranteeName.Name() == role.Name() }) require.NoError(t, err) } - grantOwnershipToRole := func(t *testing.T, roleName string, on sdk.OwnershipGrantOn, outboundOpts *sdk.OwnershipCurrentGrantsOutboundPrivileges) { + grantOwnershipToRole := func(t *testing.T, roleName sdk.AccountObjectIdentifier, on sdk.OwnershipGrantOn, outboundOpts *sdk.OwnershipCurrentGrantsOutboundPrivileges) { t.Helper() var opts *sdk.GrantOwnershipOptions @@ -859,7 +859,7 @@ func TestInt_GrantOwnership(t *testing.T) { ctx, on, sdk.OwnershipGrantTo{ - AccountRoleName: sdk.Pointer(sdk.NewAccountObjectIdentifier(roleName)), + AccountRoleName: sdk.Pointer(roleName), }, opts, ) @@ -976,7 +976,7 @@ func TestInt_GrantOwnership(t *testing.T) { require.NoError(t, err) } - makeAccountRoleOperableOnPipe := func(t *testing.T, grantingRole string, pipe *sdk.Pipe) { + makeAccountRoleOperableOnPipe := func(t *testing.T, grantingRole sdk.AccountObjectIdentifier, pipe *sdk.Pipe) { t.Helper() err := client.Grants.GrantPrivilegesToAccountRole( @@ -992,7 +992,7 @@ func TestInt_GrantOwnership(t *testing.T) { }, }, }, - sdk.NewAccountObjectIdentifier(grantingRole), + grantingRole, new(sdk.GrantPrivilegesToAccountRoleOptions), ) require.NoError(t, err) @@ -1146,7 +1146,7 @@ func TestInt_GrantOwnership(t *testing.T) { new(sdk.GrantOwnershipOptions), ) require.NoError(t, err) - checkOwnershipOnObjectToRole(t, ownershipGrantOnPipe(pipe), role.ID().Name()) + checkOwnershipOnObjectToRole(t, ownershipGrantOnPipe(pipe), role.ID()) currentRole := testClientHelper().Context.CurrentRole(t) @@ -1173,11 +1173,11 @@ func TestInt_GrantOwnership(t *testing.T) { previousRole := testClientHelper().Context.CurrentRole(t) // Use a previously prepared role to create a pipe and grant MONITOR + OPERATE to the previously used role (ACCOUNTADMIN). - usePreviousRole := testClientHelper().Role.UseRole(t, pipeRole.Name) + usePreviousRole := testClientHelper().Role.UseRole(t, pipeRole.ID()) pipe, pipeCleanup := testClientHelper().Pipe.CreatePipe(t, copyStatement) t.Cleanup(func() { - usePreviousRole = testClientHelper().Role.UseRole(t, role.Name) + usePreviousRole = testClientHelper().Role.UseRole(t, role.ID()) defer usePreviousRole() pipeCleanup() }) @@ -1211,7 +1211,7 @@ func TestInt_GrantOwnership(t *testing.T) { }, ) require.NoError(t, err) - checkOwnershipOnObjectToRole(t, ownershipGrantOnPipe(pipe), role.ID().Name()) + checkOwnershipOnObjectToRole(t, ownershipGrantOnPipe(pipe), role.ID()) usePreviousRole() @@ -1235,11 +1235,11 @@ func TestInt_GrantOwnership(t *testing.T) { previousRole := testClientHelper().Context.CurrentRole(t) // Use a previously prepared role to create a pipe and grant MONITOR + OPERATE to the previously used role (ACCOUNTADMIN). - usePreviousRole := testClientHelper().Role.UseRole(t, pipeRole.Name) + usePreviousRole := testClientHelper().Role.UseRole(t, pipeRole.ID()) pipe, pipeCleanup := testClientHelper().Pipe.CreatePipe(t, copyStatement) t.Cleanup(func() { - usePreviousRole = testClientHelper().Role.UseRole(t, role.Name) + usePreviousRole = testClientHelper().Role.UseRole(t, role.ID()) defer usePreviousRole() pipeCleanup() }) @@ -1273,7 +1273,7 @@ func TestInt_GrantOwnership(t *testing.T) { }, ) require.NoError(t, err) - checkOwnershipOnObjectToRole(t, ownershipGrantOnPipe(pipe), role.ID().Name()) + checkOwnershipOnObjectToRole(t, ownershipGrantOnPipe(pipe), role.ID()) usePreviousRole() @@ -1295,11 +1295,11 @@ func TestInt_GrantOwnership(t *testing.T) { grantPipeRole(t, pipeRole, table, stage) // Use a previously prepared role to create a pipe and grant MONITOR + OPERATE to the previously used role (ACCOUNTADMIN). - usePreviousRole := testClientHelper().Role.UseRole(t, pipeRole.Name) + usePreviousRole := testClientHelper().Role.UseRole(t, pipeRole.ID()) pipe, pipeCleanup := testClientHelper().Pipe.CreatePipe(t, copyStatement) t.Cleanup(func() { - usePreviousRole = testClientHelper().Role.UseRole(t, pipeRole.Name) + usePreviousRole = testClientHelper().Role.UseRole(t, pipeRole.ID()) defer usePreviousRole() pipeCleanup() }) @@ -1341,11 +1341,11 @@ func TestInt_GrantOwnership(t *testing.T) { grantPipeRole(t, pipeRole, table, stage) // Use a previously prepared role to create a pipe and grant MONITOR + OPERATE to the previously used role (ACCOUNTADMIN). - usePreviousRole := testClientHelper().Role.UseRole(t, pipeRole.Name) + usePreviousRole := testClientHelper().Role.UseRole(t, pipeRole.ID()) pipe, pipeCleanup := testClientHelper().Pipe.CreatePipe(t, copyStatement) t.Cleanup(func() { - usePreviousRole = testClientHelper().Role.UseRole(t, role.Name) + usePreviousRole = testClientHelper().Role.UseRole(t, role.ID()) defer usePreviousRole() pipeCleanup() }) @@ -1372,7 +1372,7 @@ func TestInt_GrantOwnership(t *testing.T) { new(sdk.GrantOwnershipOptions), ) require.NoError(t, err) - checkOwnershipOnObjectToRole(t, ownershipGrantOnPipe(pipe), role.Name) + checkOwnershipOnObjectToRole(t, ownershipGrantOnPipe(pipe), role.ID()) }) t.Run("on all pipes", func(t *testing.T) { @@ -1409,8 +1409,8 @@ func TestInt_GrantOwnership(t *testing.T) { ) require.NoError(t, err) - checkOwnershipOnObjectToRole(t, ownershipGrantOnPipe(pipe), role.ID().Name()) - checkOwnershipOnObjectToRole(t, ownershipGrantOnPipe(secondPipe), role.ID().Name()) + checkOwnershipOnObjectToRole(t, ownershipGrantOnPipe(pipe), role.ID()) + checkOwnershipOnObjectToRole(t, ownershipGrantOnPipe(secondPipe), role.ID()) currentRole := testClientHelper().Context.CurrentRole(t) grantOwnershipToRole(t, currentRole, onAllPipesInSchema, nil) @@ -1449,7 +1449,7 @@ func TestInt_GrantOwnership(t *testing.T) { new(sdk.GrantOwnershipOptions), ) require.NoError(t, err) - checkOwnershipOnObjectToRole(t, ownershipGrantOnTask(task), role.ID().Name()) + checkOwnershipOnObjectToRole(t, ownershipGrantOnTask(task), role.ID()) task, err = client.Tasks.ShowByID(ctx, task.ID()) require.NoError(t, err) @@ -1470,11 +1470,11 @@ func TestInt_GrantOwnership(t *testing.T) { grantTaskRole(t, taskRole.ID()) // Use a previously prepared role to create a task - usePreviousRole := testClientHelper().Role.UseRole(t, taskRole.Name) + usePreviousRole := testClientHelper().Role.UseRole(t, taskRole.ID()) task, taskCleanup := testClientHelper().Task.CreateTask(t) t.Cleanup(func() { - usePreviousRole := testClientHelper().Role.UseRole(t, taskRole.Name) + usePreviousRole := testClientHelper().Role.UseRole(t, taskRole.ID()) defer usePreviousRole() taskCleanup() }) @@ -1513,10 +1513,10 @@ func TestInt_GrantOwnership(t *testing.T) { grantTaskRole(t, taskRole.ID()) currentRole := testClientHelper().Context.CurrentRole(t) - grantTaskRole(t, sdk.NewAccountObjectIdentifier(currentRole)) + grantTaskRole(t, currentRole) // Use a previously prepared role to create a task - usePreviousRole := testClientHelper().Role.UseRole(t, taskRole.Name) + usePreviousRole := testClientHelper().Role.UseRole(t, taskRole.ID()) task, taskCleanup := testClientHelper().Task.CreateTask(t) t.Cleanup(taskCleanup) @@ -1534,7 +1534,7 @@ func TestInt_GrantOwnership(t *testing.T) { }, }, }, - sdk.NewAccountObjectIdentifier(currentRole), + currentRole, new(sdk.GrantPrivilegesToAccountRoleOptions), ) require.NoError(t, err) @@ -1566,7 +1566,7 @@ func TestInt_GrantOwnership(t *testing.T) { }, ) require.NoError(t, err) - checkOwnershipOnObjectToRole(t, ownershipGrantOnTask(task), role.ID().Name()) + checkOwnershipOnObjectToRole(t, ownershipGrantOnTask(task), role.ID()) currentTask, err = client.Tasks.ShowByID(ctx, task.ID()) require.NoError(t, err) @@ -1613,8 +1613,8 @@ func TestInt_GrantOwnership(t *testing.T) { ) require.NoError(t, err) - checkOwnershipOnObjectToRole(t, ownershipGrantOnTask(task), role.ID().Name()) - checkOwnershipOnObjectToRole(t, ownershipGrantOnTask(secondTask), role.ID().Name()) + checkOwnershipOnObjectToRole(t, ownershipGrantOnTask(task), role.ID()) + checkOwnershipOnObjectToRole(t, ownershipGrantOnTask(secondTask), role.ID()) currentTask, err = client.Tasks.ShowByID(ctx, task.ID()) require.NoError(t, err) @@ -1641,10 +1641,10 @@ func TestInt_GrantOwnership(t *testing.T) { currentRole := testClientHelper().Context.CurrentRole(t) grantTaskRole(t, role.ID()) - grantTaskRole(t, sdk.NewAccountObjectIdentifier(currentRole)) + grantTaskRole(t, currentRole) // Use a previously prepared role to create a task - usePreviousRole := testClientHelper().Role.UseRole(t, taskRole.Name) + usePreviousRole := testClientHelper().Role.UseRole(t, taskRole.ID()) task, taskCleanup := testClientHelper().Task.CreateTask(t) t.Cleanup(taskCleanup) @@ -1665,7 +1665,7 @@ func TestInt_GrantOwnership(t *testing.T) { }, }, }, - sdk.NewAccountObjectIdentifier(currentRole), + currentRole, new(sdk.GrantPrivilegesToAccountRoleOptions), ) require.NoError(t, err) @@ -1683,7 +1683,7 @@ func TestInt_GrantOwnership(t *testing.T) { }, }, }, - sdk.NewAccountObjectIdentifier(currentRole), + currentRole, new(sdk.GrantPrivilegesToAccountRoleOptions), ) require.NoError(t, err) @@ -1698,13 +1698,13 @@ func TestInt_GrantOwnership(t *testing.T) { t.Cleanup(func() { currentRole := testClientHelper().Context.CurrentRole(t) - usePreviousRole := testClientHelper().Role.UseRole(t, role.Name) + usePreviousRole := testClientHelper().Role.UseRole(t, role.ID()) grantOwnershipToRole(t, currentRole, ownershipGrantOnTask(task), sdk.Pointer(sdk.Revoke)) grantOwnershipToRole(t, currentRole, ownershipGrantOnTask(secondTask), sdk.Pointer(sdk.Revoke)) usePreviousRole() }) - usePreviousRole = testClientHelper().Role.UseRole(t, taskRole.Name) + usePreviousRole = testClientHelper().Role.UseRole(t, taskRole.ID()) currentTask, err := client.Tasks.ShowByID(ctx, task.ID()) require.NoError(t, err) require.Equal(t, sdk.TaskStateStarted, currentTask.State) @@ -1734,10 +1734,10 @@ func TestInt_GrantOwnership(t *testing.T) { ) require.NoError(t, err) - checkOwnershipOnObjectToRole(t, ownershipGrantOnTask(task), role.ID().Name()) - checkOwnershipOnObjectToRole(t, ownershipGrantOnTask(secondTask), role.ID().Name()) + checkOwnershipOnObjectToRole(t, ownershipGrantOnTask(task), role.ID()) + checkOwnershipOnObjectToRole(t, ownershipGrantOnTask(secondTask), role.ID()) - usePreviousRole = testClientHelper().Role.UseRole(t, role.Name) + usePreviousRole = testClientHelper().Role.UseRole(t, role.ID()) currentTask, err = client.Tasks.ShowByID(ctx, task.ID()) require.NoError(t, err) require.Equal(t, sdk.TaskStateSuspended, currentTask.State) diff --git a/pkg/sdk/testint/managed_accounts_gen_integration_test.go b/pkg/sdk/testint/managed_accounts_gen_integration_test.go index 726edeac19..176524b58f 100644 --- a/pkg/sdk/testint/managed_accounts_gen_integration_test.go +++ b/pkg/sdk/testint/managed_accounts_gen_integration_test.go @@ -103,7 +103,7 @@ func TestInt_ManagedAccounts(t *testing.T) { }) t.Run("drop managed account: non-existing", func(t *testing.T) { - id := sdk.NewAccountObjectIdentifier("does_not_exist") + id := NonExistingAccountObjectIdentifier err := client.ManagedAccounts.Drop(ctx, sdk.NewDropManagedAccountRequest(id)) assert.ErrorIs(t, err, sdk.ErrObjectNotExistOrAuthorized) diff --git a/pkg/sdk/testint/notification_integrations_gen_integration_test.go b/pkg/sdk/testint/notification_integrations_gen_integration_test.go index bddba5c919..b6fb761ae8 100644 --- a/pkg/sdk/testint/notification_integrations_gen_integration_test.go +++ b/pkg/sdk/testint/notification_integrations_gen_integration_test.go @@ -409,7 +409,7 @@ func TestInt_NotificationIntegrations(t *testing.T) { }) t.Run("drop notification integration: non-existing", func(t *testing.T) { - id := sdk.NewAccountObjectIdentifier("does_not_exist") + id := NonExistingAccountObjectIdentifier err := client.NotificationIntegrations.Drop(ctx, sdk.NewDropNotificationIntegrationRequest(id)) assert.ErrorIs(t, err, sdk.ErrObjectNotExistOrAuthorized) @@ -446,7 +446,7 @@ func TestInt_NotificationIntegrations(t *testing.T) { }) t.Run("describe notification integration: non-existing", func(t *testing.T) { - id := sdk.NewAccountObjectIdentifier("does_not_exist") + id := NonExistingAccountObjectIdentifier _, err := client.NotificationIntegrations.Describe(ctx, id) assert.ErrorIs(t, err, sdk.ErrObjectNotExistOrAuthorized) diff --git a/pkg/sdk/testint/procedures_integration_test.go b/pkg/sdk/testint/procedures_integration_test.go index f950f79283..8d9f361874 100644 --- a/pkg/sdk/testint/procedures_integration_test.go +++ b/pkg/sdk/testint/procedures_integration_test.go @@ -805,6 +805,7 @@ func TestInt_CreateAndCallProcedures(t *testing.T) { t.Run("create and call procedure for Java: returns table", func(t *testing.T) { // https://docs.snowflake.com/en/developer-guide/stored-procedure/stored-procedures-java#omitting-return-column-names-and-types + // TODO [SNOW-1348106]: make random with procedures rework name := sdk.NewAccountObjectIdentifier("filter_by_role") definition := ` @@ -835,6 +836,7 @@ func TestInt_CreateAndCallProcedures(t *testing.T) { t.Run("create and call procedure for Scala: returns table", func(t *testing.T) { // https://docs.snowflake.com/en/developer-guide/stored-procedure/stored-procedures-scala#omitting-return-column-names-and-types + // TODO [SNOW-1348106]: make random with procedures rework name := sdk.NewAccountObjectIdentifier("filter_by_role") definition := ` @@ -867,6 +869,7 @@ func TestInt_CreateAndCallProcedures(t *testing.T) { t.Run("create and call procedure for Javascript", func(t *testing.T) { // https://docs.snowflake.com/en/developer-guide/stored-procedure/stored-procedures-javascript#basic-examples + // TODO [SNOW-1348106]: make random with procedures rework name := sdk.NewAccountObjectIdentifier("stproc1") definition := ` @@ -891,6 +894,7 @@ func TestInt_CreateAndCallProcedures(t *testing.T) { t.Run("create and call procedure for Javascript: no arguments", func(t *testing.T) { // https://docs.snowflake.com/en/sql-reference/sql/create-procedure#examples + // TODO [SNOW-1348106]: make random with procedures rework name := sdk.NewAccountObjectIdentifier("sp_pi") definition := `return 3.1415926;` @@ -918,6 +922,7 @@ func TestInt_CreateAndCallProcedures(t *testing.T) { t.Run("create and call procedure for Python: returns table", func(t *testing.T) { // https://docs.snowflake.com/en/developer-guide/stored-procedure/stored-procedures-python#omitting-return-column-names-and-types + // TODO [SNOW-1348106]: make random with procedures rework name := sdk.NewAccountObjectIdentifier("filterByRole") definition := ` from snowflake.snowpark.functions import col @@ -940,6 +945,7 @@ def filter_by_role(session, name, role): t.Run("create and call procedure for Java: returns table and with clause", func(t *testing.T) { // https://docs.snowflake.com/en/developer-guide/stored-procedure/stored-procedures-java#omitting-return-column-names-and-types + // TODO [SNOW-1348106]: make random with procedures rework name := sdk.NewAccountObjectIdentifier("filter_by_role") definition := ` import com.snowflake.snowpark_java.*; @@ -960,6 +966,7 @@ def filter_by_role(session, name, role): packages := []sdk.ProcedurePackageRequest{*sdk.NewProcedurePackageRequest("com.snowflake:snowpark:latest")} ca := []string{fmt.Sprintf(`'%s'`, tid.FullyQualifiedName()), "'dev'"} + // TODO [SNOW-1348106]: make random with procedures rework cte := sdk.NewAccountObjectIdentifier("records") statement := fmt.Sprintf(`(SELECT name, role FROM %s WHERE name = 'Bob')`, tid.FullyQualifiedName()) clause := sdk.NewProcedureWithClauseRequest(cte, statement).WithCteColumns([]string{"name", "role"}) diff --git a/pkg/sdk/testint/resource_monitors_integration_test.go b/pkg/sdk/testint/resource_monitors_integration_test.go index 31bfb973fe..55eb068834 100644 --- a/pkg/sdk/testint/resource_monitors_integration_test.go +++ b/pkg/sdk/testint/resource_monitors_integration_test.go @@ -312,7 +312,7 @@ func TestInt_ResourceMonitorDrop(t *testing.T) { }) t.Run("when resource monitor does not exist", func(t *testing.T) { - id := sdk.NewAccountObjectIdentifier("does_not_exist") + id := NonExistingAccountObjectIdentifier err := client.ResourceMonitors.Drop(ctx, id, nil) assert.ErrorIs(t, err, sdk.ErrObjectNotExistOrAuthorized) }) diff --git a/pkg/sdk/testint/sessions_integration_test.go b/pkg/sdk/testint/sessions_integration_test.go index 10f705ede5..8675a3bc40 100644 --- a/pkg/sdk/testint/sessions_integration_test.go +++ b/pkg/sdk/testint/sessions_integration_test.go @@ -88,9 +88,8 @@ func TestInt_ShowObjectParameter(t *testing.T) { func TestInt_ShowUserParameter(t *testing.T) { client := testClient(t) ctx := testContext(t) - user := testClientHelper().Context.CurrentUser(t) - userID := sdk.NewAccountObjectIdentifier(user) - parameter, err := client.Parameters.ShowUserParameter(ctx, sdk.UserParameterAutocommit, userID) + userId := testClientHelper().Context.CurrentUser(t) + parameter, err := client.Parameters.ShowUserParameter(ctx, sdk.UserParameterAutocommit, userId) require.NoError(t, err) assert.NotEmpty(t, parameter) } diff --git a/pkg/sdk/testint/setup_test.go b/pkg/sdk/testint/setup_test.go index 0c77efe458..eaeef1e63c 100644 --- a/pkg/sdk/testint/setup_test.go +++ b/pkg/sdk/testint/setup_test.go @@ -21,6 +21,8 @@ var ( TestWarehouseName = "int_test_wh_" + random.IntegrationTestsSuffix TestDatabaseName = "int_test_db_" + random.IntegrationTestsSuffix TestSchemaName = "int_test_sc_" + random.IntegrationTestsSuffix + + NonExistingAccountObjectIdentifier = sdk.NewAccountObjectIdentifier("does_not_exist") ) var itc integrationTestContext diff --git a/pkg/sdk/testint/shares_integration_test.go b/pkg/sdk/testint/shares_integration_test.go index 4297c62321..4b4f282f68 100644 --- a/pkg/sdk/testint/shares_integration_test.go +++ b/pkg/sdk/testint/shares_integration_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance/helpers/random" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance/ids" "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -113,7 +114,7 @@ func TestInt_SharesDrop(t *testing.T) { }) t.Run("when share does not exist", func(t *testing.T) { - err := client.Shares.Drop(ctx, sdk.NewAccountObjectIdentifier("does_not_exist"), &sdk.DropShareOptions{}) + err := client.Shares.Drop(ctx, NonExistingAccountObjectIdentifier, &sdk.DropShareOptions{}) assert.ErrorIs(t, err, sdk.ErrObjectNotExistOrAuthorized) }) } @@ -400,6 +401,6 @@ func TestInt_ShareDescribeConsumer(t *testing.T) { assert.Equal(t, 1, len(shareDetails.SharedObjects)) sharedObject := shareDetails.SharedObjects[0] assert.Equal(t, sdk.ObjectTypeDatabase, sharedObject.Kind) - assert.Equal(t, sdk.NewAccountObjectIdentifier(""), sharedObject.Name) + assert.Equal(t, ids.DatabasePlaceholder, sharedObject.Name) }) } diff --git a/pkg/sdk/testint/stages_gen_integration_test.go b/pkg/sdk/testint/stages_gen_integration_test.go index dd57dcf4b2..32f4eb1fc4 100644 --- a/pkg/sdk/testint/stages_gen_integration_test.go +++ b/pkg/sdk/testint/stages_gen_integration_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance/helpers/random" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance/ids" "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance/testenvs" "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk" "github.com/stretchr/testify/assert" @@ -23,11 +24,11 @@ func TestInt_Stages(t *testing.T) { azureBucketUrl := testenvs.GetOrSkipTest(t, testenvs.AzureExternalBucketUrl) azureSasToken := testenvs.GetOrSkipTest(t, testenvs.AzureExternalSasToken) - s3StorageIntegration, err := client.StorageIntegrations.ShowByID(ctx, sdk.NewAccountObjectIdentifier("S3_STORAGE_INTEGRATION")) + s3StorageIntegration, err := client.StorageIntegrations.ShowByID(ctx, ids.PrecreatedS3StorageIntegration) require.NoError(t, err) - gcpStorageIntegration, err := client.StorageIntegrations.ShowByID(ctx, sdk.NewAccountObjectIdentifier("GCP_STORAGE_INTEGRATION")) + gcpStorageIntegration, err := client.StorageIntegrations.ShowByID(ctx, ids.PrecreatedGcpStorageIntegration) require.NoError(t, err) - azureStorageIntegration, err := client.StorageIntegrations.ShowByID(ctx, sdk.NewAccountObjectIdentifier("AZURE_STORAGE_INTEGRATION")) + azureStorageIntegration, err := client.StorageIntegrations.ShowByID(ctx, ids.PrecreatedAzureStorageIntegration) require.NoError(t, err) cleanupStage := func(t *testing.T, id sdk.SchemaObjectIdentifier) { @@ -56,7 +57,7 @@ func TestInt_Stages(t *testing.T) { err := client.Stages.CreateOnGCS(ctx, sdk.NewCreateOnGCSStageRequest(stageId). WithFileFormat(sdk.NewStageFileFormatRequest().WithType(&sdk.FileFormatTypeJSON)). WithExternalStageParams(sdk.NewExternalGCSStageParamsRequest(gcsBucketUrl). - WithStorageIntegration(sdk.Pointer(sdk.NewAccountObjectIdentifier(gcpStorageIntegration.Name))))) + WithStorageIntegration(sdk.Pointer(ids.PrecreatedGcpStorageIntegration)))) require.NoError(t, err) cleanupStage(t, stageId) } @@ -141,7 +142,7 @@ func TestInt_Stages(t *testing.T) { id := sdk.NewSchemaObjectIdentifier(testDb(t).Name, testSchema(t).Name, random.AlphanumericN(32)) s3Req := sdk.NewExternalS3StageParamsRequest(awsBucketUrl). - WithStorageIntegration(sdk.Pointer(sdk.NewAccountObjectIdentifier(s3StorageIntegration.Name))) + WithStorageIntegration(sdk.Pointer(ids.PrecreatedS3StorageIntegration)) err := client.Stages.CreateOnS3(ctx, sdk.NewCreateOnS3StageRequest(id). WithTemporary(sdk.Bool(true)). WithFileFormat(sdk.NewStageFileFormatRequest().WithType(&sdk.FileFormatTypeJSON)). @@ -161,7 +162,7 @@ func TestInt_Stages(t *testing.T) { err := client.Stages.CreateOnGCS(ctx, sdk.NewCreateOnGCSStageRequest(id). WithFileFormat(sdk.NewStageFileFormatRequest().WithType(&sdk.FileFormatTypeJSON)). WithExternalStageParams(sdk.NewExternalGCSStageParamsRequest(gcsBucketUrl). - WithStorageIntegration(sdk.Pointer(sdk.NewAccountObjectIdentifier(gcpStorageIntegration.Name)))). + WithStorageIntegration(sdk.Pointer(ids.PrecreatedGcpStorageIntegration))). WithComment(sdk.String("some comment"))) require.NoError(t, err) cleanupStage(t, id) @@ -177,7 +178,7 @@ func TestInt_Stages(t *testing.T) { err := client.Stages.CreateOnAzure(ctx, sdk.NewCreateOnAzureStageRequest(id). WithFileFormat(sdk.NewStageFileFormatRequest().WithType(&sdk.FileFormatTypeJSON)). WithExternalStageParams(sdk.NewExternalAzureStageParamsRequest(azureBucketUrl). - WithStorageIntegration(sdk.Pointer(sdk.NewAccountObjectIdentifier(azureStorageIntegration.Name)))). + WithStorageIntegration(sdk.Pointer(ids.PrecreatedAzureStorageIntegration))). WithComment(sdk.String("some comment"))) require.NoError(t, err) cleanupStage(t, id) @@ -340,7 +341,7 @@ func TestInt_Stages(t *testing.T) { err := client.Stages.AlterExternalS3Stage(ctx, sdk.NewAlterExternalS3StageStageRequest(id). WithExternalStageParams(sdk.NewExternalS3StageParamsRequest(awsBucketUrl). - WithStorageIntegration(sdk.Pointer(sdk.NewAccountObjectIdentifier(s3StorageIntegration.Name)))). + WithStorageIntegration(sdk.Pointer(ids.PrecreatedS3StorageIntegration))). WithComment(sdk.String("Updated comment"))) require.NoError(t, err) @@ -360,7 +361,7 @@ func TestInt_Stages(t *testing.T) { err := client.Stages.AlterExternalGCSStage(ctx, sdk.NewAlterExternalGCSStageStageRequest(id). WithExternalStageParams(sdk.NewExternalGCSStageParamsRequest(gcsBucketUrl). - WithStorageIntegration(sdk.Pointer(sdk.NewAccountObjectIdentifier(gcpStorageIntegration.Name)))). + WithStorageIntegration(sdk.Pointer(ids.PrecreatedGcpStorageIntegration))). WithComment(sdk.String("Updated comment"))) require.NoError(t, err) @@ -375,7 +376,7 @@ func TestInt_Stages(t *testing.T) { err := client.Stages.AlterExternalAzureStage(ctx, sdk.NewAlterExternalAzureStageStageRequest(id). WithExternalStageParams(sdk.NewExternalAzureStageParamsRequest(azureBucketUrl). - WithStorageIntegration(sdk.Pointer(sdk.NewAccountObjectIdentifier(azureStorageIntegration.Name)))). + WithStorageIntegration(sdk.Pointer(ids.PrecreatedAzureStorageIntegration))). WithComment(sdk.String("Updated comment"))) require.NoError(t, err) diff --git a/pkg/sdk/testint/streamlits_integration_test.go b/pkg/sdk/testint/streamlits_integration_test.go index 3a7c888a46..bdfcf990dc 100644 --- a/pkg/sdk/testint/streamlits_integration_test.go +++ b/pkg/sdk/testint/streamlits_integration_test.go @@ -286,7 +286,7 @@ func TestInt_Streamlits(t *testing.T) { require.Equal(t, e.Name, detail.Name) require.Equal(t, e.UrlId, detail.UrlId) require.Equal(t, mainFile, detail.MainFile) - require.Equal(t, stage.Location(), detail.RootLocation) + require.Equal(t, stage.ID().FullyQualifiedName(), sdk.NewSchemaObjectIdentifierFromFullyQualifiedName(detail.RootLocation[1:]).FullyQualifiedName()) require.Empty(t, detail.Title) require.Empty(t, detail.QueryWarehouse) }) diff --git a/pkg/sdk/testint/system_functions_integration_test.go b/pkg/sdk/testint/system_functions_integration_test.go index 0371f69969..851f1d476e 100644 --- a/pkg/sdk/testint/system_functions_integration_test.go +++ b/pkg/sdk/testint/system_functions_integration_test.go @@ -151,7 +151,7 @@ func TestInt_PipeForceResume(t *testing.T) { }, }, sdk.OwnershipGrantTo{ - AccountRoleName: sdk.Pointer(sdk.NewAccountObjectIdentifier(currentRole)), + AccountRoleName: sdk.Pointer(currentRole), }, new(sdk.GrantOwnershipOptions), ) diff --git a/pkg/sdk/testint/tables_integration_test.go b/pkg/sdk/testint/tables_integration_test.go index 523ebdd78a..3a732c3f92 100644 --- a/pkg/sdk/testint/tables_integration_test.go +++ b/pkg/sdk/testint/tables_integration_test.go @@ -10,6 +10,7 @@ import ( "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance/helpers" "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance/helpers/random" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/internal/snowflakeroles" "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk" "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk/internal/collections" "github.com/stretchr/testify/assert" @@ -545,7 +546,7 @@ func TestInt_Table(t *testing.T) { require.NoError(t, err) require.Equal(t, 2, len(tableDetails)) - assert.Equal(t, maskingPolicy.ID().FullyQualifiedName(), *tableDetails[0].PolicyName) + assert.Equal(t, maskingPolicy.ID().FullyQualifiedName(), sdk.NewSchemaObjectIdentifierFromFullyQualifiedName(*tableDetails[0].PolicyName).FullyQualifiedName()) alterRequest := sdk.NewAlterTableRequest(id). WithColumnAction(sdk.NewTableColumnActionRequest().WithUnsetMaskingPolicy(sdk.NewTableColumnAlterUnsetMaskingPolicyActionRequest("COLUMN_1"))) @@ -1051,7 +1052,7 @@ func TestInt_TablesShowByID(t *testing.T) { err = client.Grants.GrantPrivilegesToAccountRole(ctx, &sdk.AccountRoleGrantPrivileges{SchemaObjectPrivileges: []sdk.SchemaObjectPrivilege{sdk.SchemaObjectPrivilegeEvolveSchema}}, &sdk.AccountRoleGrantOn{SchemaObject: &sdk.GrantOnSchemaObject{SchemaObject: &sdk.Object{ObjectType: sdk.ObjectTypeTable, Name: sdk.NewObjectIdentifierFromFullyQualifiedName(table.ID().FullyQualifiedName())}}}, - sdk.NewAccountObjectIdentifier("ACCOUNTADMIN"), + snowflakeroles.Accountadmin, nil) require.NoError(t, err) diff --git a/pkg/sdk/testint/users_integration_test.go b/pkg/sdk/testint/users_integration_test.go index ad74543f8e..dcebb58d8c 100644 --- a/pkg/sdk/testint/users_integration_test.go +++ b/pkg/sdk/testint/users_integration_test.go @@ -209,7 +209,7 @@ func TestInt_UserDescribe(t *testing.T) { }) t.Run("when user does not exist", func(t *testing.T) { - id := sdk.NewAccountObjectIdentifier("does_not_exist") + id := NonExistingAccountObjectIdentifier _, err := client.Users.Describe(ctx, id) assert.ErrorIs(t, err, sdk.ErrObjectNotExistOrAuthorized) }) @@ -231,7 +231,7 @@ func TestInt_UserDrop(t *testing.T) { }) t.Run("when user does not exist", func(t *testing.T) { - id := sdk.NewAccountObjectIdentifier("does_not_exist") + id := NonExistingAccountObjectIdentifier err := client.Users.Drop(ctx, id, &sdk.DropUserOptions{}) assert.ErrorIs(t, err, sdk.ErrObjectNotExistOrAuthorized) }) diff --git a/pkg/sdk/testint/views_gen_integration_test.go b/pkg/sdk/testint/views_gen_integration_test.go index 937773c217..05170da964 100644 --- a/pkg/sdk/testint/views_gen_integration_test.go +++ b/pkg/sdk/testint/views_gen_integration_test.go @@ -334,7 +334,7 @@ func TestInt_Views(t *testing.T) { require.NoError(t, err) assert.Equal(t, 1, len(alteredViewDetails)) - assert.Equal(t, maskingPolicy.ID().FullyQualifiedName(), *alteredViewDetails[0].PolicyName) + assert.Equal(t, maskingPolicy.ID().FullyQualifiedName(), sdk.NewSchemaObjectIdentifierFromFullyQualifiedName(*alteredViewDetails[0].PolicyName).FullyQualifiedName()) alterRequest = sdk.NewAlterViewRequest(id).WithUnsetMaskingPolicyOnColumn( sdk.NewViewUnsetColumnMaskingPolicyRequest("id"), diff --git a/pkg/sdk/testint/warehouses_integration_test.go b/pkg/sdk/testint/warehouses_integration_test.go index b4340963bb..92ffd9eec5 100644 --- a/pkg/sdk/testint/warehouses_integration_test.go +++ b/pkg/sdk/testint/warehouses_integration_test.go @@ -177,7 +177,7 @@ func TestInt_WarehouseDescribe(t *testing.T) { }) t.Run("when warehouse does not exist", func(t *testing.T) { - id := sdk.NewAccountObjectIdentifier("does_not_exist") + id := NonExistingAccountObjectIdentifier _, err := client.Warehouses.Describe(ctx, id) assert.ErrorIs(t, err, sdk.ErrObjectNotExistOrAuthorized) }) @@ -524,7 +524,7 @@ func TestInt_WarehouseDrop(t *testing.T) { }) t.Run("when warehouse does not exist", func(t *testing.T) { - id := sdk.NewAccountObjectIdentifier("does_not_exist") + id := NonExistingAccountObjectIdentifier err := client.Warehouses.Drop(ctx, id, nil) assert.ErrorIs(t, err, sdk.ErrObjectNotExistOrAuthorized) }) diff --git a/pkg/sdk/validations_test.go b/pkg/sdk/validations_test.go index dacda226af..6bd3a20f64 100644 --- a/pkg/sdk/validations_test.go +++ b/pkg/sdk/validations_test.go @@ -38,7 +38,7 @@ func TestValidObjectIdentifier(t *testing.T) { }) t.Run("with invalid object identifier", func(t *testing.T) { - ok := ValidObjectIdentifier(NewAccountObjectIdentifier("")) + ok := ValidObjectIdentifier(emptyAccountObjectIdentifier) assert.Equal(t, ok, false) }) @@ -158,7 +158,7 @@ func TestValueSet(t *testing.T) { }) t.Run("with invalid identifier", func(t *testing.T) { - ok := valueSet(NewAccountObjectIdentifier("")) + ok := valueSet(emptyAccountObjectIdentifier) assert.Equal(t, ok, false) }) diff --git a/v1-preparations/ESSENTIAL_GA_OBJECTS.MD b/v1-preparations/ESSENTIAL_GA_OBJECTS.MD index 7f0bf76ecb..68d9f51c69 100644 --- a/v1-preparations/ESSENTIAL_GA_OBJECTS.MD +++ b/v1-preparations/ESSENTIAL_GA_OBJECTS.MD @@ -19,14 +19,14 @@ newer provider versions. We will address these while working on the given object | RESOURCE MONITOR | ❌ | [#1990](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1990), [#1832](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1832), [#1821](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1821), [#1754](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1754), [#1716](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1716), [#1714](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1714), [#1624](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1624), [#1500](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1500), [#1175](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1175) | | ROLE | ❌ | - | | SECURITY INTEGRATION | ❌ | [#2719](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2719), [#2568](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2568), [#2177](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2177), [#1851](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1851), [#1773](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1773), [#1741](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1741), [#1637](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1637), [#1503](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1503), [#1498](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1498), [#1421](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1421), [#1224](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1224) | -| USER | ❌ | [#2662](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2662), [#1572](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1572), [#1535](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1535), [#1155](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1155) | +| USER | ❌ | [#2817](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2817), [#2662](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2662), [#1572](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1572), [#1535](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1535), [#1155](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1155) | | WAREHOUSE | ❌ | [#1844](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1844), [#1104](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1104) | | FUNCTION | ❌ | [#2735](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2735), [#2426](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2426), [#1479](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1479), [#1393](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1393), [#1208](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1208), [#1079](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1079) | | MASKING POLICY | ❌ | [#2236](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2236), [#2035](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2035), [#1799](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1799), [#1764](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1764), [#1656](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1656), [#1444](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1444), [#1422](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1422), [#1097](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1097) | | PROCEDURE | ❌ | [#2735](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2735), [#2623](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2623), [#2257](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2257), [#2146](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2146), [#1855](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1855), [#1695](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1695), [#1640](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1640), [#1195](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1195), [#1189](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1189), [#1178](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1178), [#1050](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1050) | | ROW ACCESS POLICY | ❌ | [#2053](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2053), [#1600](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1600), [#1151](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1151) | | SCHEMA | ❌ | [#2211](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2211), [#1243](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1243), [#506](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/506) | -| STAGE | ❌ | [#2505](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2505), [#1911](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1911), [#1903](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1903), [#1795](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1795), [#1705](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1705), [#1544](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1544), [#1491](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1491), [#1087](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1087), [#265](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/265) | +| STAGE | ❌ | [#2818](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2818), [#2505](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2505), [#1911](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1911), [#1903](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1903), [#1795](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1795), [#1705](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1705), [#1544](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1544), [#1491](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1491), [#1087](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1087), [#265](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/265) | | STREAM | ❌ | [#2413](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2413), [#2201](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2201), [#1150](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1150) | | STREAMLIT | ❌ | [#1933](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1933) | | TABLE | ❌ | [#2735](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2735), [#2733](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2733), [#2683](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2683), [#2676](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2676), [#2674](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2674), [#2629](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2629), [#2418](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2418), [#2415](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2415), [#2406](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2406), [#2236](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2236), [#2035](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2035), [#1799](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1799), [#1764](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1764), [#1600](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1600), [#1387](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1387), [#1272](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1272), [#1271](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1271), [#1248](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1248), [#1241](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1241), [#1146](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1146), [#1032](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/1032), [#420](https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/420) |