diff --git a/.github/workflows/golangci.yml b/.github/workflows/golangci.yml index c35ca4ca..dada129e 100644 --- a/.github/workflows/golangci.yml +++ b/.github/workflows/golangci.yml @@ -10,16 +10,16 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Setup Go uses: actions/setup-go@v5 with: - go-version: 1.23.x + go-version: 1.24.x - run: go mod vendor - name: Run golangci-lint - uses: golangci/golangci-lint-action@v6 + uses: golangci/golangci-lint-action@v8 with: - version: v1.61 + version: v2.4 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 1d98f821..d39ac1c6 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -28,7 +28,7 @@ jobs: name: Set up Go uses: actions/setup-go@v5 with: - go-version: '1.23' + go-version: '1.24' - name: Import GPG key id: import_gpg diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index b0cf3441..d985534f 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -24,7 +24,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v5 with: - go-version: '1.23' + go-version: '1.24' - name: test run: make test diff --git a/.golangci.yml b/.golangci.yml index bbe02476..c1ac0deb 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,8 +1,10 @@ +version: "2" + run: timeout: 5m -issues: - exclude-rules: - - linters: - - errcheck - text: "Error return value of `d.Set` is not checked" +linters: + settings: + errcheck: + exclude-functions: + - (*github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema.ResourceData).Set diff --git a/go.mod b/go.mod index 9e2dc272..72b5fda8 100644 --- a/go.mod +++ b/go.mod @@ -1,8 +1,8 @@ module github.com/terraform-providers/terraform-provider-postgresql -go 1.23.0 +go 1.24.0 -toolchain go1.23.2 +toolchain go1.24.2 require ( github.com/Azure/azure-sdk-for-go/sdk/azcore v1.11.1 diff --git a/postgresql/config.go b/postgresql/config.go index c2f1410c..d19ca762 100644 --- a/postgresql/config.go +++ b/postgresql/config.go @@ -302,7 +302,7 @@ func (c *Client) Connect() (*DBConnection, error) { } if err != nil { errString := strings.Replace(err.Error(), c.config.Password, "XXXX", 2) - return nil, fmt.Errorf("Error connecting to PostgreSQL server %s (scheme: %s): %s", c.config.Host, c.config.Scheme, errString) + return nil, fmt.Errorf("error connecting to PostgreSQL server %s (scheme: %s): %s", c.config.Host, c.config.Scheme, errString) } // We don't want to retain connection @@ -365,17 +365,17 @@ func openImpersonatedGCPDBConnection(ctx context.Context, dsn string, targetServ Scopes: []string{"https://www.googleapis.com/auth/sqlservice.admin"}, }) if err != nil { - return nil, fmt.Errorf("Error creating token source with service account impersonation of %s: %w", targetServiceAccountEmail, err) + return nil, fmt.Errorf("error creating token source with service account impersonation of %s: %w", targetServiceAccountEmail, err) } client, err := gcp.NewHTTPClient(gcp.DefaultTransport(), ts) if err != nil { - return nil, fmt.Errorf("Error creating HTTP client with service account impersonation of %s: %w", targetServiceAccountEmail, err) + return nil, fmt.Errorf("error creating HTTP client with service account impersonation of %s: %w", targetServiceAccountEmail, err) } certSource := cloudsql.NewCertSourceWithIAM(client, ts) opener := gcppostgres.URLOpener{CertSource: certSource} dbURL, err := url.Parse(dsn) if err != nil { - return nil, fmt.Errorf("Error parsing connection string: %w", err) + return nil, fmt.Errorf("error parsing connection string: %w", err) } return opener.OpenPostgresURL(ctx, dbURL) } diff --git a/postgresql/data_source_helpers.go b/postgresql/data_source_helpers.go index f5f00bea..7a12cc2b 100644 --- a/postgresql/data_source_helpers.go +++ b/postgresql/data_source_helpers.go @@ -18,9 +18,9 @@ const ( ) func applyPatternMatchingToQuery(patternMatchingTarget string, d *schema.ResourceData) []string { - likeAnyPatterns := d.Get("like_any_patterns").([]interface{}) - likeAllPatterns := d.Get("like_all_patterns").([]interface{}) - notLikeAllPatterns := d.Get("not_like_all_patterns").([]interface{}) + likeAnyPatterns := d.Get("like_any_patterns").([]any) + likeAllPatterns := d.Get("like_all_patterns").([]any) + notLikeAllPatterns := d.Get("not_like_all_patterns").([]any) regexPattern := d.Get("regex_pattern").(string) filters := []string{} @@ -46,7 +46,7 @@ func generatePatternMatchingString(patternMatchingTarget string, additionalQuery return patternMatchingFilter } -func applyTypeMatchingToQuery(objectKeyword string, objects []interface{}) string { +func applyTypeMatchingToQuery(objectKeyword string, objects []any) string { var typeFilter string if len(objects) > 0 { typeFilter = fmt.Sprintf("%s = %s", objectKeyword, generatePatternArrayString(objects, queryArrayKeywordAny)) @@ -55,7 +55,7 @@ func applyTypeMatchingToQuery(objectKeyword string, objects []interface{}) strin return typeFilter } -func generatePatternArrayString(patterns []interface{}, queryArrayKeyword string) string { +func generatePatternArrayString(patterns []any, queryArrayKeyword string) string { formattedPatterns := []string{} for _, pattern := range patterns { diff --git a/postgresql/data_source_postgresql_schemas.go b/postgresql/data_source_postgresql_schemas.go index 3aa8da5c..f70c4dbd 100644 --- a/postgresql/data_source_postgresql_schemas.go +++ b/postgresql/data_source_postgresql_schemas.go @@ -2,6 +2,7 @@ package postgresql import ( "fmt" + "log" "strconv" "strings" @@ -103,7 +104,11 @@ func dataSourcePostgreSQLSchemasRead(db *DBConnection, d *schema.ResourceData) e if err != nil { return err } - defer rows.Close() + defer func() { + if err := rows.Close(); err != nil { + log.Printf("error closing rows: %v", err) + } + }() schemas := []string{} for rows.Next() { @@ -124,9 +129,9 @@ func dataSourcePostgreSQLSchemasRead(db *DBConnection, d *schema.ResourceData) e func generateDataSourceSchemasID(d *schema.ResourceData, databaseName string) string { return strings.Join([]string{ databaseName, strconv.FormatBool(d.Get("include_system_schemas").(bool)), - generatePatternArrayString(d.Get("like_any_patterns").([]interface{}), queryArrayKeywordAny), - generatePatternArrayString(d.Get("like_all_patterns").([]interface{}), queryArrayKeywordAll), - generatePatternArrayString(d.Get("not_like_all_patterns").([]interface{}), queryArrayKeywordAll), + generatePatternArrayString(d.Get("like_any_patterns").([]any), queryArrayKeywordAny), + generatePatternArrayString(d.Get("like_all_patterns").([]any), queryArrayKeywordAll), + generatePatternArrayString(d.Get("not_like_all_patterns").([]any), queryArrayKeywordAll), d.Get("regex_pattern").(string), }, "_") } diff --git a/postgresql/data_source_postgresql_sequences.go b/postgresql/data_source_postgresql_sequences.go index 05a96e38..d4bbb2ca 100644 --- a/postgresql/data_source_postgresql_sequences.go +++ b/postgresql/data_source_postgresql_sequences.go @@ -2,6 +2,7 @@ package postgresql import ( "fmt" + "log" "strings" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -102,9 +103,13 @@ func dataSourcePostgreSQLSequencesRead(db *DBConnection, d *schema.ResourceData) if err != nil { return err } - defer rows.Close() + defer func() { + if err := rows.Close(); err != nil { + log.Printf("error closing rows: %v", err) + } + }() - sequences := make([]interface{}, 0) + sequences := make([]any, 0) for rows.Next() { var object_name string var schema_name string @@ -114,7 +119,7 @@ func dataSourcePostgreSQLSequencesRead(db *DBConnection, d *schema.ResourceData) return fmt.Errorf("could not scan sequence output for database: %w", err) } - result := make(map[string]interface{}) + result := make(map[string]any) result["object_name"] = object_name result["schema_name"] = schema_name result["data_type"] = data_type @@ -130,17 +135,17 @@ func dataSourcePostgreSQLSequencesRead(db *DBConnection, d *schema.ResourceData) func generateDataSourceSequencesID(d *schema.ResourceData, databaseName string) string { return strings.Join([]string{ databaseName, - generatePatternArrayString(d.Get("schemas").([]interface{}), queryArrayKeywordAny), - generatePatternArrayString(d.Get("like_any_patterns").([]interface{}), queryArrayKeywordAny), - generatePatternArrayString(d.Get("like_all_patterns").([]interface{}), queryArrayKeywordAll), - generatePatternArrayString(d.Get("not_like_all_patterns").([]interface{}), queryArrayKeywordAll), + generatePatternArrayString(d.Get("schemas").([]any), queryArrayKeywordAny), + generatePatternArrayString(d.Get("like_any_patterns").([]any), queryArrayKeywordAny), + generatePatternArrayString(d.Get("like_all_patterns").([]any), queryArrayKeywordAll), + generatePatternArrayString(d.Get("not_like_all_patterns").([]any), queryArrayKeywordAll), d.Get("regex_pattern").(string), }, "_") } func applySequenceDataSourceQueryFilters(query string, queryConcatKeyword string, d *schema.ResourceData) string { filters := []string{} - schemasTypeFilter := applyTypeMatchingToQuery(sequenceSchemaKeyword, d.Get("schemas").([]interface{})) + schemasTypeFilter := applyTypeMatchingToQuery(sequenceSchemaKeyword, d.Get("schemas").([]any)) if len(schemasTypeFilter) > 0 { filters = append(filters, schemasTypeFilter) } diff --git a/postgresql/data_source_postgresql_tables.go b/postgresql/data_source_postgresql_tables.go index e1899ac5..15849e96 100644 --- a/postgresql/data_source_postgresql_tables.go +++ b/postgresql/data_source_postgresql_tables.go @@ -2,6 +2,7 @@ package postgresql import ( "fmt" + "log" "strings" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -110,9 +111,13 @@ func dataSourcePostgreSQLTablesRead(db *DBConnection, d *schema.ResourceData) er if err != nil { return err } - defer rows.Close() + defer func() { + if err := rows.Close(); err != nil { + log.Printf("error closing rows: %v\n", err) + } + }() - tables := make([]interface{}, 0) + tables := make([]any, 0) for rows.Next() { var object_name string var schema_name string @@ -122,7 +127,7 @@ func dataSourcePostgreSQLTablesRead(db *DBConnection, d *schema.ResourceData) er return fmt.Errorf("could not scan table output for database: %w", err) } - result := make(map[string]interface{}) + result := make(map[string]any) result["object_name"] = object_name result["schema_name"] = schema_name result["table_type"] = table_type @@ -138,22 +143,22 @@ func dataSourcePostgreSQLTablesRead(db *DBConnection, d *schema.ResourceData) er func generateDataSourceTablesID(d *schema.ResourceData, databaseName string) string { return strings.Join([]string{ databaseName, - generatePatternArrayString(d.Get("schemas").([]interface{}), queryArrayKeywordAny), - generatePatternArrayString(d.Get("table_types").([]interface{}), queryArrayKeywordAny), - generatePatternArrayString(d.Get("like_any_patterns").([]interface{}), queryArrayKeywordAny), - generatePatternArrayString(d.Get("like_all_patterns").([]interface{}), queryArrayKeywordAll), - generatePatternArrayString(d.Get("not_like_all_patterns").([]interface{}), queryArrayKeywordAll), + generatePatternArrayString(d.Get("schemas").([]any), queryArrayKeywordAny), + generatePatternArrayString(d.Get("table_types").([]any), queryArrayKeywordAny), + generatePatternArrayString(d.Get("like_any_patterns").([]any), queryArrayKeywordAny), + generatePatternArrayString(d.Get("like_all_patterns").([]any), queryArrayKeywordAll), + generatePatternArrayString(d.Get("not_like_all_patterns").([]any), queryArrayKeywordAll), d.Get("regex_pattern").(string), }, "_") } func applyTableDataSourceQueryFilters(query string, queryConcatKeyword string, d *schema.ResourceData) string { filters := []string{} - schemasTypeFilter := applyTypeMatchingToQuery(tableSchemaKeyword, d.Get("schemas").([]interface{})) + schemasTypeFilter := applyTypeMatchingToQuery(tableSchemaKeyword, d.Get("schemas").([]any)) if len(schemasTypeFilter) > 0 { filters = append(filters, schemasTypeFilter) } - tableTypeFilter := applyTypeMatchingToQuery(tableTypeKeyword, d.Get("table_types").([]interface{})) + tableTypeFilter := applyTypeMatchingToQuery(tableTypeKeyword, d.Get("table_types").([]any)) if len(tableTypeFilter) > 0 { filters = append(filters, tableTypeFilter) } diff --git a/postgresql/helpers.go b/postgresql/helpers.go index 54e462d9..eee22efb 100644 --- a/postgresql/helpers.go +++ b/postgresql/helpers.go @@ -11,8 +11,8 @@ import ( "github.com/lib/pq" ) -func PGResourceFunc(fn func(*DBConnection, *schema.ResourceData) error) func(*schema.ResourceData, interface{}) error { - return func(d *schema.ResourceData, meta interface{}) error { +func PGResourceFunc(fn func(*DBConnection, *schema.ResourceData) error) func(*schema.ResourceData, any) error { + return func(d *schema.ResourceData, meta any) error { client := meta.(*Client) db, err := client.Connect() @@ -24,8 +24,8 @@ func PGResourceFunc(fn func(*DBConnection, *schema.ResourceData) error) func(*sc } } -func PGResourceExistsFunc(fn func(*DBConnection, *schema.ResourceData) (bool, error)) func(*schema.ResourceData, interface{}) (bool, error) { - return func(d *schema.ResourceData, meta interface{}) (bool, error) { +func PGResourceExistsFunc(fn func(*DBConnection, *schema.ResourceData) (bool, error)) func(*schema.ResourceData, any) (bool, error) { + return func(d *schema.ResourceData, meta any) (bool, error) { client := meta.(*Client) db, err := client.Connect() @@ -39,9 +39,9 @@ func PGResourceExistsFunc(fn func(*DBConnection, *schema.ResourceData) (bool, er // QueryAble is a DB connection (sql.DB/Tx) type QueryAble interface { - Exec(query string, args ...interface{}) (sql.Result, error) - Query(query string, args ...interface{}) (*sql.Rows, error) - QueryRow(query string, args ...interface{}) *sql.Row + Exec(query string, args ...any) (sql.Result, error) + Query(query string, args ...any) (*sql.Rows, error) + QueryRow(query string, args ...any) *sql.Row } // pqQuoteLiteral returns a string literal safe for inclusion in a PostgreSQL @@ -49,8 +49,8 @@ type QueryAble interface { // single quotes in SQL (i.e. fmt.Sprintf(`'%s'`, pqQuoteLiteral("str"))). See // quote_literal_internal() in postgresql/backend/utils/adt/quote.c:77. func pqQuoteLiteral(in string) string { - in = strings.Replace(in, `\`, `\\`, -1) - in = strings.Replace(in, `'`, `''`, -1) + in = strings.ReplaceAll(in, `\`, `\\`) + in = strings.ReplaceAll(in, `'`, `''`) return in } @@ -107,7 +107,7 @@ func grantRoleMembership(db QueryAble, role, member string) (bool, error) { sql := fmt.Sprintf("GRANT %s TO %s", pq.QuoteIdentifier(role), pq.QuoteIdentifier(member)) if _, err := db.Exec(sql); err != nil { - return false, fmt.Errorf("Error granting role %s to %s: %w", role, member, err) + return false, fmt.Errorf("error granting role %s to %s: %w", role, member, err) } return true, nil } @@ -131,7 +131,7 @@ func revokeRoleMembership(db QueryAble, role, member string) (bool, error) { sql := fmt.Sprintf("REVOKE %s FROM %s", pq.QuoteIdentifier(role), pq.QuoteIdentifier(member)) if _, err := db.Exec(sql); err != nil { - return false, fmt.Errorf("Error revoking role %s from %s: %w", role, member, err) + return false, fmt.Errorf("error revoking role %s from %s: %w", role, member, err) } return true, nil } @@ -295,7 +295,7 @@ func resourcePrivilegesEqual(granted *schema.Set, d *schema.ResourceData) bool { // implicit check: e.g. for object_type schema -> ALL == ["CREATE", "USAGE"] log.Printf("The wanted privilege is 'ALL'. therefore, we will check if the current privileges are ALL implicitly") - implicits := []interface{}{} + implicits := []any{} for _, p := range allowedPrivileges[objectType] { if p != "ALL" { implicits = append(implicits, p) @@ -306,7 +306,7 @@ func resourcePrivilegesEqual(granted *schema.Set, d *schema.ResourceData) bool { } func pgArrayToSet(arr pq.ByteaArray) *schema.Set { - s := make([]interface{}, len(arr)) + s := make([]any, len(arr)) for i, v := range arr { s[i] = string(v) } @@ -314,7 +314,7 @@ func pgArrayToSet(arr pq.ByteaArray) *schema.Set { } func stringSliceToSet(slice []string) *schema.Set { - s := make([]interface{}, len(slice)) + s := make([]any, len(slice)) for i, v := range slice { s[i] = v } @@ -459,12 +459,12 @@ func getDatabase(d *schema.ResourceData, databaseName string) string { func getDatabaseOwner(db QueryAble, database string) (string, error) { dbQueryString := "$1" - dbQueryValues := []interface{}{database} + dbQueryValues := []any{database} // Empty means current DB if database == "" { dbQueryString = "current_database()" - dbQueryValues = []interface{}{} + dbQueryValues = []any{} } query := fmt.Sprintf(` @@ -599,8 +599,8 @@ func pgLockDatabase(txn *sql.Tx, database string) error { return nil } -func arrayDifference(a, b []interface{}) (diff []interface{}) { - m := make(map[interface{}]bool) +func arrayDifference(a, b []any) (diff []any) { + m := make(map[any]bool) for _, item := range b { m[item] = true @@ -614,8 +614,8 @@ func arrayDifference(a, b []interface{}) (diff []interface{}) { return } -func isUniqueArr(arr []interface{}) (interface{}, bool) { - keys := make(map[interface{}]bool, len(arr)) +func isUniqueArr(arr []any) (any, bool) { + keys := make(map[any]bool, len(arr)) for _, entry := range arr { if _, value := keys[entry]; value { return entry, false diff --git a/postgresql/helpers_test.go b/postgresql/helpers_test.go index 57066f2e..a7d1fc12 100644 --- a/postgresql/helpers_test.go +++ b/postgresql/helpers_test.go @@ -103,7 +103,7 @@ func TestArePrivilegesEqual(t *testing.T) { } } -func buildPrivilegesSet(grants ...interface{}) *schema.Set { +func buildPrivilegesSet(grants ...any) *schema.Set { return schema.NewSet(schema.HashString, grants) } diff --git a/postgresql/model_pg_function.go b/postgresql/model_pg_function.go index 6998d382..77b3e07d 100644 --- a/postgresql/model_pg_function.go +++ b/postgresql/model_pg_function.go @@ -70,10 +70,10 @@ func (pgFunction *PGFunction) FromResourceData(d *schema.ResourceData) error { argOutput := "void" if args, ok := d.GetOk(funcArgAttr); ok { - args := args.([]interface{}) + args := args.([]any) for _, arg := range args { - arg := arg.(map[string]interface{}) + arg := arg.(map[string]any) var pgArg PGFunctionArg diff --git a/postgresql/model_pg_function_test.go b/postgresql/model_pg_function_test.go index 7ed92ef4..072d96da 100644 --- a/postgresql/model_pg_function_test.go +++ b/postgresql/model_pg_function_test.go @@ -243,7 +243,7 @@ func mockFunctionResourceData(t *testing.T, obj PGFunction) *schema.ResourceData state.ID = "" // Build the attribute map from ForemanModel - attributes := make(map[string]interface{}) + attributes := make(map[string]any) attributes["name"] = obj.Name attributes["returns"] = obj.Returns @@ -254,10 +254,10 @@ func mockFunctionResourceData(t *testing.T, obj PGFunction) *schema.ResourceData attributes["parallel"] = obj.Parallel attributes["volatility"] = obj.Volatility - var args []interface{} + var args []any for _, a := range obj.Args { - args = append(args, map[string]interface{}{ + args = append(args, map[string]any{ "type": a.Type, "name": a.Name, "mode": a.Mode, diff --git a/postgresql/provider.go b/postgresql/provider.go index 8bc7546d..778778be 100644 --- a/postgresql/provider.go +++ b/postgresql/provider.go @@ -229,7 +229,7 @@ func Provider() *schema.Provider { } } -func validateExpectedVersion(v interface{}, key string) (warnings []string, errors []error) { +func validateExpectedVersion(v any, key string) (warnings []string, errors []error) { if _, err := semver.ParseTolerant(v.(string)); err != nil { errors = append(errors, fmt.Errorf("invalid version (%q): %w", v.(string), err)) } @@ -300,7 +300,11 @@ func createGoogleCredsFileIfNeeded() error { if err != nil { return fmt.Errorf("could not create temporary file: %w", err) } - defer tmpFile.Close() + defer func() { + if err := tmpFile.Close(); err != nil { + fmt.Printf("could not close temporary file: %v", err) + } + }() _, err = tmpFile.WriteString(rawGoogleCredentials) if err != nil { @@ -326,7 +330,7 @@ func acquireAzureOauthToken(tenantId string) (string, error) { return token.Token, nil } -func providerConfigure(d *schema.ResourceData) (interface{}, error) { +func providerConfigure(d *schema.ResourceData) (any, error) { var sslMode string if sslModeRaw, ok := d.GetOk("sslmode"); ok { sslMode = sslModeRaw.(string) @@ -385,7 +389,7 @@ func providerConfigure(d *schema.ResourceData) (interface{}, error) { } if value, ok := d.GetOk("clientcert"); ok { - if spec, ok := value.([]interface{})[0].(map[string]interface{}); ok { + if spec, ok := value.([]any)[0].(map[string]interface{}); ok { config.SSLClientCert = &ClientCertificateConfig{ CertificatePath: spec["cert"].(string), KeyPath: spec["key"].(string), diff --git a/postgresql/provider_test.go b/postgresql/provider_test.go index 44714db4..b67d9fe8 100644 --- a/postgresql/provider_test.go +++ b/postgresql/provider_test.go @@ -26,7 +26,7 @@ func TestProvider(t *testing.T) { } func TestProvider_impl(t *testing.T) { - var _ *schema.Provider = Provider() + var _ = Provider() } func testAccPreCheck(t *testing.T) { diff --git a/postgresql/resource_postgresql_database.go b/postgresql/resource_postgresql_database.go index 6cabadf7..00036290 100644 --- a/postgresql/resource_postgresql_database.go +++ b/postgresql/resource_postgresql_database.go @@ -228,7 +228,7 @@ func createDatabase(db *DBConnection, d *schema.ResourceData) error { sql := b.String() if _, err := db.Exec(sql); err != nil { - return fmt.Errorf("Error creating database %q: %w", dbName, err) + return fmt.Errorf("error creating database %q: %w", dbName, err) } // Set err outside of the return so that the deferred revoke can override err @@ -268,7 +268,7 @@ func resourcePostgreSQLDatabaseDelete(db *DBConnection, d *schema.ResourceData) // Template databases must have this attribute cleared before // they can be dropped. if err := doSetDBIsTemplate(db, dbName, false); err != nil { - return fmt.Errorf("Error updating database IS_TEMPLATE during DROP DATABASE: %w", err) + return fmt.Errorf("error updating database IS_TEMPLATE during DROP DATABASE: %w", err) } } } @@ -289,7 +289,7 @@ func resourcePostgreSQLDatabaseDelete(db *DBConnection, d *schema.ResourceData) sql := fmt.Sprintf("DROP DATABASE %s %s", pq.QuoteIdentifier(dbName), dropWithForce) if _, err := db.Exec(sql); err != nil { - return fmt.Errorf("Error dropping database: %w", err) + return fmt.Errorf("error dropping database: %w", err) } d.SetId("") @@ -322,7 +322,7 @@ func resourcePostgreSQLDatabaseReadImpl(db *DBConnection, d *schema.ResourceData d.SetId("") return nil case err != nil: - return fmt.Errorf("Error reading database: %w", err) + return fmt.Errorf("error reading database: %w", err) } var dbEncoding, dbCollation, dbCType, dbTablespaceName string @@ -354,7 +354,7 @@ func resourcePostgreSQLDatabaseReadImpl(db *DBConnection, d *schema.ResourceData d.SetId("") return nil case err != nil: - return fmt.Errorf("Error reading database: %w", err) + return fmt.Errorf("error reading database: %w", err) } d.Set(dbNameAttr, dbName) @@ -375,7 +375,7 @@ func resourcePostgreSQLDatabaseReadImpl(db *DBConnection, d *schema.ResourceData dbSQL := fmt.Sprintf(dbSQLFmt, "d.datallowconn") err = db.QueryRow(dbSQL, dbId).Scan(&dbAllowConns) if err != nil { - return fmt.Errorf("Error reading ALLOW_CONNECTIONS property for DATABASE: %w", err) + return fmt.Errorf("error reading ALLOW_CONNECTIONS property for DATABASE: %w", err) } d.Set(dbAllowConnsAttr, dbAllowConns) @@ -386,7 +386,7 @@ func resourcePostgreSQLDatabaseReadImpl(db *DBConnection, d *schema.ResourceData dbSQL := fmt.Sprintf(dbSQLFmt, "d.datistemplate") err = db.QueryRow(dbSQL, dbId).Scan(&dbIsTemplate) if err != nil { - return fmt.Errorf("Error reading IS_TEMPLATE property for DATABASE: %w", err) + return fmt.Errorf("error reading IS_TEMPLATE property for DATABASE: %w", err) } d.Set(dbIsTemplateAttr, dbIsTemplate) @@ -438,12 +438,12 @@ func setDBName(db QueryAble, d *schema.ResourceData) error { o := oraw.(string) n := nraw.(string) if n == "" { - return errors.New("Error setting database name to an empty string") + return errors.New("error setting database name to an empty string") } sql := fmt.Sprintf("ALTER DATABASE %s RENAME TO %s", pq.QuoteIdentifier(o), pq.QuoteIdentifier(n)) if _, err := db.Exec(sql); err != nil { - return fmt.Errorf("Error updating database name: %w", err) + return fmt.Errorf("error updating database name: %w", err) } d.SetId(n) @@ -482,7 +482,7 @@ func setDBOwner(db *DBConnection, d *schema.ResourceData) error { sql := fmt.Sprintf("ALTER DATABASE %s OWNER TO %s", pq.QuoteIdentifier(dbName), pq.QuoteIdentifier(owner)) if _, err := db.Exec(sql); err != nil { - return fmt.Errorf("Error updating database OWNER: %w", err) + return fmt.Errorf("error updating database OWNER: %w", err) } return err @@ -513,7 +513,7 @@ func setAlterOwnership(db *DBConnection, d *schema.ResourceData) error { currentOwner, err := getDatabaseOwner(db, dbName) if err != nil { - return fmt.Errorf("Error getting current database OWNER: %w", err) + return fmt.Errorf("error getting current database OWNER: %w", err) } newOwner := d.Get(dbOwnerAttr).(string) @@ -533,7 +533,7 @@ func setAlterOwnership(db *DBConnection, d *schema.ResourceData) error { } sql := fmt.Sprintf("REASSIGN OWNED BY %s TO %s", pq.QuoteIdentifier(currentOwner), pq.QuoteIdentifier(newOwner)) if _, err := lockTxn.Exec(sql); err != nil { - return fmt.Errorf("Error reassigning objects owned by '%s': %w", currentOwner, err) + return fmt.Errorf("error reassigning objects owned by '%s': %w", currentOwner, err) } if err := lockTxn.Commit(); err != nil { @@ -557,7 +557,7 @@ func setDBTablespace(db QueryAble, d *schema.ResourceData) error { } if _, err := db.Exec(sql); err != nil { - return fmt.Errorf("Error updating database TABLESPACE: %w", err) + return fmt.Errorf("error updating database TABLESPACE: %w", err) } return nil @@ -572,7 +572,7 @@ func setDBConnLimit(db QueryAble, d *schema.ResourceData) error { dbName := d.Get(dbNameAttr).(string) sql := fmt.Sprintf("ALTER DATABASE %s CONNECTION LIMIT = %d", pq.QuoteIdentifier(dbName), connLimit) if _, err := db.Exec(sql); err != nil { - return fmt.Errorf("Error updating database CONNECTION LIMIT: %w", err) + return fmt.Errorf("error updating database CONNECTION LIMIT: %w", err) } return nil @@ -591,7 +591,7 @@ func setDBAllowConns(db *DBConnection, d *schema.ResourceData) error { dbName := d.Get(dbNameAttr).(string) sql := fmt.Sprintf("ALTER DATABASE %s ALLOW_CONNECTIONS %t", pq.QuoteIdentifier(dbName), allowConns) if _, err := db.Exec(sql); err != nil { - return fmt.Errorf("Error updating database ALLOW_CONNECTIONS: %w", err) + return fmt.Errorf("error updating database ALLOW_CONNECTIONS: %w", err) } return nil @@ -603,7 +603,7 @@ func setDBIsTemplate(db *DBConnection, d *schema.ResourceData) error { } if err := doSetDBIsTemplate(db, d.Get(dbNameAttr).(string), d.Get(dbIsTemplateAttr).(bool)); err != nil { - return fmt.Errorf("Error updating database IS_TEMPLATE: %w", err) + return fmt.Errorf("error updating database IS_TEMPLATE: %w", err) } return nil @@ -616,7 +616,7 @@ func doSetDBIsTemplate(db *DBConnection, dbName string, isTemplate bool) error { sql := fmt.Sprintf("ALTER DATABASE %s IS_TEMPLATE %t", pq.QuoteIdentifier(dbName), isTemplate) if _, err := db.Exec(sql); err != nil { - return fmt.Errorf("Error updating database IS_TEMPLATE: %w", err) + return fmt.Errorf("error updating database IS_TEMPLATE: %w", err) } return nil @@ -629,7 +629,7 @@ func terminateBConnections(db *DBConnection, dbName string) error { alterSql := fmt.Sprintf("ALTER DATABASE %s ALLOW_CONNECTIONS false", pq.QuoteIdentifier(dbName)) if _, err := db.Exec(alterSql); err != nil { - return fmt.Errorf("Error blocking connections to database: %w", err) + return fmt.Errorf("error blocking connections to database: %w", err) } } pid := "procpid" @@ -638,7 +638,7 @@ func terminateBConnections(db *DBConnection, dbName string) error { } terminateSql = fmt.Sprintf("SELECT pg_terminate_backend(%s) FROM pg_stat_activity WHERE datname = '%s' AND %s <> pg_backend_pid()", pid, dbName, pid) if _, err := db.Exec(terminateSql); err != nil { - return fmt.Errorf("Error terminating database connections: %w", err) + return fmt.Errorf("error terminating database connections: %w", err) } return nil diff --git a/postgresql/resource_postgresql_database_test.go b/postgresql/resource_postgresql_database_test.go index 6e8c9715..befdfdea 100644 --- a/postgresql/resource_postgresql_database_test.go +++ b/postgresql/resource_postgresql_database_test.go @@ -197,8 +197,6 @@ func TestAccPostgresqlDatabase_GrantOwner(t *testing.T) { skipIfNotAcc(t) config := getTestConfig(t) - dsn := config.connStr("postgres") - var stateConfig = ` resource postgresql_role "test_owner" { name = "test_owner" @@ -221,7 +219,7 @@ resource postgresql_database "test_db" { resource.TestCheckResourceAttr("postgresql_database.test_db", "owner", "test_owner"), // check if connected user does not have test_owner granted anymore. - checkUserMembership(t, dsn, config.Username, "test_owner", false), + checkUserMembership(t, config.Username, "test_owner", false), ), }, }, @@ -263,7 +261,7 @@ resource postgresql_database "test_db" { resource.TestCheckResourceAttr("postgresql_database.test_db", "owner", "test_owner"), // check if connected user still have test_owner granted. - checkUserMembership(t, dsn, config.Username, "test_owner", true), + checkUserMembership(t, config.Username, "test_owner", true), ), }, }, @@ -343,7 +341,7 @@ resource postgresql_database "test_db" { } func checkUserMembership( - t *testing.T, dsn, member, role string, shouldHaveRole bool, + t *testing.T, member, role string, shouldHaveRole bool, ) resource.TestCheckFunc { return func(s *terraform.State) error { client := testAccProvider.Meta().(*Client) @@ -391,7 +389,7 @@ func checkTableOwnership( if err != nil { t.Fatalf("could not create connection pool: %v", err) } - defer db.Close() + defer closeDB(t, db) var _rez int @@ -406,7 +404,7 @@ func checkTableOwnership( "User %s should be owner of %s but is not", owner, tableName, ) case err != nil: - t.Fatalf("Error checking table ownership. %v", err) + t.Fatalf("error checking table ownership. %v", err) } @@ -426,7 +424,7 @@ func testAccCheckPostgresqlDatabaseDestroy(s *terraform.State) error { exists, err := checkDatabaseExists(client, rs.Primary.ID) if err != nil { - return fmt.Errorf("Error checking db %s", err) + return fmt.Errorf("error checking db %s", err) } if exists { @@ -452,7 +450,7 @@ func testAccCheckPostgresqlDatabaseExists(n string) resource.TestCheckFunc { exists, err := checkDatabaseExists(client, rs.Primary.ID) if err != nil { - return fmt.Errorf("Error checking db %s", err) + return fmt.Errorf("error checking db %s", err) } if !exists { @@ -474,7 +472,7 @@ func checkDatabaseExists(client *Client, dbName string) (bool, error) { case err == sql.ErrNoRows: return false, nil case err != nil: - return false, fmt.Errorf("Error reading info about database: %s", err) + return false, fmt.Errorf("error reading info about database: %s", err) } return true, nil diff --git a/postgresql/resource_postgresql_default_privileges.go b/postgresql/resource_postgresql_default_privileges.go index d7eb066d..fe5013ae 100644 --- a/postgresql/resource_postgresql_default_privileges.go +++ b/postgresql/resource_postgresql_default_privileges.go @@ -226,7 +226,7 @@ func readRoleDefaultPrivileges(txn *sql.Tx, d *schema.ResourceData) error { } var query string - var queryArgs []interface{} + var queryArgs []any if pgSchema != "" { query = `SELECT array_agg(prtype) FROM ( @@ -236,7 +236,7 @@ func readRoleDefaultPrivileges(txn *sql.Tx, d *schema.ResourceData) error { JOIN pg_namespace ON pg_namespace.oid = namespace WHERE grantee_oid = $1 AND nspname = $2 AND pg_get_userbyid(grantor_oid) = $4; ` - queryArgs = []interface{}{roleOID, pgSchema, objectTypes[objectType], owner} + queryArgs = []any{roleOID, pgSchema, objectTypes[objectType], owner} } else { query = `SELECT array_agg(prtype) FROM ( SELECT defaclnamespace, (aclexplode(defaclacl)).* FROM pg_default_acl @@ -244,7 +244,7 @@ func readRoleDefaultPrivileges(txn *sql.Tx, d *schema.ResourceData) error { ) AS t (namespace, grantor_oid, grantee_oid, prtype, grantable) WHERE grantee_oid = $1 AND namespace = 0 AND pg_get_userbyid(grantor_oid) = $3; ` - queryArgs = []interface{}{roleOID, objectTypes[objectType], owner} + queryArgs = []any{roleOID, objectTypes[objectType], owner} } // This query aggregates the list of default privileges type (prtype) diff --git a/postgresql/resource_postgresql_default_privileges_test.go b/postgresql/resource_postgresql_default_privileges_test.go index 34005689..9d5fb93c 100644 --- a/postgresql/resource_postgresql_default_privileges_test.go +++ b/postgresql/resource_postgresql_default_privileges_test.go @@ -23,10 +23,7 @@ func TestAccPostgresqlDefaultPrivileges(t *testing.T) { // Set default privileges to the test role then to public (i.e.: everyone) for _, role := range []string{roleName, "public"} { t.Run(role, func(t *testing.T) { - withGrant := true - if role == "public" { - withGrant = false - } + withGrant := (role != "public") // We set PGUSER as owner as he will create the test table var tfConfig = fmt.Sprintf(` @@ -135,7 +132,6 @@ func TestAccPostgresqlDefaultPrivileges_GrantOwner(t *testing.T) { defer teardown() config := getTestConfig(t) - dsn := config.connStr("postgres") dbName, roleName := getTestDBNames(dbSuffix) // We set PGUSER as owner as he will create the test table @@ -188,7 +184,7 @@ resource "postgresql_default_privileges" "test_ro" { resource.TestCheckResourceAttr("postgresql_default_privileges.test_ro", "privileges.0", "SELECT"), // check if connected user does not have test_owner granted anymore. - checkUserMembership(t, dsn, config.Username, "test_owner", false), + checkUserMembership(t, config.Username, "test_owner", false), ), }, }, diff --git a/postgresql/resource_postgresql_extension.go b/postgresql/resource_postgresql_extension.go index b356b497..2e043956 100644 --- a/postgresql/resource_postgresql_extension.go +++ b/postgresql/resource_postgresql_extension.go @@ -111,7 +111,7 @@ func resourcePostgreSQLExtensionCreate(db *DBConnection, d *schema.ResourceData) } if err = txn.Commit(); err != nil { - return fmt.Errorf("Error creating extension: %w", err) + return fmt.Errorf("error creating extension: %w", err) } d.SetId(generateExtensionID(d, databaseName)) @@ -192,7 +192,7 @@ func resourcePostgreSQLExtensionReadImpl(db *DBConnection, d *schema.ResourceDat d.SetId("") return nil case err != nil: - return fmt.Errorf("Error reading extension: %w", err) + return fmt.Errorf("error reading extension: %w", err) } d.Set(extNameAttr, extName) @@ -232,7 +232,7 @@ func resourcePostgreSQLExtensionDelete(db *DBConnection, d *schema.ResourceData) } if err = txn.Commit(); err != nil { - return fmt.Errorf("Error deleting extension: %w", err) + return fmt.Errorf("error deleting extension: %w", err) } d.SetId("") @@ -266,7 +266,7 @@ func resourcePostgreSQLExtensionUpdate(db *DBConnection, d *schema.ResourceData) } if err = txn.Commit(); err != nil { - return fmt.Errorf("Error updating extension: %w", err) + return fmt.Errorf("error updating extension: %w", err) } return resourcePostgreSQLExtensionReadImpl(db, d) @@ -281,13 +281,13 @@ func setExtSchema(txn *sql.Tx, d *schema.ResourceData) error { _, nraw := d.GetChange(extSchemaAttr) n := nraw.(string) if n == "" { - return errors.New("Error setting extension name to an empty string") + return errors.New("error setting extension name to an empty string") } sql := fmt.Sprintf("ALTER EXTENSION %s SET SCHEMA %s", pq.QuoteIdentifier(extName), pq.QuoteIdentifier(n)) if _, err := txn.Exec(sql); err != nil { - return fmt.Errorf("Error updating extension SCHEMA: %w", err) + return fmt.Errorf("error updating extension SCHEMA: %w", err) } return nil @@ -311,7 +311,7 @@ func setExtVersion(txn *sql.Tx, d *schema.ResourceData) error { sql := b.String() if _, err := txn.Exec(sql); err != nil { - return fmt.Errorf("Error updating extension version: %w", err) + return fmt.Errorf("error updating extension version: %w", err) } return nil diff --git a/postgresql/resource_postgresql_extension_test.go b/postgresql/resource_postgresql_extension_test.go index 4f21b5d8..118a349d 100644 --- a/postgresql/resource_postgresql_extension_test.go +++ b/postgresql/resource_postgresql_extension_test.go @@ -61,7 +61,7 @@ func testAccCheckPostgresqlExtensionDestroy(s *terraform.State) error { exists, err := checkExtensionExists(txn, getExtensionNameFromID(rs.Primary.ID)) if err != nil { - return fmt.Errorf("Error checking extension %s", err) + return fmt.Errorf("error checking extension %s", err) } if exists { @@ -103,7 +103,7 @@ func testAccCheckPostgresqlExtensionExists(n string) resource.TestCheckFunc { exists, err := checkExtensionExists(txn, extName) if err != nil { - return fmt.Errorf("Error checking extension %s", err) + return fmt.Errorf("error checking extension %s", err) } if !exists { @@ -161,7 +161,7 @@ func checkExtensionExists(txn *sql.Tx, extensionName string) (bool, error) { case err == sql.ErrNoRows: return false, nil case err != nil: - return false, fmt.Errorf("Error reading info about extension: %s", err) + return false, fmt.Errorf("error reading info about extension: %s", err) } return true, nil @@ -301,7 +301,7 @@ func testAccCheckExtensionDependency(extName string) resource.TestCheckFunc { exists, err := checkExtensionExists(txn, extName) if err != nil { - return fmt.Errorf("Error checking extension %s", err) + return fmt.Errorf("error checking extension %s", err) } if !exists { return fmt.Errorf("Extension %s not found", extName) diff --git a/postgresql/resource_postgresql_function.go b/postgresql/resource_postgresql_function.go index ee790b2d..c6a1dd55 100644 --- a/postgresql/resource_postgresql_function.go +++ b/postgresql/resource_postgresql_function.go @@ -129,7 +129,7 @@ func resourcePostgreSQLFunction() *schema.Resource { DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool { return normalizeFunctionBody(new) == old }, - StateFunc: func(val interface{}) string { + StateFunc: func(val any) string { return normalizeFunctionBody(val.(string)) }, }, @@ -279,7 +279,7 @@ func resourcePostgreSQLFunctionReadImpl(db *DBConnection, d *schema.ResourceData d.SetId("") return nil case err != nil: - return fmt.Errorf("Error reading function: %w", err) + return fmt.Errorf("error reading function: %w", err) } if err := txn.Commit(); err != nil { @@ -293,10 +293,10 @@ func resourcePostgreSQLFunctionReadImpl(db *DBConnection, d *schema.ResourceData return err } - var args []map[string]interface{} + var args []map[string]any for _, a := range pgFunction.Args { - args = append(args, map[string]interface{}{ + args = append(args, map[string]any{ funcArgTypeAttr: a.Type, funcArgNameAttr: a.Name, funcArgModeAttr: a.Mode, @@ -541,5 +541,5 @@ func quoteSignature(s string) (signature string, err error) { return fmt.Sprintf("%s.%s(%s)", pq.QuoteIdentifier(schemaName), pq.QuoteIdentifier(name), args), nil } - return "", fmt.Errorf("Incorrect signature format \"%s\". The expected format is schema.function_name(arguments)", s) + return "", fmt.Errorf("incorrect signature format \"%s\". The expected format is schema.function_name(arguments)", s) } diff --git a/postgresql/resource_postgresql_function_test.go b/postgresql/resource_postgresql_function_test.go index d9a351f0..325d68a4 100644 --- a/postgresql/resource_postgresql_function_test.go +++ b/postgresql/resource_postgresql_function_test.go @@ -245,7 +245,7 @@ func testAccCheckPostgresqlFunctionExists(n string, database string) resource.Te exists, err := checkFunctionExists(txn, signature) if err != nil { - return fmt.Errorf("Error checking function %s", err) + return fmt.Errorf("error checking function %s", err) } if !exists { @@ -279,7 +279,7 @@ func testAccCheckPostgresqlFunctionDestroy(s *terraform.State) error { exists, err := checkFunctionExists(txn, functionSignature) if err != nil { - return fmt.Errorf("Error checking function %s", err) + return fmt.Errorf("error checking function %s", err) } if exists { @@ -297,7 +297,7 @@ func checkFunctionExists(txn *sql.Tx, signature string) (bool, error) { case err == sql.ErrNoRows: return false, nil case err != nil: - return false, fmt.Errorf("Error reading info about function: %s", err) + return false, fmt.Errorf("error reading info about function: %s", err) } return _rez, nil diff --git a/postgresql/resource_postgresql_grant.go b/postgresql/resource_postgresql_grant.go index fb93c479..274579d9 100644 --- a/postgresql/resource_postgresql_grant.go +++ b/postgresql/resource_postgresql_grant.go @@ -34,7 +34,7 @@ var objectTypes = map[string]string{ "schema": "n", } -type ResourceSchemeGetter func(string) interface{} +type ResourceSchemeGetter func(string) any func resourcePostgreSQLGrant() *schema.Resource { return &schema.Resource{ @@ -708,7 +708,7 @@ func revokeRolePrivileges(txn *sql.Tx, d *schema.ResourceData, usePrevious bool) getter := d.Get if usePrevious { - getter = func(name string) interface{} { + getter = func(name string) any { if d.HasChange(name) { old, _ := d.GetChange(name) return old diff --git a/postgresql/resource_postgresql_grant_role.go b/postgresql/resource_postgresql_grant_role.go index f7820f63..d854d775 100644 --- a/postgresql/resource_postgresql_grant_role.go +++ b/postgresql/resource_postgresql_grant_role.go @@ -130,7 +130,7 @@ func readGrantRole(db QueryAble, d *schema.ResourceData) error { grantRoleID := d.Id() - values := []interface{}{ + values := []any{ &roleName, &grantRoleName, &withAdminOption, @@ -143,7 +143,7 @@ func readGrantRole(db QueryAble, d *schema.ResourceData) error { d.SetId("") return nil case err != nil: - return fmt.Errorf("Error reading grant role: %w", err) + return fmt.Errorf("error reading grant role: %w", err) } d.Set("role", roleName) diff --git a/postgresql/resource_postgresql_grant_role_test.go b/postgresql/resource_postgresql_grant_role_test.go index ed25777a..407f6ff3 100644 --- a/postgresql/resource_postgresql_grant_role_test.go +++ b/postgresql/resource_postgresql_grant_role_test.go @@ -17,18 +17,18 @@ func TestCreateGrantRoleQuery(t *testing.T) { var grantRoleName = "bar" cases := []struct { - resource map[string]interface{} + resource map[string]any expected string }{ { - resource: map[string]interface{}{ + resource: map[string]any{ "role": roleName, "grant_role": grantRoleName, }, expected: fmt.Sprintf("GRANT %s TO %s", pq.QuoteIdentifier(grantRoleName), pq.QuoteIdentifier(roleName)), }, { - resource: map[string]interface{}{ + resource: map[string]any{ "role": roleName, "grant_role": grantRoleName, "with_admin_option": false, @@ -36,7 +36,7 @@ func TestCreateGrantRoleQuery(t *testing.T) { expected: fmt.Sprintf("GRANT %s TO %s", pq.QuoteIdentifier(grantRoleName), pq.QuoteIdentifier(roleName)), }, { - resource: map[string]interface{}{ + resource: map[string]any{ "role": roleName, "grant_role": grantRoleName, "with_admin_option": true, @@ -48,7 +48,7 @@ func TestCreateGrantRoleQuery(t *testing.T) { for _, c := range cases { out := createGrantRoleQuery(schema.TestResourceDataRaw(t, resourcePostgreSQLGrantRole().Schema, c.resource)) if out != c.expected { - t.Fatalf("Error matching output and expected: %#v vs %#v", out, c.expected) + t.Fatalf("error matching output and expected: %#v vs %#v", out, c.expected) } } } @@ -60,23 +60,23 @@ func TestRevokeRoleQuery(t *testing.T) { expected := fmt.Sprintf("REVOKE %s FROM %s", pq.QuoteIdentifier(grantRoleName), pq.QuoteIdentifier(roleName)) cases := []struct { - resource map[string]interface{} + resource map[string]any }{ { - resource: map[string]interface{}{ + resource: map[string]any{ "role": roleName, "grant_role": grantRoleName, }, }, { - resource: map[string]interface{}{ + resource: map[string]any{ "role": roleName, "grant_role": grantRoleName, "with_admin_option": false, }, }, { - resource: map[string]interface{}{ + resource: map[string]any{ "role": roleName, "grant_role": grantRoleName, "with_admin_option": true, @@ -87,7 +87,7 @@ func TestRevokeRoleQuery(t *testing.T) { for _, c := range cases { out := createRevokeRoleQuery(schema.TestResourceDataRaw(t, resourcePostgreSQLGrantRole().Schema, c.resource)) if out != expected { - t.Fatalf("Error matching output and expected: %#v vs %#v", out, expected) + t.Fatalf("error matching output and expected: %#v vs %#v", out, expected) } } } @@ -145,7 +145,7 @@ func checkGrantRole(t *testing.T, dsn, role string, grantRole string, withAdmin if err != nil { t.Fatalf("could to create connection pool: %v", err) } - defer db.Close() + defer closeDB(t, db) var _rez int err = db.QueryRow(` diff --git a/postgresql/resource_postgresql_grant_test.go b/postgresql/resource_postgresql_grant_test.go index 4b62180b..b9808b22 100644 --- a/postgresql/resource_postgresql_grant_test.go +++ b/postgresql/resource_postgresql_grant_test.go @@ -16,9 +16,9 @@ import ( func TestCreateGrantQuery(t *testing.T) { var databaseName = "foo" var roleName = "bar" - var tableObjects = []interface{}{"o1", "o2"} - var tableColumns = []interface{}{"col1", "col2"} - var fdwObjects = []interface{}{"baz"} + var tableObjects = []any{"o1", "o2"} + var tableColumns = []any{"col1", "col2"} + var fdwObjects = []any{"baz"} cases := []struct { resource *schema.ResourceData @@ -26,7 +26,7 @@ func TestCreateGrantQuery(t *testing.T) { expected string }{ { - resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]interface{}{ + resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]any{ "object_type": "table", "schema": databaseName, "role": roleName, @@ -35,7 +35,7 @@ func TestCreateGrantQuery(t *testing.T) { expected: fmt.Sprintf("GRANT SELECT ON ALL TABLES IN SCHEMA %s TO %s", pq.QuoteIdentifier(databaseName), pq.QuoteIdentifier(roleName)), }, { - resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]interface{}{ + resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]any{ "object_type": "sequence", "schema": databaseName, "role": roleName, @@ -44,7 +44,7 @@ func TestCreateGrantQuery(t *testing.T) { expected: fmt.Sprintf("GRANT SELECT ON ALL SEQUENCES IN SCHEMA %s TO %s", pq.QuoteIdentifier(databaseName), pq.QuoteIdentifier(roleName)), }, { - resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]interface{}{ + resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]any{ "object_type": "function", "schema": databaseName, "role": roleName, @@ -53,7 +53,7 @@ func TestCreateGrantQuery(t *testing.T) { expected: fmt.Sprintf("GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA %s TO %s", pq.QuoteIdentifier(databaseName), pq.QuoteIdentifier(roleName)), }, { - resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]interface{}{ + resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]any{ "object_type": "procedure", "schema": databaseName, "role": roleName, @@ -62,7 +62,7 @@ func TestCreateGrantQuery(t *testing.T) { expected: fmt.Sprintf("GRANT EXECUTE ON ALL PROCEDURES IN SCHEMA %s TO %s", pq.QuoteIdentifier(databaseName), pq.QuoteIdentifier(roleName)), }, { - resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]interface{}{ + resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]any{ "object_type": "routine", "schema": databaseName, "role": roleName, @@ -71,7 +71,7 @@ func TestCreateGrantQuery(t *testing.T) { expected: fmt.Sprintf("GRANT EXECUTE ON ALL ROUTINES IN SCHEMA %s TO %s", pq.QuoteIdentifier(databaseName), pq.QuoteIdentifier(roleName)), }, { - resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]interface{}{ + resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]any{ "object_type": "TABLE", "schema": databaseName, "role": roleName, @@ -81,7 +81,7 @@ func TestCreateGrantQuery(t *testing.T) { expected: fmt.Sprintf("GRANT SELECT,INSERT,UPDATE ON ALL TABLES IN SCHEMA %s TO %s WITH GRANT OPTION", pq.QuoteIdentifier(databaseName), pq.QuoteIdentifier(roleName)), }, { - resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]interface{}{ + resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]any{ "object_type": "database", "database": databaseName, "role": roleName, @@ -90,7 +90,7 @@ func TestCreateGrantQuery(t *testing.T) { expected: fmt.Sprintf("GRANT CREATE ON DATABASE %s TO %s", pq.QuoteIdentifier(databaseName), pq.QuoteIdentifier(roleName)), }, { - resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]interface{}{ + resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]any{ "object_type": "database", "database": databaseName, "role": roleName, @@ -99,7 +99,7 @@ func TestCreateGrantQuery(t *testing.T) { expected: fmt.Sprintf("GRANT CREATE,CONNECT ON DATABASE %s TO %s", pq.QuoteIdentifier(databaseName), pq.QuoteIdentifier(roleName)), }, { - resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]interface{}{ + resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]any{ "object_type": "DATABASE", "database": databaseName, "role": roleName, @@ -109,7 +109,7 @@ func TestCreateGrantQuery(t *testing.T) { expected: fmt.Sprintf("GRANT ALL PRIVILEGES ON DATABASE %s TO %s WITH GRANT OPTION", pq.QuoteIdentifier(databaseName), pq.QuoteIdentifier(roleName)), }, { - resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]interface{}{ + resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]any{ "object_type": "table", "objects": tableObjects, "schema": databaseName, @@ -119,9 +119,9 @@ func TestCreateGrantQuery(t *testing.T) { expected: fmt.Sprintf(`GRANT SELECT ON TABLE %[1]s."o2",%[1]s."o1" TO %s`, pq.QuoteIdentifier(databaseName), pq.QuoteIdentifier(roleName)), }, { - resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]interface{}{ + resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]any{ "object_type": "column", - "objects": []interface{}{"o1"}, + "objects": []any{"o1"}, "columns": tableColumns, "schema": databaseName, "role": roleName, @@ -130,7 +130,7 @@ func TestCreateGrantQuery(t *testing.T) { expected: fmt.Sprintf(`GRANT SELECT (%[2]s,%[3]s) ON TABLE %[1]s."o1" TO %[4]s`, pq.QuoteIdentifier(databaseName), pq.QuoteIdentifier("col2"), pq.QuoteIdentifier("col1"), pq.QuoteIdentifier(roleName)), }, { - resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]interface{}{ + resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]any{ "object_type": "foreign_data_wrapper", "objects": fdwObjects, "role": roleName, @@ -139,7 +139,7 @@ func TestCreateGrantQuery(t *testing.T) { expected: fmt.Sprintf(`GRANT USAGE ON FOREIGN DATA WRAPPER "baz" TO %s`, pq.QuoteIdentifier(roleName)), }, { - resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]interface{}{ + resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]any{ "object_type": "foreign_data_wrapper", "objects": fdwObjects, "role": roleName, @@ -149,7 +149,7 @@ func TestCreateGrantQuery(t *testing.T) { expected: fmt.Sprintf(`GRANT ALL PRIVILEGES ON FOREIGN DATA WRAPPER "baz" TO %s WITH GRANT OPTION`, pq.QuoteIdentifier(roleName)), }, { - resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]interface{}{ + resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]any{ "object_type": "foreign_server", "objects": fdwObjects, "role": roleName, @@ -158,7 +158,7 @@ func TestCreateGrantQuery(t *testing.T) { expected: fmt.Sprintf(`GRANT USAGE ON FOREIGN SERVER "baz" TO %s`, pq.QuoteIdentifier(roleName)), }, { - resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]interface{}{ + resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]any{ "object_type": "foreign_server", "objects": fdwObjects, "role": roleName, @@ -172,7 +172,7 @@ func TestCreateGrantQuery(t *testing.T) { for _, c := range cases { out := createGrantQuery(c.resource, c.privileges) if out != c.expected { - t.Fatalf("Error matching output and expected: %#v vs %#v", out, c.expected) + t.Fatalf("error matching output and expected: %#v vs %#v", out, c.expected) } } } @@ -180,16 +180,16 @@ func TestCreateGrantQuery(t *testing.T) { func TestCreateRevokeQuery(t *testing.T) { var databaseName = "foo" var roleName = "bar" - var tableObjects = []interface{}{"o1", "o2"} - var tableColumns = []interface{}{"col1", "col2"} - var fdwObjects = []interface{}{"baz"} + var tableObjects = []any{"o1", "o2"} + var tableColumns = []any{"col1", "col2"} + var fdwObjects = []any{"baz"} cases := []struct { resource *schema.ResourceData expected string }{ { - resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]interface{}{ + resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]any{ "object_type": "table", "schema": databaseName, "role": roleName, @@ -197,7 +197,7 @@ func TestCreateRevokeQuery(t *testing.T) { expected: fmt.Sprintf("REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA %s FROM %s", pq.QuoteIdentifier(databaseName), pq.QuoteIdentifier(roleName)), }, { - resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]interface{}{ + resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]any{ "object_type": "sequence", "schema": databaseName, "role": roleName, @@ -205,7 +205,7 @@ func TestCreateRevokeQuery(t *testing.T) { expected: fmt.Sprintf("REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA %s FROM %s", pq.QuoteIdentifier(databaseName), pq.QuoteIdentifier(roleName)), }, { - resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]interface{}{ + resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]any{ "object_type": "function", "schema": databaseName, "role": roleName, @@ -213,7 +213,7 @@ func TestCreateRevokeQuery(t *testing.T) { expected: fmt.Sprintf("REVOKE ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA %s FROM %s", pq.QuoteIdentifier(databaseName), pq.QuoteIdentifier(roleName)), }, { - resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]interface{}{ + resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]any{ "object_type": "procedure", "schema": databaseName, "role": roleName, @@ -221,7 +221,7 @@ func TestCreateRevokeQuery(t *testing.T) { expected: fmt.Sprintf("REVOKE ALL PRIVILEGES ON ALL PROCEDURES IN SCHEMA %s FROM %s", pq.QuoteIdentifier(databaseName), pq.QuoteIdentifier(roleName)), }, { - resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]interface{}{ + resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]any{ "object_type": "routine", "schema": databaseName, "role": roleName, @@ -229,7 +229,7 @@ func TestCreateRevokeQuery(t *testing.T) { expected: fmt.Sprintf("REVOKE ALL PRIVILEGES ON ALL ROUTINES IN SCHEMA %s FROM %s", pq.QuoteIdentifier(databaseName), pq.QuoteIdentifier(roleName)), }, { - resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]interface{}{ + resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]any{ "object_type": "database", "database": databaseName, "role": roleName, @@ -237,7 +237,7 @@ func TestCreateRevokeQuery(t *testing.T) { expected: fmt.Sprintf("REVOKE ALL PRIVILEGES ON DATABASE %s FROM %s", pq.QuoteIdentifier(databaseName), pq.QuoteIdentifier(roleName)), }, { - resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]interface{}{ + resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]any{ "object_type": "DATABASE", "database": databaseName, "role": roleName, @@ -245,7 +245,7 @@ func TestCreateRevokeQuery(t *testing.T) { expected: fmt.Sprintf("REVOKE ALL PRIVILEGES ON DATABASE %s FROM %s", pq.QuoteIdentifier(databaseName), pq.QuoteIdentifier(roleName)), }, { - resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]interface{}{ + resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]any{ "object_type": "table", "objects": tableObjects, "schema": databaseName, @@ -254,28 +254,28 @@ func TestCreateRevokeQuery(t *testing.T) { expected: fmt.Sprintf(`REVOKE ALL PRIVILEGES ON TABLE %[1]s."o2",%[1]s."o1" FROM %s`, pq.QuoteIdentifier(databaseName), pq.QuoteIdentifier(roleName)), }, { - resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]interface{}{ + resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]any{ "object_type": "table", "objects": tableObjects, "schema": databaseName, "role": roleName, - "privileges": []interface{}{"INSERT", "UPDATE"}, + "privileges": []any{"INSERT", "UPDATE"}, }), expected: fmt.Sprintf(`REVOKE UPDATE,INSERT ON TABLE %[1]s."o2",%[1]s."o1" FROM %s`, pq.QuoteIdentifier(databaseName), pq.QuoteIdentifier(roleName)), }, { - resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]interface{}{ + resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]any{ "object_type": "column", - "objects": []interface{}{"o1"}, + "objects": []any{"o1"}, "schema": databaseName, "columns": tableColumns, "role": roleName, - "privileges": []interface{}{"SELECT"}, + "privileges": []any{"SELECT"}, }), expected: fmt.Sprintf(`REVOKE SELECT ("col2","col1") ON TABLE %[1]s."o1" FROM %s`, pq.QuoteIdentifier(databaseName), pq.QuoteIdentifier(roleName)), }, { - resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]interface{}{ + resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]any{ "object_type": "foreign_data_wrapper", "objects": fdwObjects, "role": roleName, @@ -283,7 +283,7 @@ func TestCreateRevokeQuery(t *testing.T) { expected: fmt.Sprintf(`REVOKE ALL PRIVILEGES ON FOREIGN DATA WRAPPER "baz" FROM %s`, pq.QuoteIdentifier(roleName)), }, { - resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]interface{}{ + resource: schema.TestResourceDataRaw(t, resourcePostgreSQLGrant().Schema, map[string]any{ "object_type": "foreign_server", "objects": fdwObjects, "role": roleName, @@ -295,7 +295,7 @@ func TestCreateRevokeQuery(t *testing.T) { for _, c := range cases { out := createRevokeQuery(c.resource.Get) if out != c.expected { - t.Fatalf("Error matching output and expected: %#v vs %#v", out, c.expected) + t.Fatalf("error matching output and expected: %#v vs %#v", out, c.expected) } } } @@ -1446,8 +1446,7 @@ func TestAccPostgresqlGrantOwnerPG15(t *testing.T) { if err != nil { t.Fatalf("could not connect to database %s: %v", dbName, err) } - - defer db.Close() + defer closeDB(t, db) if _, err := db.Exec(` ALTER SCHEMA test_schema OWNER TO pg_database_owner; @@ -1484,7 +1483,7 @@ func TestAccPostgresqlGrantOwnerPG15(t *testing.T) { func testCheckDatabasesPrivileges(t *testing.T, canCreate bool) func(*terraform.State) error { return func(*terraform.State) error { db := connectAsTestRole(t, "test_grant_role", "test_grant_db") - defer db.Close() + defer closeDB(t, db) if err := testHasGrantForQuery(db, "CREATE SCHEMA plop", canCreate); err != nil { return err @@ -1496,7 +1495,7 @@ func testCheckDatabasesPrivileges(t *testing.T, canCreate bool) func(*terraform. func testCheckFunctionExecutable(t *testing.T, role, function string) func(*terraform.State) error { return func(*terraform.State) error { db := connectAsTestRole(t, role, "postgres") - defer db.Close() + defer closeDB(t, db) if err := testHasGrantForQuery(db, fmt.Sprintf("SELECT %s()", function), true); err != nil { return err @@ -1508,7 +1507,7 @@ func testCheckFunctionExecutable(t *testing.T, role, function string) func(*terr func testCheckFunctionWithArgsExecutable(t *testing.T, role, function string, args []string) func(*terraform.State) error { return func(*terraform.State) error { db := connectAsTestRole(t, role, "postgres") - defer db.Close() + defer closeDB(t, db) if err := testHasGrantForQuery(db, fmt.Sprintf("SELECT %s(%s)", function, strings.Join(args, ", ")), true); err != nil { return err @@ -1520,7 +1519,7 @@ func testCheckFunctionWithArgsExecutable(t *testing.T, role, function string, ar func testCheckProcedureExecutable(t *testing.T, role, procedure string) func(*terraform.State) error { return func(*terraform.State) error { db := connectAsTestRole(t, role, "postgres") - defer db.Close() + defer closeDB(t, db) if err := testHasGrantForQuery(db, fmt.Sprintf("CALL %s()", procedure), true); err != nil { return err @@ -1542,7 +1541,7 @@ func testCheckSchemaPrivileges(t *testing.T, usage, create bool) func(*terraform dbExecute(t, dsn, "GRANT SELECT ON test_schema.test_usage TO test_grant_role") db := connectAsTestRole(t, "test_grant_role", "postgres") - defer db.Close() + defer closeDB(t, db) if err := testHasGrantForQuery(db, "SELECT 1 FROM test_schema.test_usage", usage); err != nil { return err @@ -1565,7 +1564,7 @@ func testCheckForeignDataWrapperPrivileges(t *testing.T, usage bool) func(*terra dbExecute(t, dsn, "DROP SERVER IF EXISTS test_srv") }() db := connectAsTestRole(t, "test_role", "postgres") - defer db.Close() + defer closeDB(t, db) if err := testHasGrantForQuery(db, "CREATE SERVER test_srv FOREIGN DATA WRAPPER test_fdw", usage); err != nil { return err @@ -1584,7 +1583,7 @@ func testCheckForeignServerPrivileges(t *testing.T, usage bool) func(*terraform. dbExecute(t, dsn, "DROP FOREIGN TABLE IF EXISTS test_tbl") }() db := connectAsTestRole(t, "test_role", "postgres") - defer db.Close() + defer closeDB(t, db) if err := testHasGrantForQuery(db, "CREATE FOREIGN TABLE test_tbl() SERVER test_srv", usage); err != nil { return err diff --git a/postgresql/resource_postgresql_publication.go b/postgresql/resource_postgresql_publication.go index 5c653b67..daba28bf 100644 --- a/postgresql/resource_postgresql_publication.go +++ b/postgresql/resource_postgresql_publication.go @@ -128,7 +128,7 @@ func resourcePostgreSQLPublicationUpdate(db *DBConnection, d *schema.ResourceDat } if err = txn.Commit(); err != nil { - return fmt.Errorf("Error updating publication: %w", err) + return fmt.Errorf("error updating publication: %w", err) } return resourcePostgreSQLPublicationReadImpl(db, d) } @@ -143,7 +143,7 @@ func setPubName(txn *sql.Tx, d *schema.ResourceData) error { database := d.Get(pubDatabaseAttr).(string) sql := fmt.Sprintf("ALTER PUBLICATION %s RENAME TO %s", pq.QuoteIdentifier(o), pq.QuoteIdentifier(n)) if _, err := txn.Exec(sql); err != nil { - return fmt.Errorf("Error updating publication name: %w", err) + return fmt.Errorf("error updating publication name: %w", err) } d.SetId(generatePublicationID(d, database)) return nil @@ -160,7 +160,7 @@ func setPubOwner(txn *sql.Tx, d *schema.ResourceData) error { sql := fmt.Sprintf("ALTER PUBLICATION %s OWNER TO %s", pubName, n) if _, err := txn.Exec(sql); err != nil { - return fmt.Errorf("Error updating publication owner: %w", err) + return fmt.Errorf("error updating publication owner: %w", err) } return nil } @@ -205,12 +205,12 @@ func setPubParams(txn *sql.Tx, d *schema.ResourceData, pubViaRootEnabled bool) e paramAlterTemplate := "ALTER PUBLICATION %s %s" publicationParametersString, err := getPublicationParameters(d, pubViaRootEnabled) if err != nil { - return fmt.Errorf("Error getting publication parameters: %w", err) + return fmt.Errorf("error getting publication parameters: %w", err) } if publicationParametersString != "" { sql := fmt.Sprintf(paramAlterTemplate, pubName, publicationParametersString) if _, err := txn.Exec(sql); err != nil { - return fmt.Errorf("Error updating publication parameters: %w", err) + return fmt.Errorf("error updating publication parameters: %w", err) } } return nil @@ -243,14 +243,14 @@ func resourcePostgreSQLPublicationCreate(db *DBConnection, d *schema.ResourceDat sql := fmt.Sprintf("CREATE PUBLICATION %s %s %s", name, tables, publicationParameters) if _, err := txn.Exec(sql); err != nil { - return fmt.Errorf("Error creating Publication: %w", err) + return fmt.Errorf("error creating Publication: %w", err) } if err := setPubOwner(txn, d); err != nil { return fmt.Errorf("could not set publication owner during creation: %w", err) } if err = txn.Commit(); err != nil { - return fmt.Errorf("Error creating Publication: %w", err) + return fmt.Errorf("error creating Publication: %w", err) } d.SetId(generatePublicationID(d, databaseName)) @@ -325,7 +325,7 @@ func resourcePostgreSQLPublicationReadImpl(db *DBConnection, d *schema.ResourceD var puballtables, pubinsert, pubupdate, pubdelete, pubtruncate, pubviaroot bool var pubowner string columns := []string{"puballtables", "pubinsert", "pubupdate", "pubdelete", "r.rolname as pubownername"} - values := []interface{}{ + values := []any{ &puballtables, &pubinsert, &pubupdate, @@ -351,7 +351,7 @@ func resourcePostgreSQLPublicationReadImpl(db *DBConnection, d *schema.ResourceD d.SetId("") return nil case err != nil: - return fmt.Errorf("Error reading publication info: %w", err) + return fmt.Errorf("error reading publication info: %w", err) } query = `SELECT CONCAT(schemaname,'.',tablename) as fulltablename ` + @@ -362,7 +362,11 @@ func resourcePostgreSQLPublicationReadImpl(db *DBConnection, d *schema.ResourceD if err != nil { return fmt.Errorf("could not get publication tables: %w", err) } - defer rows.Close() + defer func() { + if err := rows.Close(); err != nil { + log.Printf("error closing rows: %v", err) + } + }() for rows.Next() { var table string @@ -373,7 +377,7 @@ func resourcePostgreSQLPublicationReadImpl(db *DBConnection, d *schema.ResourceD tables = append(tables, table) } if err := rows.Err(); err != nil { - return fmt.Errorf("Got rows.Err: %w", err) + return fmt.Errorf("got rows.Err: %w", err) } if pubinsert { @@ -429,7 +433,7 @@ func resourcePostgreSQLPublicationDelete(db *DBConnection, d *schema.ResourceDat } if err = txn.Commit(); err != nil { - return fmt.Errorf("Error deleting Publication: %w", err) + return fmt.Errorf("error deleting Publication: %w", err) } d.SetId("") @@ -469,7 +473,7 @@ func getTablesForPublication(d *schema.ResourceData) (string, error) { return tablesString, nil } -func validatedPublicationPublishParams(paramList []interface{}) ([]string, error) { +func validatedPublicationPublishParams(paramList []any) ([]string, error) { var attrs []string if elem, ok := isUniqueArr(paramList); !ok { return make([]string, 0), fmt.Errorf("'%s' is duplicated for attribute `%s`", elem.(string), pubTablesAttr) @@ -501,7 +505,7 @@ func getPublicationParameters(d *schema.ResourceData, pubViaRootEnabled bool) (s } if v, ok := d.GetOk(pubPublishAttr); ok { - if paramsList, err := validatedPublicationPublishParams(v.([]interface{})); err != nil { + if paramsList, err := validatedPublicationPublishParams(v.([]any)); err != nil { return "", err } else { pubParams["publish"] = fmt.Sprintf("'%s'", strings.Join(paramsList, ", ")) @@ -524,7 +528,7 @@ func getPublicationParameters(d *schema.ResourceData, pubViaRootEnabled bool) (s if d.HasChange(pubPublishAttr) { _, nraw := d.GetChange(pubPublishAttr) - if paramsList, err := validatedPublicationPublishParams(nraw.([]interface{})); err != nil { + if paramsList, err := validatedPublicationPublishParams(nraw.([]any)); err != nil { return "", err } else { pubParams["publish"] = fmt.Sprintf("'%s'", strings.Join(paramsList, ", ")) @@ -561,7 +565,7 @@ func getDBPublicationName(d *schema.ResourceData, client *Client) (string, strin if PublicationName == "" { parsed := strings.Split(d.Id(), ".") if len(parsed) != 2 { - return "", "", fmt.Errorf("Publication ID %s has not the expected format 'database.publication_name': %v", d.Id(), parsed) + return "", "", fmt.Errorf("publication ID %s has not the expected format 'database.publication_name': %v", d.Id(), parsed) } database = parsed[0] PublicationName = parsed[1] diff --git a/postgresql/resource_postgresql_publication_test.go b/postgresql/resource_postgresql_publication_test.go index cc298597..79ab7d11 100644 --- a/postgresql/resource_postgresql_publication_test.go +++ b/postgresql/resource_postgresql_publication_test.go @@ -31,7 +31,7 @@ func testAccCheckPostgresqlPublicationDestroy(s *terraform.State) error { exists, err := checkPublicationExists(txn, getPublicationNameFromID(rs.Primary.ID)) if err != nil { - return fmt.Errorf("Error checking publication %s", err) + return fmt.Errorf("error checking publication %s", err) } if exists { @@ -73,7 +73,7 @@ func testAccCheckPostgresqlPublicationExists(n string) resource.TestCheckFunc { exists, err := checkPublicationExists(txn, pubName) if err != nil { - return fmt.Errorf("Error checking publication %s", err) + return fmt.Errorf("error checking publication %s", err) } if !exists { @@ -489,7 +489,7 @@ func checkPublicationExists(txn *sql.Tx, pubName string) (bool, error) { case err == sql.ErrNoRows: return false, nil case err != nil: - return false, fmt.Errorf("Error reading info about publication: %s", err) + return false, fmt.Errorf("error reading info about publication: %s", err) } return true, nil @@ -809,7 +809,7 @@ resource "postgresql_publication" "test" { }, { Config: testAccPostgresqlPublicationWrongKeys, - ExpectError: regexp.MustCompile("could not update publication tables: Error getting publication parameters: invalid value of `publish_param`: wrong_param. Should be at least one of 'insert, update, delete, truncate'"), + ExpectError: regexp.MustCompile("could not update publication tables: error getting publication parameters: invalid value of `publish_param`: wrong_param. Should be at least one of 'insert, update, delete, truncate'"), }, { Config: testAccPostgresqlPublicationDuplicateKeys, diff --git a/postgresql/resource_postgresql_replication_slot.go b/postgresql/resource_postgresql_replication_slot.go index 1d61d411..348d5e34 100644 --- a/postgresql/resource_postgresql_replication_slot.go +++ b/postgresql/resource_postgresql_replication_slot.go @@ -60,7 +60,7 @@ func resourcePostgreSQLReplicationSlotCreate(db *DBConnection, d *schema.Resourc } if err = txn.Commit(); err != nil { - return fmt.Errorf("Error creating ReplicationSlot: %w", err) + return fmt.Errorf("error creating ReplicationSlot: %w", err) } d.SetId(generateReplicationSlotID(d, databaseName)) @@ -128,7 +128,7 @@ func resourcePostgreSQLReplicationSlotReadImpl(db *DBConnection, d *schema.Resou d.SetId("") return nil case err != nil: - return fmt.Errorf("Error reading ReplicationSlot: %w", err) + return fmt.Errorf("error reading ReplicationSlot: %w", err) } d.Set("name", replicationSlotName) @@ -156,7 +156,7 @@ func resourcePostgreSQLReplicationSlotDelete(db *DBConnection, d *schema.Resourc } if err = txn.Commit(); err != nil { - return fmt.Errorf("Error deleting ReplicationSlot: %w", err) + return fmt.Errorf("error deleting ReplicationSlot: %w", err) } d.SetId("") @@ -195,7 +195,7 @@ func getDBReplicationSlotName(d *schema.ResourceData, client *Client) (string, s if replicationSlotName == "" { parsed := strings.Split(d.Id(), ".") if len(parsed) != 2 { - return "", "", fmt.Errorf("Replication Slot ID %s has not the expected format 'database.replication_slot': %v", d.Id(), parsed) + return "", "", fmt.Errorf("replication Slot ID %s has not the expected format 'database.replication_slot': %v", d.Id(), parsed) } database = parsed[0] replicationSlotName = parsed[1] diff --git a/postgresql/resource_postgresql_replication_slot_test.go b/postgresql/resource_postgresql_replication_slot_test.go index f2221b14..975714d6 100644 --- a/postgresql/resource_postgresql_replication_slot_test.go +++ b/postgresql/resource_postgresql_replication_slot_test.go @@ -57,7 +57,7 @@ func testAccCheckPostgresqlReplicationSlotDestroy(s *terraform.State) error { exists, err := checkReplicationSlotExists(txn, getReplicationSlotNameFromID(rs.Primary.ID)) if err != nil { - return fmt.Errorf("Error checking replication slot %s", err) + return fmt.Errorf("error checking replication slot %s", err) } if exists { @@ -99,7 +99,7 @@ func testAccCheckPostgresqlReplicationSlotExists(n string) resource.TestCheckFun exists, err := checkReplicationSlotExists(txn, extName) if err != nil { - return fmt.Errorf("Error checking replication slot %s", err) + return fmt.Errorf("error checking replication slot %s", err) } if !exists { @@ -157,7 +157,7 @@ func checkReplicationSlotExists(txn *sql.Tx, slotName string) (bool, error) { case err == sql.ErrNoRows: return false, nil case err != nil: - return false, fmt.Errorf("Error reading info about replication slot: %s", err) + return false, fmt.Errorf("error reading info about replication slot: %s", err) } return true, nil diff --git a/postgresql/resource_postgresql_role.go b/postgresql/resource_postgresql_role.go index 49fbd3f9..38bfb9e9 100644 --- a/postgresql/resource_postgresql_role.go +++ b/postgresql/resource_postgresql_role.go @@ -414,7 +414,7 @@ func resourcePostgreSQLRoleDelete(db *DBConnection, d *schema.ResourceData) erro } if err := txn.Commit(); err != nil { - return fmt.Errorf("Error committing schema: %w", err) + return fmt.Errorf("error committing schema: %w", err) } d.SetId("") @@ -459,7 +459,7 @@ func resourcePostgreSQLRoleReadImpl(db *DBConnection, d *schema.ResourceData) er "rolconfig", } - values := []interface{}{ + values := []any{ &roleRoles, &roleName, &roleSuperuser, @@ -497,7 +497,7 @@ func resourcePostgreSQLRoleReadImpl(db *DBConnection, d *schema.ResourceData) er d.SetId("") return nil case err != nil: - return fmt.Errorf("Error reading ROLE: %w", err) + return fmt.Errorf("error reading ROLE: %w", err) } d.Set(roleNameAttr, roleName) @@ -568,7 +568,7 @@ func readIdleInTransactionSessionTimeout(roleConfig pq.ByteaArray) (int, error) var result = strings.Split(strings.TrimPrefix(config, roleIdleInTransactionSessionTimeoutAttr+"="), ", ") res, err := strconv.Atoi(result[0]) if err != nil { - return -1, fmt.Errorf("Error reading statement_timeout: %w", err) + return -1, fmt.Errorf("error reading statement_timeout: %w", err) } return res, nil } @@ -585,7 +585,7 @@ func readStatementTimeout(roleConfig pq.ByteaArray) (int, error) { var result = strings.Split(strings.TrimPrefix(config, roleStatementTimeoutAttr+"="), ", ") res, err := strconv.Atoi(result[0]) if err != nil { - return -1, fmt.Errorf("Error reading statement_timeout: %w", err) + return -1, fmt.Errorf("error reading statement_timeout: %w", err) } return res, nil } @@ -642,7 +642,7 @@ func readRolePassword(db *DBConnection, d *schema.ResourceData, roleCanLogin boo // They don't have a password return "", nil case err != nil: - return "", fmt.Errorf("Error reading role: %w", err) + return "", fmt.Errorf("error reading role: %w", err) } // If the password isn't already in md5 format, but hashing the input // matches the password in the database for the user, they are the same @@ -765,12 +765,12 @@ func setRoleName(txn *sql.Tx, d *schema.ResourceData) error { o := oraw.(string) n := nraw.(string) if n == "" { - return errors.New("Error setting role name to an empty string") + return errors.New("error setting role name to an empty string") } sql := fmt.Sprintf("ALTER ROLE %s RENAME TO %s", pq.QuoteIdentifier(o), pq.QuoteIdentifier(n)) if _, err := txn.Exec(sql); err != nil { - return fmt.Errorf("Error updating role NAME: %w", err) + return fmt.Errorf("error updating role NAME: %w", err) } d.SetId(n) @@ -807,7 +807,7 @@ func setRolePassword(txn *sql.Tx, d *schema.ResourceData) error { sql := fmt.Sprintf("ALTER ROLE %s PASSWORD '%s'", pq.QuoteIdentifier(roleName), pqQuoteLiteral(password)) if _, err := txn.Exec(sql); err != nil { - return fmt.Errorf("Error updating role password: %w", err) + return fmt.Errorf("error updating role password: %w", err) } return nil @@ -830,7 +830,7 @@ func setRoleBypassRLS(db *DBConnection, txn *sql.Tx, d *schema.ResourceData) err roleName := d.Get(roleNameAttr).(string) sql := fmt.Sprintf("ALTER ROLE %s WITH %s", pq.QuoteIdentifier(roleName), tok) if _, err := txn.Exec(sql); err != nil { - return fmt.Errorf("Error updating role BYPASSRLS: %w", err) + return fmt.Errorf("error updating role BYPASSRLS: %w", err) } return nil @@ -845,7 +845,7 @@ func setRoleConnLimit(txn *sql.Tx, d *schema.ResourceData) error { roleName := d.Get(roleNameAttr).(string) sql := fmt.Sprintf("ALTER ROLE %s CONNECTION LIMIT %d", pq.QuoteIdentifier(roleName), connLimit) if _, err := txn.Exec(sql); err != nil { - return fmt.Errorf("Error updating role CONNECTION LIMIT: %w", err) + return fmt.Errorf("error updating role CONNECTION LIMIT: %w", err) } return nil @@ -864,7 +864,7 @@ func setRoleCreateDB(txn *sql.Tx, d *schema.ResourceData) error { roleName := d.Get(roleNameAttr).(string) sql := fmt.Sprintf("ALTER ROLE %s WITH %s", pq.QuoteIdentifier(roleName), tok) if _, err := txn.Exec(sql); err != nil { - return fmt.Errorf("Error updating role CREATEDB: %w", err) + return fmt.Errorf("error updating role CREATEDB: %w", err) } return nil @@ -883,7 +883,7 @@ func setRoleCreateRole(txn *sql.Tx, d *schema.ResourceData) error { roleName := d.Get(roleNameAttr).(string) sql := fmt.Sprintf("ALTER ROLE %s WITH %s", pq.QuoteIdentifier(roleName), tok) if _, err := txn.Exec(sql); err != nil { - return fmt.Errorf("Error updating role CREATEROLE: %w", err) + return fmt.Errorf("error updating role CREATEROLE: %w", err) } return nil @@ -902,7 +902,7 @@ func setRoleInherit(txn *sql.Tx, d *schema.ResourceData) error { roleName := d.Get(roleNameAttr).(string) sql := fmt.Sprintf("ALTER ROLE %s WITH %s", pq.QuoteIdentifier(roleName), tok) if _, err := txn.Exec(sql); err != nil { - return fmt.Errorf("Error updating role INHERIT: %w", err) + return fmt.Errorf("error updating role INHERIT: %w", err) } return nil @@ -921,7 +921,7 @@ func setRoleLogin(txn *sql.Tx, d *schema.ResourceData) error { roleName := d.Get(roleNameAttr).(string) sql := fmt.Sprintf("ALTER ROLE %s WITH %s", pq.QuoteIdentifier(roleName), tok) if _, err := txn.Exec(sql); err != nil { - return fmt.Errorf("Error updating role LOGIN: %w", err) + return fmt.Errorf("error updating role LOGIN: %w", err) } return nil @@ -940,7 +940,7 @@ func setRoleReplication(txn *sql.Tx, d *schema.ResourceData) error { roleName := d.Get(roleNameAttr).(string) sql := fmt.Sprintf("ALTER ROLE %s WITH %s", pq.QuoteIdentifier(roleName), tok) if _, err := txn.Exec(sql); err != nil { - return fmt.Errorf("Error updating role REPLICATION: %w", err) + return fmt.Errorf("error updating role REPLICATION: %w", err) } return nil @@ -959,7 +959,7 @@ func setRoleSuperuser(txn *sql.Tx, d *schema.ResourceData) error { roleName := d.Get(roleNameAttr).(string) sql := fmt.Sprintf("ALTER ROLE %s WITH %s", pq.QuoteIdentifier(roleName), tok) if _, err := txn.Exec(sql); err != nil { - return fmt.Errorf("Error updating role SUPERUSER: %w", err) + return fmt.Errorf("error updating role SUPERUSER: %w", err) } return nil @@ -980,7 +980,7 @@ func setRoleValidUntil(txn *sql.Tx, d *schema.ResourceData) error { roleName := d.Get(roleNameAttr).(string) sql := fmt.Sprintf("ALTER ROLE %s VALID UNTIL '%s'", pq.QuoteIdentifier(roleName), pqQuoteLiteral(validUntil)) if _, err := txn.Exec(sql); err != nil { - return fmt.Errorf("Error updating role VALID UNTIL: %w", err) + return fmt.Errorf("error updating role VALID UNTIL: %w", err) } return nil @@ -998,7 +998,11 @@ func revokeRoles(txn *sql.Tx, d *schema.ResourceData) error { if err != nil { return fmt.Errorf("could not get roles list for role %s: %w", role, err) } - defer rows.Close() + defer func() { + if err := rows.Close(); err != nil { + log.Printf("error closing rows: %v", err) + } + }() grantedRoles := []string{} for rows.Next() { @@ -1040,7 +1044,7 @@ func grantRoles(txn *sql.Tx, d *schema.ResourceData) error { func alterSearchPath(txn *sql.Tx, d *schema.ResourceData) error { role := d.Get(roleNameAttr).(string) - searchPathInterface := d.Get(roleSearchPathAttr).([]interface{}) + searchPathInterface := d.Get(roleSearchPathAttr).([]any) var searchPathString []string if len(searchPathInterface) > 0 { diff --git a/postgresql/resource_postgresql_role_test.go b/postgresql/resource_postgresql_role_test.go index c49774d1..9910ca0f 100644 --- a/postgresql/resource_postgresql_role_test.go +++ b/postgresql/resource_postgresql_role_test.go @@ -3,6 +3,7 @@ package postgresql import ( "database/sql" "fmt" + "log" "os" "reflect" "sort" @@ -248,7 +249,7 @@ func testAccCheckPostgresqlRoleDestroy(s *terraform.State) error { exists, err := checkRoleExists(client, rs.Primary.ID) if err != nil { - return fmt.Errorf("Error checking role %s", err) + return fmt.Errorf("error checking role %s", err) } if exists { @@ -265,7 +266,7 @@ func testAccCheckPostgresqlRoleExists(roleName string, grantedRoles []string, se exists, err := checkRoleExists(client, roleName) if err != nil { - return fmt.Errorf("Error checking role %s", err) + return fmt.Errorf("error checking role %s", err) } if !exists { @@ -298,7 +299,7 @@ func checkRoleExists(client *Client, roleName string) (bool, error) { case err == sql.ErrNoRows: return false, nil case err != nil: - return false, fmt.Errorf("Error reading info about role: %s", err) + return false, fmt.Errorf("error reading info about role: %s", err) } return true, nil @@ -331,15 +332,19 @@ func checkGrantedRoles(client *Client, roleName string, expectedRoles []string) roleName, ) if err != nil { - return fmt.Errorf("Error reading granted roles: %v", err) + return fmt.Errorf("error reading granted roles: %v", err) } - defer rows.Close() + defer func() { + if err := rows.Close(); err != nil { + log.Printf("error closing rows: %v", err) + } + }() grantedRoles := []string{} for rows.Next() { var grantedRole string if err := rows.Scan(&grantedRole); err != nil { - return fmt.Errorf("Error scanning granted role: %v", err) + return fmt.Errorf("error scanning granted role: %v", err) } grantedRoles = append(grantedRoles, grantedRole) } @@ -370,7 +375,7 @@ func checkSearchPath(client *Client, roleName string, expectedSearchPath []strin if err != nil && err == sql.ErrNoRows { searchPathStr = "\"$user\", public" } else if err != nil { - return fmt.Errorf("Error reading search_path: %v", err) + return fmt.Errorf("error reading search_path: %v", err) } searchPath := strings.Split(searchPathStr, ", ") diff --git a/postgresql/resource_postgresql_schema.go b/postgresql/resource_postgresql_schema.go index 91d34dca..508fbc33 100644 --- a/postgresql/resource_postgresql_schema.go +++ b/postgresql/resource_postgresql_schema.go @@ -149,7 +149,7 @@ func resourcePostgreSQLSchemaCreate(db *DBConnection, d *schema.ResourceData) er } if err := txn.Commit(); err != nil { - return fmt.Errorf("Error committing schema: %w", err) + return fmt.Errorf("error committing schema: %w", err) } d.SetId(generateSchemaID(d, database)) @@ -182,7 +182,7 @@ func createSchema(db *DBConnection, txn *sql.Tx, d *schema.ResourceData) error { queries = append(queries, b.String()) case err != nil: - return fmt.Errorf("Error looking for schema: %w", err) + return fmt.Errorf("error looking for schema: %w", err) default: // The schema already exists, we just set the owner. @@ -203,7 +203,7 @@ func createSchema(db *DBConnection, txn *sql.Tx, d *schema.ResourceData) error { schemaPolicies = make(map[RoleKey]acl.Schema, len(policiesList)) for _, policyRaw := range policiesList { - policyMap := policyRaw.(map[string]interface{}) + policyMap := policyRaw.(map[string]any) rolePolicy := schemaPolicyToACL(policyMap) roleKey := RoleKey(strings.ToLower(rolePolicy.Role)) @@ -221,7 +221,7 @@ func createSchema(db *DBConnection, txn *sql.Tx, d *schema.ResourceData) error { for _, query := range queries { if _, err = txn.Exec(query); err != nil { - return fmt.Errorf("Error creating schema %s: %w", schemaName, err) + return fmt.Errorf("error creating schema %s: %w", schemaName, err) } } @@ -258,7 +258,7 @@ func resourcePostgreSQLSchemaDelete(db *DBConnection, d *schema.ResourceData) er sql := fmt.Sprintf("DROP SCHEMA %s %s", pq.QuoteIdentifier(schemaName), dropMode) if _, err = txn.Exec(sql); err != nil { - return fmt.Errorf("Error deleting schema: %w", err) + return fmt.Errorf("error deleting schema: %w", err) } return nil @@ -267,7 +267,7 @@ func resourcePostgreSQLSchemaDelete(db *DBConnection, d *schema.ResourceData) er } if err := txn.Commit(); err != nil { - return fmt.Errorf("Error committing schema: %w", err) + return fmt.Errorf("error committing schema: %w", err) } d.SetId("") @@ -298,7 +298,7 @@ func resourcePostgreSQLSchemaExists(db *DBConnection, d *schema.ResourceData) (b case err == sql.ErrNoRows: return false, nil case err != nil: - return false, fmt.Errorf("Error reading schema: %w", err) + return false, fmt.Errorf("error reading schema: %w", err) } return true, nil @@ -329,14 +329,14 @@ func resourcePostgreSQLSchemaReadImpl(db *DBConnection, d *schema.ResourceData) d.SetId("") return nil case err != nil: - return fmt.Errorf("Error reading schema: %w", err) + return fmt.Errorf("error reading schema: %w", err) default: type RoleKey string schemaPolicies := make(map[RoleKey]acl.Schema, len(schemaACLs)) for _, aclStr := range schemaACLs { aclItem, err := acl.Parse(aclStr) if err != nil { - return fmt.Errorf("Error parsing aclitem: %w", err) + return fmt.Errorf("error parsing aclitem: %w", err) } schemaACL, err := acl.NewSchema(aclItem) @@ -385,7 +385,7 @@ func resourcePostgreSQLSchemaUpdate(db *DBConnection, d *schema.ResourceData) er } if err := txn.Commit(); err != nil { - return fmt.Errorf("Error committing schema: %w", err) + return fmt.Errorf("error committing schema: %w", err) } return resourcePostgreSQLSchemaReadImpl(db, d) @@ -400,12 +400,12 @@ func setSchemaName(txn *sql.Tx, d *schema.ResourceData, databaseName string) err o := oraw.(string) n := nraw.(string) if n == "" { - return errors.New("Error setting schema name to an empty string") + return errors.New("error setting schema name to an empty string") } sql := fmt.Sprintf("ALTER SCHEMA %s RENAME TO %s", pq.QuoteIdentifier(o), pq.QuoteIdentifier(n)) if _, err := txn.Exec(sql); err != nil { - return fmt.Errorf("Error updating schema NAME: %w", err) + return fmt.Errorf("error updating schema NAME: %w", err) } d.SetId(generateSchemaID(d, databaseName)) @@ -421,12 +421,12 @@ func setSchemaOwner(txn *sql.Tx, d *schema.ResourceData) error { schemaOwner := d.Get(schemaOwnerAttr).(string) if schemaOwner == "" { - return errors.New("Error setting schema owner to an empty string") + return errors.New("error setting schema owner to an empty string") } sql := fmt.Sprintf("ALTER SCHEMA %s OWNER TO %s", pq.QuoteIdentifier(schemaName), pq.QuoteIdentifier(schemaOwner)) if _, err := txn.Exec(sql); err != nil { - return fmt.Errorf("Error updating schema OWNER: %w", err) + return fmt.Errorf("error updating schema OWNER: %w", err) } return nil @@ -447,7 +447,7 @@ func setSchemaPolicy(txn *sql.Tx, d *schema.ResourceData) error { dropped, added, updated, _ := schemaChangedPolicies(oldList, newList) for _, p := range dropped { - pMap := p.(map[string]interface{}) + pMap := p.(map[string]any) rolePolicy := schemaPolicyToACL(pMap) // The PUBLIC role can not be DROP'ed, therefore we do not need @@ -460,7 +460,7 @@ func setSchemaPolicy(txn *sql.Tx, d *schema.ResourceData) error { // Don't execute this role's REVOKEs because the role // was dropped first and therefore doesn't exist. case err != nil: - return fmt.Errorf("Error reading schema: %w", err) + return fmt.Errorf("error reading schema: %w", err) default: queries = append(queries, rolePolicy.Revokes(schemaName)...) } @@ -468,25 +468,25 @@ func setSchemaPolicy(txn *sql.Tx, d *schema.ResourceData) error { } for _, p := range added { - pMap := p.(map[string]interface{}) + pMap := p.(map[string]any) rolePolicy := schemaPolicyToACL(pMap) queries = append(queries, rolePolicy.Grants(schemaName)...) } for _, p := range updated { - policies := p.([]interface{}) + policies := p.([]any) if len(policies) != 2 { panic("expected 2 policies, old and new") } { - oldPolicies := policies[0].(map[string]interface{}) + oldPolicies := policies[0].(map[string]any) rolePolicy := schemaPolicyToACL(oldPolicies) queries = append(queries, rolePolicy.Revokes(schemaName)...) } { - newPolicies := policies[1].(map[string]interface{}) + newPolicies := policies[1].(map[string]any) rolePolicy := schemaPolicyToACL(newPolicies) queries = append(queries, rolePolicy.Grants(schemaName)...) } @@ -500,7 +500,7 @@ func setSchemaPolicy(txn *sql.Tx, d *schema.ResourceData) error { return withRolesGranted(txn, rolesToGrant, func() error { for _, query := range queries { if _, err := txn.Exec(query); err != nil { - return fmt.Errorf("Error updating schema DCL: %w", err) + return fmt.Errorf("error updating schema DCL: %w", err) } } return nil @@ -511,12 +511,12 @@ func setSchemaPolicy(txn *sql.Tx, d *schema.ResourceData) error { // be executed to enact each type of state change (roles that have been dropped // from the policy, added to a policy, have updated privileges, or are // unchanged). -func schemaChangedPolicies(old, new []interface{}) (dropped, added, update, unchanged map[string]interface{}) { +func schemaChangedPolicies(old, new []any) (dropped, added, update, unchanged map[string]interface{}) { type RoleKey string - oldLookupMap := make(map[RoleKey]interface{}, len(old)) + oldLookupMap := make(map[RoleKey]any, len(old)) for idx := range old { v := old[idx] - schemaPolicy := v.(map[string]interface{}) + schemaPolicy := v.(map[string]any) if roleRaw, ok := schemaPolicy[schemaPolicyRoleAttr]; ok { role := roleRaw.(string) roleKey := strings.ToLower(role) @@ -524,10 +524,10 @@ func schemaChangedPolicies(old, new []interface{}) (dropped, added, update, unch } } - newLookupMap := make(map[RoleKey]interface{}, len(new)) + newLookupMap := make(map[RoleKey]any, len(new)) for idx := range new { v := new[idx] - schemaPolicy := v.(map[string]interface{}) + schemaPolicy := v.(map[string]any) if roleRaw, ok := schemaPolicy[schemaPolicyRoleAttr]; ok { role := roleRaw.(string) roleKey := strings.ToLower(role) @@ -535,28 +535,28 @@ func schemaChangedPolicies(old, new []interface{}) (dropped, added, update, unch } } - droppedRoles := make(map[string]interface{}, len(old)) + droppedRoles := make(map[string]any, len(old)) for kOld, vOld := range oldLookupMap { if _, ok := newLookupMap[kOld]; !ok { droppedRoles[string(kOld)] = vOld } } - addedRoles := make(map[string]interface{}, len(new)) + addedRoles := make(map[string]any, len(new)) for kNew, vNew := range newLookupMap { if _, ok := oldLookupMap[kNew]; !ok { addedRoles[string(kNew)] = vNew } } - updatedRoles := make(map[string]interface{}, len(new)) - unchangedRoles := make(map[string]interface{}, len(new)) + updatedRoles := make(map[string]any, len(new)) + unchangedRoles := make(map[string]any, len(new)) for kOld, vOld := range oldLookupMap { if vNew, ok := newLookupMap[kOld]; ok { if reflect.DeepEqual(vOld, vNew) { unchangedRoles[string(kOld)] = vOld } else { - updatedRoles[string(kOld)] = []interface{}{vOld, vNew} + updatedRoles[string(kOld)] = []any{vOld, vNew} } } } @@ -564,7 +564,7 @@ func schemaChangedPolicies(old, new []interface{}) (dropped, added, update, unch return droppedRoles, addedRoles, updatedRoles, unchangedRoles } -func schemaPolicyToACL(policyMap map[string]interface{}) acl.Schema { +func schemaPolicyToACL(policyMap map[string]any) acl.Schema { var rolePolicy acl.Schema if policyMap[schemaPolicyCreateAttr].(bool) { diff --git a/postgresql/resource_postgresql_schema_test.go b/postgresql/resource_postgresql_schema_test.go index 2a86e793..2a603694 100644 --- a/postgresql/resource_postgresql_schema_test.go +++ b/postgresql/resource_postgresql_schema_test.go @@ -304,7 +304,7 @@ func testAccCheckPostgresqlSchemaDestroy(s *terraform.State) error { exists, err := checkSchemaExists(txn, getExtensionNameFromID(rs.Primary.ID)) if err != nil { - return fmt.Errorf("Error checking schema %s", err) + return fmt.Errorf("error checking schema %s", err) } if exists { @@ -346,7 +346,7 @@ func testAccCheckPostgresqlSchemaExists(n string, schemaName string) resource.Te exists, err := checkSchemaExists(txn, schemaName) if err != nil { - return fmt.Errorf("Error checking schema %s", err) + return fmt.Errorf("error checking schema %s", err) } if !exists { diff --git a/postgresql/resource_postgresql_security_label.go b/postgresql/resource_postgresql_security_label.go index 626d87fd..c9970d20 100644 --- a/postgresql/resource_postgresql_security_label.go +++ b/postgresql/resource_postgresql_security_label.go @@ -96,7 +96,7 @@ func resourcePostgreSQLSecurityLabelUpdateImpl(db *DBConnection, d *schema.Resou func resourcePostgreSQLSecurityLabelRead(db *DBConnection, d *schema.ResourceData) error { if !db.featureSupported(featureSecurityLabel) { return fmt.Errorf( - "Security Label is not supported for this Postgres version (%s)", + "security Label is not supported for this Postgres version (%s)", db.version, ) } @@ -127,7 +127,7 @@ func resourcePostgreSQLSecurityLabelReadImpl(db *DBConnection, d *schema.Resourc d.SetId("") return nil case err != nil: - return fmt.Errorf("Error reading security label: %w", err) + return fmt.Errorf("error reading security label: %w", err) } if quoteIdentifier(objectName) != newObjectName || quoteIdentifier(provider) != newProvider { @@ -148,7 +148,7 @@ func resourcePostgreSQLSecurityLabelReadImpl(db *DBConnection, d *schema.Resourc func resourcePostgreSQLSecurityLabelDelete(db *DBConnection, d *schema.ResourceData) error { if !db.featureSupported(featureSecurityLabel) { return fmt.Errorf( - "Security Label is not supported for this Postgres version (%s)", + "security Label is not supported for this Postgres version (%s)", db.version, ) } @@ -166,7 +166,7 @@ func resourcePostgreSQLSecurityLabelDelete(db *DBConnection, d *schema.ResourceD func resourcePostgreSQLSecurityLabelUpdate(db *DBConnection, d *schema.ResourceData) error { if !db.featureSupported(featureServer) { return fmt.Errorf( - "Security Label is not supported for this Postgres version (%s)", + "security Label is not supported for this Postgres version (%s)", db.version, ) } diff --git a/postgresql/resource_postgresql_security_label_test.go b/postgresql/resource_postgresql_security_label_test.go index f1701795..0de0868a 100644 --- a/postgresql/resource_postgresql_security_label_test.go +++ b/postgresql/resource_postgresql_security_label_test.go @@ -89,7 +89,7 @@ func checkSecurityLabelExists(txn *sql.Tx, objectType string, objectName string, case err == sql.ErrNoRows: return false, nil case err != nil: - return false, fmt.Errorf("Error reading info about security label: %s", err) + return false, fmt.Errorf("error reading info about security label: %s", err) } return true, nil @@ -113,7 +113,7 @@ func testAccCheckPostgresqlSecurityLabelDestroy(s *terraform.State) error { exists, err := checkSecurityLabelExists(txn, splitted[1], splitted[2], splitted[0]) if err != nil { - return fmt.Errorf("Error checking security label%s", err) + return fmt.Errorf("error checking security label%s", err) } if exists { @@ -160,7 +160,7 @@ func testAccCheckPostgresqlSecurityLabelExists(n string) resource.TestCheckFunc exists, err := checkSecurityLabelExists(txn, objectType, objectName, provider) if err != nil { - return fmt.Errorf("Error checking security label%s", err) + return fmt.Errorf("error checking security label%s", err) } if !exists { diff --git a/postgresql/resource_postgresql_server.go b/postgresql/resource_postgresql_server.go index e1c8e300..daa41237 100644 --- a/postgresql/resource_postgresql_server.go +++ b/postgresql/resource_postgresql_server.go @@ -81,7 +81,7 @@ func resourcePostgreSQLServer() *schema.Resource { func resourcePostgreSQLServerCreate(db *DBConnection, d *schema.ResourceData) error { if !db.featureSupported(featureServer) { return fmt.Errorf( - "Foreign Server resource is not supported for this Postgres version (%s)", + "foreign server resource is not supported for this Postgres version (%s)", db.version, ) } @@ -104,8 +104,8 @@ func resourcePostgreSQLServerCreate(db *DBConnection, d *schema.ResourceData) er if options, ok := d.GetOk(serverOptionsAttr); ok { fmt.Fprint(b, " OPTIONS ( ") cnt := 0 - len := len(options.(map[string]interface{})) - for k, v := range options.(map[string]interface{}) { + len := len(options.(map[string]any)) + for k, v := range options.(map[string]any) { fmt.Fprint(b, " ", pq.QuoteIdentifier(k), " ", pq.QuoteLiteral(v.(string))) if cnt < len-1 { fmt.Fprint(b, ", ") @@ -139,7 +139,7 @@ func resourcePostgreSQLServerCreate(db *DBConnection, d *schema.ResourceData) er } if err = txn.Commit(); err != nil { - return fmt.Errorf("Error creating server: %w", err) + return fmt.Errorf("error creating server: %w", err) } d.SetId(d.Get(serverNameAttr).(string)) @@ -150,7 +150,7 @@ func resourcePostgreSQLServerCreate(db *DBConnection, d *schema.ResourceData) er func resourcePostgreSQLServerRead(db *DBConnection, d *schema.ResourceData) error { if !db.featureSupported(featureServer) { return fmt.Errorf( - "Foreign Server resource is not supported for this Postgres version (%s)", + "foreign server resource is not supported for this Postgres version (%s)", db.version, ) } @@ -178,10 +178,10 @@ func resourcePostgreSQLServerReadImpl(db *DBConnection, d *schema.ResourceData) d.SetId("") return nil case err != nil: - return fmt.Errorf("Error reading foreign server: %w", err) + return fmt.Errorf("error reading foreign server: %w", err) } - mappedOptions := make(map[string]interface{}) + mappedOptions := make(map[string]any) for _, v := range serverOptions { pair := strings.Split(v, "=") mappedOptions[pair[0]] = pair[1] @@ -201,7 +201,7 @@ func resourcePostgreSQLServerReadImpl(db *DBConnection, d *schema.ResourceData) func resourcePostgreSQLServerDelete(db *DBConnection, d *schema.ResourceData) error { if !db.featureSupported(featureServer) { return fmt.Errorf( - "Foreign Server resource is not supported for this Postgres version (%s)", + "foreign server resource is not supported for this Postgres version (%s)", db.version, ) } @@ -225,7 +225,7 @@ func resourcePostgreSQLServerDelete(db *DBConnection, d *schema.ResourceData) er } if err = txn.Commit(); err != nil { - return fmt.Errorf("Error deleting server: %w", err) + return fmt.Errorf("error deleting server: %w", err) } d.SetId("") @@ -236,7 +236,7 @@ func resourcePostgreSQLServerDelete(db *DBConnection, d *schema.ResourceData) er func resourcePostgreSQLServerUpdate(db *DBConnection, d *schema.ResourceData) error { if !db.featureSupported(featureServer) { return fmt.Errorf( - "Foreign Server resource is not supported for this Postgres version (%s)", + "foreign server resource is not supported for this Postgres version (%s)", db.version, ) } @@ -260,7 +260,7 @@ func resourcePostgreSQLServerUpdate(db *DBConnection, d *schema.ResourceData) er } if err = txn.Commit(); err != nil { - return fmt.Errorf("Error updating foreign server: %w", err) + return fmt.Errorf("error updating foreign server: %w", err) } return resourcePostgreSQLServerReadImpl(db, d) @@ -284,11 +284,11 @@ func setServerVersionOptionsIfChanged(txn *sql.Tx, d *schema.ResourceData) error oldOptions, newOptions := d.GetChange(serverOptionsAttr) fmt.Fprint(b, " OPTIONS ( ") cnt := 0 - len := len(newOptions.(map[string]interface{})) - toRemove := oldOptions.(map[string]interface{}) - for k, v := range newOptions.(map[string]interface{}) { + len := len(newOptions.(map[string]any)) + toRemove := oldOptions.(map[string]any) + for k, v := range newOptions.(map[string]any) { operation := "ADD" - if oldOptions.(map[string]interface{})[k] != nil { + if oldOptions.(map[string]any)[k] != nil { operation = "SET" delete(toRemove, k) } @@ -312,7 +312,7 @@ func setServerVersionOptionsIfChanged(txn *sql.Tx, d *schema.ResourceData) error sql := b.String() if _, err := txn.Exec(sql); err != nil { - return fmt.Errorf("Error updating foreign server version and/or options: %w", err) + return fmt.Errorf("error updating foreign server version and/or options: %w", err) } return nil @@ -330,7 +330,7 @@ func setServerNameIfChanged(txn *sql.Tx, d *schema.ResourceData) error { sql := b.String() if _, err := txn.Exec(sql); err != nil { - return fmt.Errorf("Error updating foreign server name: %w", err) + return fmt.Errorf("error updating foreign server name: %w", err) } return nil @@ -352,7 +352,7 @@ func setServerOwner(txn *sql.Tx, d *schema.ResourceData) error { sql := b.String() if _, err := txn.Exec(sql); err != nil { - return fmt.Errorf("Error updating foreign server owner: %w", err) + return fmt.Errorf("error updating foreign server owner: %w", err) } return nil diff --git a/postgresql/resource_postgresql_server_test.go b/postgresql/resource_postgresql_server_test.go index d45069f5..abbded2e 100644 --- a/postgresql/resource_postgresql_server_test.go +++ b/postgresql/resource_postgresql_server_test.go @@ -73,7 +73,7 @@ func testAccCheckPostgresqlServerDestroy(s *terraform.State) error { exists, err := checkServerExists(txn, rs.Primary.ID) if err != nil { - return fmt.Errorf("Error checking foreign server %s", err) + return fmt.Errorf("error checking foreign server %s", err) } if exists { @@ -110,7 +110,7 @@ func testAccCheckPostgresqlServerExists(n string) resource.TestCheckFunc { exists, err := checkServerExists(txn, serverName) if err != nil { - return fmt.Errorf("Error checking foreign server %s", err) + return fmt.Errorf("error checking foreign server %s", err) } if !exists { @@ -208,7 +208,7 @@ func checkServerExists(txn *sql.Tx, serverName string) (bool, error) { case err == sql.ErrNoRows: return false, nil case err != nil: - return false, fmt.Errorf("Error reading info about foreign server: %s", err) + return false, fmt.Errorf("error reading info about foreign server: %s", err) } return true, nil diff --git a/postgresql/resource_postgresql_subscription.go b/postgresql/resource_postgresql_subscription.go index 346bdfae..d0645de0 100644 --- a/postgresql/resource_postgresql_subscription.go +++ b/postgresql/resource_postgresql_subscription.go @@ -128,7 +128,7 @@ func resourcePostgreSQLSubscriptionReadImpl(db *DBConnection, d *schema.Resource queryExists := "SELECT TRUE FROM pg_catalog.pg_stat_subscription WHERE subname = $1" err = txn.QueryRow(queryExists, pqQuoteLiteral(subName)).Scan(&subExists) if err != nil { - return fmt.Errorf("Failed to check subscription: %w", err) + return fmt.Errorf("failed to check subscription: %w", err) } if !subExists { @@ -151,7 +151,7 @@ func resourcePostgreSQLSubscriptionReadImpl(db *DBConnection, d *schema.Resource setPublications, ok := d.GetOk("publications") if !ok { - return fmt.Errorf("Attribute publications is not set") + return fmt.Errorf("attribute publications is not set") } publications := setPublications.(*schema.Set).List() d.Set("publications", publications) @@ -249,7 +249,7 @@ func getPublicationsForSubscription(d *schema.ResourceData) (string, error) { setPublications, ok := d.GetOk("publications") if !ok { - return publicationsString, fmt.Errorf("Attribute publications is not set") + return publicationsString, fmt.Errorf("attribute publications is not set") } publications := setPublications.(*schema.Set).List() @@ -268,7 +268,7 @@ func getConnInfoForSubscription(d *schema.ResourceData) (string, error) { var connInfo string setConnInfo, ok := d.GetOk("conninfo") if !ok { - return connInfo, fmt.Errorf("Attribute conninfo is not set") + return connInfo, fmt.Errorf("attribute conninfo is not set") } return setConnInfo.(string), nil } @@ -296,7 +296,7 @@ func getDBSubscriptionName(d *schema.ResourceData, client *Client) (string, stri if subName == "" { parsed := strings.Split(d.Id(), ".") if len(parsed) != 2 { - return "", "", fmt.Errorf("Subscription ID %s has not the expected format 'database.subscriptionName': %v", d.Id(), parsed) + return "", "", fmt.Errorf("subscription ID %s has not the expected format 'database.subscriptionName': %v", d.Id(), parsed) } database = parsed[0] subName = parsed[1] diff --git a/postgresql/resource_postgresql_subscription_test.go b/postgresql/resource_postgresql_subscription_test.go index f4e4d085..05db4ac7 100644 --- a/postgresql/resource_postgresql_subscription_test.go +++ b/postgresql/resource_postgresql_subscription_test.go @@ -31,7 +31,7 @@ func testAccCheckPostgresqlSubscriptionDestroy(s *terraform.State) error { exists, err := checkSubscriptionExists(txn, getSubscriptionNameFromID(rs.Primary.ID)) if err != nil { - return fmt.Errorf("Error checking subscription %s", err) + return fmt.Errorf("error checking subscription %s", err) } if exists { @@ -41,7 +41,7 @@ func testAccCheckPostgresqlSubscriptionDestroy(s *terraform.State) error { streams, err := checkSubscriptionStreams(txn, getSubscriptionNameFromID(rs.Primary.ID)) if err != nil { - return fmt.Errorf("Error checking subscription %s", err) + return fmt.Errorf("error checking subscription %s", err) } if streams { @@ -60,7 +60,7 @@ func checkSubscriptionExists(txn *sql.Tx, subName string) (bool, error) { case err == sql.ErrNoRows: return false, nil case err != nil: - return false, fmt.Errorf("Error reading info about subscription: %s", err) + return false, fmt.Errorf("error reading info about subscription: %s", err) } return true, nil @@ -74,7 +74,7 @@ func checkSubscriptionStreams(txn *sql.Tx, subName string) (bool, error) { case err == sql.ErrNoRows: return false, nil case err != nil: - return false, fmt.Errorf("Error reading info about subscription: %s", err) + return false, fmt.Errorf("error reading info about subscription: %s", err) } return true, nil @@ -112,7 +112,7 @@ func testAccCheckPostgresqlSubscriptionExists(n string) resource.TestCheckFunc { exists, err := checkSubscriptionExists(txn, subName) if err != nil { - return fmt.Errorf("Error checking subscription %s", err) + return fmt.Errorf("error checking subscription %s", err) } if !exists { @@ -121,7 +121,7 @@ func testAccCheckPostgresqlSubscriptionExists(n string) resource.TestCheckFunc { streams, err := checkSubscriptionStreams(txn, subName) if err != nil { - return fmt.Errorf("Error checking subscription %s", err) + return fmt.Errorf("error checking subscription %s", err) } if !streams { return fmt.Errorf("Subscription not streaming") diff --git a/postgresql/resource_postgresql_user_mapping.go b/postgresql/resource_postgresql_user_mapping.go index 891ef2b0..dcebc2ca 100644 --- a/postgresql/resource_postgresql_user_mapping.go +++ b/postgresql/resource_postgresql_user_mapping.go @@ -55,7 +55,7 @@ func resourcePostgreSQLUserMapping() *schema.Resource { func resourcePostgreSQLUserMappingCreate(db *DBConnection, d *schema.ResourceData) error { if !db.featureSupported(featureServer) { return fmt.Errorf( - "Foreign Server resource is not supported for this Postgres version (%s)", + "foreign server resource is not supported for this Postgres version (%s)", db.version, ) } @@ -70,8 +70,8 @@ func resourcePostgreSQLUserMappingCreate(db *DBConnection, d *schema.ResourceDat if options, ok := d.GetOk(userMappingOptionsAttr); ok { fmt.Fprint(b, " OPTIONS ( ") cnt := 0 - len := len(options.(map[string]interface{})) - for k, v := range options.(map[string]interface{}) { + len := len(options.(map[string]any)) + for k, v := range options.(map[string]any) { fmt.Fprint(b, " ", pq.QuoteIdentifier(k), " ", pq.QuoteLiteral(v.(string))) if cnt < len-1 { fmt.Fprint(b, ", ") @@ -82,7 +82,7 @@ func resourcePostgreSQLUserMappingCreate(db *DBConnection, d *schema.ResourceDat } if _, err := db.Exec(b.String()); err != nil { - return fmt.Errorf("Could not create user mapping: %w", err) + return fmt.Errorf("could not create user mapping: %w", err) } d.SetId(generateUserMappingID(d)) @@ -93,7 +93,7 @@ func resourcePostgreSQLUserMappingCreate(db *DBConnection, d *schema.ResourceDat func resourcePostgreSQLUserMappingRead(db *DBConnection, d *schema.ResourceData) error { if !db.featureSupported(featureServer) { return fmt.Errorf( - "Foreign Server resource is not supported for this Postgres version (%s)", + "foreign server resource is not supported for this Postgres version (%s)", db.version, ) } @@ -127,10 +127,10 @@ func resourcePostgreSQLUserMappingReadImpl(db *DBConnection, d *schema.ResourceD d.SetId("") return nil case err != nil: - return fmt.Errorf("Error reading user mapping: %w", err) + return fmt.Errorf("error reading user mapping: %w", err) } - mappedOptions := make(map[string]interface{}) + mappedOptions := make(map[string]any) for _, v := range userMappingOptions { pair := strings.SplitN(v, "=", 2) mappedOptions[pair[0]] = pair[1] @@ -147,7 +147,7 @@ func resourcePostgreSQLUserMappingReadImpl(db *DBConnection, d *schema.ResourceD func resourcePostgreSQLUserMappingDelete(db *DBConnection, d *schema.ResourceData) error { if !db.featureSupported(featureServer) { return fmt.Errorf( - "Foreign Server resource is not supported for this Postgres version (%s)", + "foreign server resource is not supported for this Postgres version (%s)", db.version, ) } @@ -167,7 +167,7 @@ func resourcePostgreSQLUserMappingDelete(db *DBConnection, d *schema.ResourceDat } if err = txn.Commit(); err != nil { - return fmt.Errorf("Error deleting user mapping: %w", err) + return fmt.Errorf("error deleting user mapping: %w", err) } d.SetId("") @@ -178,7 +178,7 @@ func resourcePostgreSQLUserMappingDelete(db *DBConnection, d *schema.ResourceDat func resourcePostgreSQLUserMappingUpdate(db *DBConnection, d *schema.ResourceData) error { if !db.featureSupported(featureServer) { return fmt.Errorf( - "Foreign Server resource is not supported for this Postgres version (%s)", + "foreign server resource is not supported for this Postgres version (%s)", db.version, ) } @@ -204,11 +204,11 @@ func setUserMappingOptionsIfChanged(db *DBConnection, d *schema.ResourceData) er oldOptions, newOptions := d.GetChange(userMappingOptionsAttr) fmt.Fprint(b, " OPTIONS ( ") cnt := 0 - len := len(newOptions.(map[string]interface{})) - toRemove := oldOptions.(map[string]interface{}) - for k, v := range newOptions.(map[string]interface{}) { + len := len(newOptions.(map[string]any)) + toRemove := oldOptions.(map[string]any) + for k, v := range newOptions.(map[string]any) { operation := "ADD" - if oldOptions.(map[string]interface{})[k] != nil { + if oldOptions.(map[string]any)[k] != nil { operation = "SET" delete(toRemove, k) } @@ -230,7 +230,7 @@ func setUserMappingOptionsIfChanged(db *DBConnection, d *schema.ResourceData) er fmt.Fprint(b, " ) ") if _, err := db.Exec(b.String()); err != nil { - return fmt.Errorf("Error updating user mapping options: %w", err) + return fmt.Errorf("error updating user mapping options: %w", err) } return nil diff --git a/postgresql/resource_postgresql_user_mapping_test.go b/postgresql/resource_postgresql_user_mapping_test.go index 4d17fb10..9ac44dcf 100644 --- a/postgresql/resource_postgresql_user_mapping_test.go +++ b/postgresql/resource_postgresql_user_mapping_test.go @@ -87,7 +87,7 @@ func checkUserMappingExists(txn *sql.Tx, username string, serverName string) (bo case err == sql.ErrNoRows: return false, nil case err != nil: - return false, fmt.Errorf("Error reading info about user mapping: %s", err) + return false, fmt.Errorf("error reading info about user mapping: %s", err) } return true, nil @@ -111,7 +111,7 @@ func testAccCheckPostgresqlUserMappingDestroy(s *terraform.State) error { exists, err := checkUserMappingExists(txn, splitted[0], splitted[1]) if err != nil { - return fmt.Errorf("Error checking user mapping %s", err) + return fmt.Errorf("error checking user mapping %s", err) } if exists { @@ -153,7 +153,7 @@ func testAccCheckPostgresqlUserMappingExists(n string) resource.TestCheckFunc { exists, err := checkUserMappingExists(txn, username, serverName) if err != nil { - return fmt.Errorf("Error checking user mapping %s", err) + return fmt.Errorf("error checking user mapping %s", err) } if !exists { diff --git a/postgresql/utils_test.go b/postgresql/utils_test.go index 5324a935..ac5160a6 100644 --- a/postgresql/utils_test.go +++ b/postgresql/utils_test.go @@ -18,6 +18,12 @@ const ( testRolePassword = "testpwd" ) +func closeDB(t *testing.T, db *sql.DB) { + if err := db.Close(); err != nil { + t.Fatalf("could not close connection to database: %v", err) + } +} + // Can be used in a PreCheck function to disable test based on feature. func testCheckCompatibleVersion(t *testing.T, feature featureName) { client := testAccProvider.Meta().(*Client) @@ -76,12 +82,12 @@ func skipIfNotSuperuser(t *testing.T) { } // dbExecute is a test helper to create a pool, execute one query then close the pool -func dbExecute(t *testing.T, dsn, query string, args ...interface{}) { +func dbExecute(t *testing.T, dsn, query string, args ...any) { db, err := sql.Open("postgres", dsn) if err != nil { t.Fatalf("could to create connection pool: %v", err) } - defer db.Close() + defer closeDB(t, db) // Create the test DB if _, err = db.Exec(query, args...); err != nil { @@ -151,7 +157,7 @@ func createTestTables(t *testing.T, dbSuffix string, tables []string, owner stri if err != nil { t.Fatalf("could not open connection pool for db %s: %v", dbName, err) } - defer db.Close() + defer closeDB(t, db) if owner != "" { if !config.Superuser { @@ -186,7 +192,7 @@ func createTestTables(t *testing.T, dbSuffix string, tables []string, owner stri if err != nil { t.Fatalf("could not open connection pool for db %s: %v", dbName, err) } - defer db.Close() + defer closeDB(t, db) if owner != "" && !config.Superuser { if _, err := db.Exec(fmt.Sprintf("GRANT %s TO CURRENT_USER", owner)); err != nil { @@ -217,7 +223,7 @@ func createTestSchemas(t *testing.T, dbSuffix string, schemas []string, owner st if err != nil { t.Fatalf("could not open connection pool for db %s: %v", dbName, err) } - defer db.Close() + defer closeDB(t, db) if owner != "" { if !config.Superuser { @@ -252,7 +258,7 @@ func createTestSchemas(t *testing.T, dbSuffix string, schemas []string, owner st if err != nil { t.Fatalf("could not open connection pool for db %s: %v", dbName, err) } - defer db.Close() + defer closeDB(t, db) if owner != "" && !config.Superuser { if _, err := db.Exec(fmt.Sprintf("GRANT %s TO CURRENT_USER", owner)); err != nil { @@ -282,7 +288,7 @@ func createTestSequences(t *testing.T, dbSuffix string, sequences []string, owne if err != nil { t.Fatalf("could not open connection pool for db %s: %v", dbName, err) } - defer db.Close() + defer closeDB(t, db) if owner != "" { if !config.Superuser { @@ -316,7 +322,7 @@ func createTestSequences(t *testing.T, dbSuffix string, sequences []string, owne if err != nil { t.Fatalf("could not open connection pool for db %s: %v", dbName, err) } - defer db.Close() + defer closeDB(t, db) if owner != "" && !config.Superuser { if _, err := db.Exec(fmt.Sprintf("GRANT %s TO CURRENT_USER", owner)); err != nil { @@ -371,7 +377,7 @@ func connectAsTestRole(t *testing.T, role, dbName string) *sql.DB { func testCheckTablesPrivileges(t *testing.T, dbName, roleName string, tables []string, allowedPrivileges []string) error { db := connectAsTestRole(t, roleName, dbName) - defer db.Close() + defer closeDB(t, db) for _, table := range tables { queries := map[string]string{ @@ -392,7 +398,7 @@ func testCheckTablesPrivileges(t *testing.T, dbName, roleName string, tables []s func testCheckSchemasPrivileges(t *testing.T, dbName, roleName string, schemas []string, allowedPrivileges []string) error { db := connectAsTestRole(t, roleName, dbName) - defer db.Close() + defer closeDB(t, db) for _, schema := range schemas { queries := map[string]string{ @@ -411,7 +417,7 @@ func testCheckSchemasPrivileges(t *testing.T, dbName, roleName string, schemas [ func testCheckColumnPrivileges(t *testing.T, dbName, roleName string, tables []string, allowedPrivileges []string, columns []string) error { db := connectAsTestRole(t, roleName, dbName) - defer db.Close() + defer closeDB(t, db) columnValues := []string{} for _, col := range columns { diff --git a/tests/docker-compose.yml b/tests/docker-compose.yml index 6eb18a01..8fce16a1 100644 --- a/tests/docker-compose.yml +++ b/tests/docker-compose.yml @@ -1,5 +1,3 @@ -version: "3" - services: postgres: build: