Skip to content

Commit

Permalink
Refactoring: remove deprecated function calls, use our functions (#146)
Browse files Browse the repository at this point in the history
* Refactoring: remove deprecated function calls, use our functions

This should change no functionality at all

* Add forgotten file
  • Loading branch information
petoju authored May 6, 2024
1 parent 88c3e5c commit 841718b
Show file tree
Hide file tree
Showing 20 changed files with 214 additions and 218 deletions.
4 changes: 2 additions & 2 deletions mysql/data_source_tables.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"log"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/id"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

Expand Down Expand Up @@ -69,7 +69,7 @@ func ShowTables(ctx context.Context, d *schema.ResourceData, meta interface{}) d
return diag.Errorf("failed setting tables field: %v", err)
}

d.SetId(resource.UniqueId())
d.SetId(id.UniqueId())

return nil
}
22 changes: 11 additions & 11 deletions mysql/data_source_tables_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,16 @@ import (

func TestAccDataSourceTables(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
PreCheck: func() { testAccPreCheck(t) },
ProviderFactories: testAccProviderFactories,
Steps: []resource.TestStep{
{
Config: testAccTablesConfig_basic("mysql", "%"),
Config: testAccTablesConfigBasic("mysql", "%"),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("data.mysql_tables.test", "database", "mysql"),
resource.TestCheckResourceAttr("data.mysql_tables.test", "pattern", "%"),
testAccTablesCount("data.mysql_tables.test", "tables.#", func(rn string, table_count int) error {
if table_count < 1 {
testAccTablesCount("data.mysql_tables.test", "tables.#", func(rn string, tableCount int) error {
if tableCount < 1 {
return fmt.Errorf("%s: tables not found", rn)
}

Expand All @@ -29,12 +29,12 @@ func TestAccDataSourceTables(t *testing.T) {
),
},
{
Config: testAccTablesConfig_basic("mysql", "__table_does_not_exist__"),
Config: testAccTablesConfigBasic("mysql", "__table_does_not_exist__"),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("data.mysql_tables.test", "database", "mysql"),
resource.TestCheckResourceAttr("data.mysql_tables.test", "pattern", "__table_does_not_exist__"),
testAccTablesCount("data.mysql_tables.test", "tables.#", func(rn string, table_count int) error {
if table_count > 0 {
testAccTablesCount("data.mysql_tables.test", "tables.#", func(rn string, tableCount int) error {
if tableCount > 0 {
return fmt.Errorf("%s: unexpected table found", rn)
}

Expand All @@ -60,17 +60,17 @@ func testAccTablesCount(rn string, key string, check func(string, int) error) re
return fmt.Errorf("%s: attribute '%s' not found", rn, key)
}

table_count, err := strconv.Atoi(value)
tableCount, err := strconv.Atoi(value)

if err != nil {
return err
}

return check(rn, table_count)
return check(rn, tableCount)
}
}

func testAccTablesConfig_basic(database string, pattern string) string {
func testAccTablesConfigBasic(database string, pattern string) string {
return fmt.Sprintf(`
data "mysql_tables" "test" {
database = "%s"
Expand Down
60 changes: 17 additions & 43 deletions mysql/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import (
"crypto/x509"
"database/sql"
"encoding/json"
"errors"
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry"
"log"
"net"
"net/url"
Expand All @@ -19,10 +19,7 @@ import (

"github.com/go-sql-driver/mysql"
"github.com/hashicorp/go-version"
"google.golang.org/api/googleapi"

"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"

Expand Down Expand Up @@ -83,7 +80,7 @@ func Provider() *schema.Provider {
ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
value := v.(string)
if value == "" {
errors = append(errors, fmt.Errorf("Endpoint must not be an empty string"))
errors = append(errors, fmt.Errorf("endpoint must not be an empty string"))
}

return
Expand Down Expand Up @@ -219,8 +216,8 @@ func providerConfigure(ctx context.Context, d *schema.ResourceData) (interface{}
var allowClearTextPasswords = authPlugin == cleartextPasswords
var allowNativePasswords = authPlugin == nativePasswords
var password = d.Get("password").(string)
var iam_auth = d.Get("iam_database_authentication").(bool)
var private_ip = d.Get("private_ip").(bool)
var iamAuth = d.Get("iam_database_authentication").(bool)
var privateIp = d.Get("private_ip").(bool)
var tlsConfig = d.Get("tls").(string)
var tlsConfigStruct *tls.Config

Expand All @@ -230,12 +227,12 @@ func providerConfigure(ctx context.Context, d *schema.ResourceData) (interface{}
customMap := customTLSMap[0].(map[string]interface{})
customTLSJson, err := json.Marshal(customMap)
if err != nil {
return nil, diag.Errorf("failed to marshal tls config: %v", customTLSMap)
return nil, diag.Errorf("failed to marshal tls config %v with error %v", customTLSMap, err)
}

err = json.Unmarshal(customTLSJson, &customTLS)
if err != nil {
return nil, diag.Errorf("failed to unmarshal tls config: %v", customTLSJson)
return nil, diag.Errorf("failed to unmarshal tls config %v with error %v", customTLSJson, err)
}

var pem []byte
Expand Down Expand Up @@ -269,7 +266,10 @@ func providerConfigure(ctx context.Context, d *schema.ResourceData) (interface{}
RootCAs: rootCertPool,
Certificates: clientCert,
}
mysql.RegisterTLSConfig(customTLS.ConfigKey, tlsConfigStruct)
err = mysql.RegisterTLSConfig(customTLS.ConfigKey, tlsConfigStruct)
if err != nil {
return nil, diag.Errorf("failed registering TLS config: %v", err)
}
tlsConfig = customTLS.ConfigKey
}

Expand All @@ -280,7 +280,7 @@ func providerConfigure(ctx context.Context, d *schema.ResourceData) (interface{}
proto = "cloudsql"
endpoint = strings.ReplaceAll(endpoint, "cloudsql://", "")
var err error
if iam_auth { // Access token will be in the password field
if iamAuth { // Access token will be in the password field

var opts []cloudsqlconn.Option

Expand All @@ -292,7 +292,7 @@ func providerConfigure(ctx context.Context, d *schema.ResourceData) (interface{}
_, err = cloudsql.RegisterDriver("cloudsql", opts...)
} else {
var endpointParams []cloudsqlconn.DialOption
if private_ip {
if privateIp {
endpointParams = append(endpointParams, cloudsqlconn.WithPrivateIP())
}

Expand Down Expand Up @@ -508,22 +508,22 @@ func createNewConnection(ctx context.Context, conf *MySQLConfiguration) (*OneCon
// when Terraform thinks it's available and when it is actually available.
// This is particularly acute when provisioning a server and then immediately
// trying to provision a database on it.
retryError := resource.RetryContext(ctx, conf.ConnectRetryTimeoutSec, func() *resource.RetryError {
retryError := retry.RetryContext(ctx, conf.ConnectRetryTimeoutSec, func() *retry.RetryError {
db, err = sql.Open(driverName, conf.Config.FormatDSN())
if err != nil {
if mysqlErrorNumber(err) != 0 || cloudsqlErrorNumber(err) != 0 || ctx.Err() != nil {
return resource.NonRetryableError(err)
return retry.NonRetryableError(err)
}
return resource.RetryableError(err)
return retry.RetryableError(err)
}

err = db.PingContext(ctx)
if err != nil {
if mysqlErrorNumber(err) != 0 || cloudsqlErrorNumber(err) != 0 || ctx.Err() != nil {
return resource.NonRetryableError(err)
return retry.NonRetryableError(err)
}

return resource.RetryableError(err)
return retry.RetryableError(err)
}

return nil
Expand All @@ -549,29 +549,3 @@ func createNewConnection(ctx context.Context, conf *MySQLConfiguration) (*OneCon
Version: currentVersion,
}, nil
}

// 0 == not mysql error or not error at all.
func mysqlErrorNumber(err error) uint16 {
if err == nil {
return 0
}
me, ok := err.(*mysql.MySQLError)
if !ok {
return 0
}
return me.Number
}

func cloudsqlErrorNumber(err error) int {
if err == nil {
return 0
}

var gapiError *googleapi.Error
if errors.As(err, &gapiError) {
if gapiError.Code >= 400 && gapiError.Code < 500 {
return gapiError.Code
}
}
return 0
}
10 changes: 6 additions & 4 deletions mysql/provider_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,15 @@ import (
// You can run the tests like this:
// make testacc TEST=./builtin/providers/mysql

var testAccProviders map[string]*schema.Provider
var testAccProviderFactories map[string]func() (*schema.Provider, error)

// var testAccProviders map[string]*schema.Provider
var testAccProvider *schema.Provider

func init() {
testAccProvider = Provider()
testAccProviders = map[string]*schema.Provider{
"mysql": testAccProvider,
testAccProviderFactories = map[string]func() (*schema.Provider, error){
"mysql": func() (*schema.Provider, error) { return testAccProvider, nil },
}
}

Expand All @@ -47,7 +49,7 @@ func TestProvider(t *testing.T) {
}

func TestProvider_impl(t *testing.T) {
var _ *schema.Provider = Provider()
var _ = Provider()
}

func testAccPreCheck(t *testing.T) {
Expand Down
9 changes: 3 additions & 6 deletions mysql/resource_database.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"log"
"strings"

"github.com/go-sql-driver/mysql"
"github.com/hashicorp/go-version"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
Expand Down Expand Up @@ -102,11 +101,9 @@ func ReadDatabase(ctx context.Context, d *schema.ResourceData, meta interface{})
var createSQL, _database string
err = db.QueryRowContext(ctx, stmtSQL).Scan(&_database, &createSQL)
if err != nil {
if mysqlErr, ok := err.(*mysql.MySQLError); ok {
if mysqlErr.Number == unknownDatabaseErrCode {
d.SetId("")
return nil
}
if mysqlErrorNumber(err) == unknownDatabaseErrCode {
d.SetId("")
return nil
}
return diag.Errorf("Error during show create database: %s", err)
}
Expand Down
46 changes: 21 additions & 25 deletions mysql/resource_database_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,25 @@ import (
"strings"
"testing"

"github.com/go-sql-driver/mysql"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
)

func TestAccDatabase(t *testing.T) {
dbName := "terraform_acceptance_test"
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheckSkipTiDB(t) },
Providers: testAccProviders,
CheckDestroy: testAccDatabaseCheckDestroy(dbName),
PreCheck: func() { testAccPreCheckSkipTiDB(t) },
ProviderFactories: testAccProviderFactories,
CheckDestroy: testAccDatabaseCheckDestroy(dbName),
Steps: []resource.TestStep{
{
Config: testAccDatabaseConfig_basic(dbName),
Check: testAccDatabaseCheck_basic(
Config: testAccDatabaseConfigBasic(dbName),
Check: testAccDatabaseCheckBasic(
"mysql_database.test", dbName,
),
},
{
Config: testAccDatabaseConfig_basic(dbName),
Config: testAccDatabaseConfigBasic(dbName),
ResourceName: "mysql_database.test",
ImportState: true,
ImportStateVerify: true,
Expand All @@ -48,14 +46,14 @@ func TestAccDatabase_collationChange(t *testing.T) {
ctx := context.Background()

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheckSkipTiDB(t) },
Providers: testAccProviders,
CheckDestroy: testAccDatabaseCheckDestroy(dbName),
PreCheck: func() { testAccPreCheckSkipTiDB(t) },
ProviderFactories: testAccProviderFactories,
CheckDestroy: testAccDatabaseCheckDestroy(dbName),
Steps: []resource.TestStep{
{
Config: testAccDatabaseConfig_full(dbName, charset1, collation1),
Config: testAccDatabaseConfigFull(dbName, charset1, collation1),
Check: resource.ComposeTestCheckFunc(
testAccDatabaseCheck_full("mysql_database.test", dbName, charset1, collation1),
testAccDatabaseCheckFull("mysql_database.test", dbName, charset1, collation1),
),
},
{
Expand All @@ -72,20 +70,20 @@ func TestAccDatabase_collationChange(t *testing.T) {

db.Exec(fmt.Sprintf("ALTER DATABASE %s CHARACTER SET %s COLLATE %s", dbName, charset2, collation2))
},
Config: testAccDatabaseConfig_full(dbName, charset1, collation1),
Config: testAccDatabaseConfigFull(dbName, charset1, collation1),
Check: resource.ComposeTestCheckFunc(
testAccDatabaseCheck_full(resourceName, dbName, charset1, collation1),
testAccDatabaseCheckFull(resourceName, dbName, charset1, collation1),
),
},
},
})
}

func testAccDatabaseCheck_basic(rn string, name string) resource.TestCheckFunc {
return testAccDatabaseCheck_full(rn, name, "utf8mb4", "utf8mb4_bin")
func testAccDatabaseCheckBasic(rn string, name string) resource.TestCheckFunc {
return testAccDatabaseCheckFull(rn, name, "utf8mb4", "utf8mb4_bin")
}

func testAccDatabaseCheck_full(rn string, name string, charset string, collation string) resource.TestCheckFunc {
func testAccDatabaseCheckFull(rn string, name string, charset string, collation string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[rn]
if !ok {
Expand Down Expand Up @@ -133,21 +131,19 @@ func testAccDatabaseCheckDestroy(name string) resource.TestCheckFunc {
return fmt.Errorf("database still exists after destroy")
}

if mysqlErr, ok := err.(*mysql.MySQLError); ok {
if mysqlErr.Number == unknownDatabaseErrCode {
return nil
}
if mysqlErrorNumber(err) == unknownDatabaseErrCode {
return nil
}

return fmt.Errorf("got unexpected error: %s", err)
}
}

func testAccDatabaseConfig_basic(name string) string {
return testAccDatabaseConfig_full(name, "utf8mb4", "utf8mb4_bin")
func testAccDatabaseConfigBasic(name string) string {
return testAccDatabaseConfigFull(name, "utf8mb4", "utf8mb4_bin")
}

func testAccDatabaseConfig_full(name string, charset string, collation string) string {
func testAccDatabaseConfigFull(name string, charset string, collation string) string {
return fmt.Sprintf(`
resource "mysql_database" "test" {
name = "%s"
Expand Down
4 changes: 2 additions & 2 deletions mysql/resource_default_roles_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ func TestAccDefaultRoles_basic(t *testing.T) {
testAccPreCheckSkipNotMySQL8(t)
testAccPreCheckSkipMariaDB(t)
},
Providers: testAccProviders,
CheckDestroy: testAccDefaultRolesCheckDestroy,
ProviderFactories: testAccProviderFactories,
CheckDestroy: testAccDefaultRolesCheckDestroy,
Steps: []resource.TestStep{
{
Config: testAccDefaultRoles_basic,
Expand Down
Loading

0 comments on commit 841718b

Please sign in to comment.