-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatasource.go
69 lines (56 loc) · 1.5 KB
/
datasource.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// Copyright (c) 2022, Geert JM Vanderkelen
package pxmysql
import (
"fmt"
"github.com/golistic/xgo/xconv"
"github.com/golistic/xgo/xsql"
)
// DataSource defines the configuration of the connection. It embeds xsql.DataSource
// and extends it with attributes defined in the Options.
type DataSource struct {
xsql.DataSource
UseTLS bool
}
// NewDataSource instantiates a DataSource using the Data Source Name (DSN).
func NewDataSource(name string) (DataSource, error) {
xds, err := xsql.ParseDSN(name)
if err != nil {
return DataSource{}, err
}
ds := DataSource{
DataSource: *xds,
UseTLS: false,
}
if err := ds.handleOptions(); err != nil {
return DataSource{}, err
}
if err := ds.CheckValidity(); err != nil {
return DataSource{}, fmt.Errorf("configuration not valid (%w)", err)
}
return ds, nil
}
// CheckValidity returns whether the DataSource has enough configuration to establish
// a connection. Needed are the address, protocol, and username.
func (ds *DataSource) CheckValidity() error {
switch {
case ds.Address == "":
return fmt.Errorf("address missing")
case ds.User == "":
return fmt.Errorf("user missing")
case ds.Protocol == "":
return fmt.Errorf("protocol missing")
default:
return nil
}
}
func (ds *DataSource) handleOptions() error {
var err error
useTLS := ds.Options.Get("useTLS")
if useTLS != "" {
ds.UseTLS, err = xconv.ParseBool(useTLS)
if err != nil {
return fmt.Errorf("invalid value for useTLS option (was %s)", useTLS)
}
}
return nil
}