github.com/pmcatominey/terraform@v0.7.0-rc2.0.20160708105029-1401a52a5cc5/builtin/providers/mysql/provider.go (about)

     1  package mysql
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	mysqlc "github.com/ziutek/mymysql/thrsafe"
     8  
     9  	"github.com/hashicorp/terraform/helper/schema"
    10  	"github.com/hashicorp/terraform/terraform"
    11  )
    12  
    13  func Provider() terraform.ResourceProvider {
    14  	return &schema.Provider{
    15  		Schema: map[string]*schema.Schema{
    16  			"endpoint": &schema.Schema{
    17  				Type:        schema.TypeString,
    18  				Required:    true,
    19  				DefaultFunc: schema.EnvDefaultFunc("MYSQL_ENDPOINT", nil),
    20  				ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
    21  					value := v.(string)
    22  					if value == "" {
    23  						errors = append(errors, fmt.Errorf("Endpoint must not be an empty string"))
    24  					}
    25  
    26  					return
    27  				},
    28  			},
    29  
    30  			"username": &schema.Schema{
    31  				Type:        schema.TypeString,
    32  				Required:    true,
    33  				DefaultFunc: schema.EnvDefaultFunc("MYSQL_USERNAME", nil),
    34  				ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
    35  					value := v.(string)
    36  					if value == "" {
    37  						errors = append(errors, fmt.Errorf("Username must not be an empty string"))
    38  					}
    39  
    40  					return
    41  				},
    42  			},
    43  
    44  			"password": &schema.Schema{
    45  				Type:        schema.TypeString,
    46  				Optional:    true,
    47  				DefaultFunc: schema.EnvDefaultFunc("MYSQL_PASSWORD", nil),
    48  			},
    49  		},
    50  
    51  		ResourcesMap: map[string]*schema.Resource{
    52  			"mysql_database": resourceDatabase(),
    53  		},
    54  
    55  		ConfigureFunc: providerConfigure,
    56  	}
    57  }
    58  
    59  func providerConfigure(d *schema.ResourceData) (interface{}, error) {
    60  
    61  	var username = d.Get("username").(string)
    62  	var password = d.Get("password").(string)
    63  	var endpoint = d.Get("endpoint").(string)
    64  
    65  	proto := "tcp"
    66  	if endpoint[0] == '/' {
    67  		proto = "unix"
    68  	}
    69  
    70  	// mysqlc is the thread-safe implementation of mymysql, so we can
    71  	// safely re-use the same connection between multiple parallel
    72  	// operations.
    73  	conn := mysqlc.New(proto, "", endpoint, username, password)
    74  
    75  	err := conn.Connect()
    76  	if err != nil {
    77  		return nil, err
    78  	}
    79  
    80  	return conn, nil
    81  }
    82  
    83  var identQuoteReplacer = strings.NewReplacer("`", "``")
    84  
    85  func quoteIdentifier(in string) string {
    86  	return fmt.Sprintf("`%s`", identQuoteReplacer.Replace(in))
    87  }