Skip to content

Commit aeaf7f2

Browse files
committed
added Config.Validate
1 parent 0c2f9a7 commit aeaf7f2

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

config.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,26 @@ type Config struct {
2222
MaxIdleConns int `json:"maxIdleConns,omitempty"`
2323
ConnMaxLifetime time.Duration `json:"connMaxLifetime,omitempty"`
2424
DefaultIsolationLevel sql.IsolationLevel `json:"-"`
25+
Err error `json:"-"`
26+
}
27+
28+
// Validate returns Config.Err if it is not nil
29+
// or an error if the Config does not have
30+
// a Driver, Host, or Database.
31+
func (c *Config) Validate() error {
32+
if c.Err != nil {
33+
return c.Err
34+
}
35+
if c.Driver == "" {
36+
return fmt.Errorf("missing sqldb.Config.Driver")
37+
}
38+
if c.Host == "" {
39+
return fmt.Errorf("missing sqldb.Config.Host")
40+
}
41+
if c.Database == "" {
42+
return fmt.Errorf("missing sqldb.Config.Database")
43+
}
44+
return nil
2545
}
2646

2747
// ConnectURL for connecting to a database
@@ -49,6 +69,10 @@ func (c *Config) ConnectURL() string {
4969
// sets all Config values and performs a ping with ctx.
5070
// The sql.DB will be returned if the ping was successful.
5171
func (c *Config) Connect(ctx context.Context) (*sql.DB, error) {
72+
err := c.Validate()
73+
if err != nil {
74+
return nil, err
75+
}
5276
db, err := sql.Open(c.Driver, c.ConnectURL())
5377
if err != nil {
5478
return nil, err

errors.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ func (e connectionWithError) Stats() sql.DBStats {
9797
}
9898

9999
func (e connectionWithError) Config() *Config {
100-
return &Config{Driver: "ConnectionWithError"}
100+
return &Config{Err: e.err}
101101
}
102102

103103
func (e connectionWithError) Now() (time.Time, error) {

0 commit comments

Comments
 (0)