@@ -110,6 +110,52 @@ func GetDBConfigFromEnv(schema string) DBConfig {
110
110
}
111
111
}
112
112
113
+ type DSNType interface {
114
+ DSNString () string
115
+ }
116
+
117
+ type DSNStringType struct {
118
+ Key string
119
+ Value string
120
+ }
121
+
122
+ func (s DSNStringType ) DSNString () string {
123
+ // key='val'. add single quote for better compatibility.
124
+ return fmt .Sprintf ("&%s=%%27%s%%27" , s .Key , url .QueryEscape (s .Value ))
125
+ }
126
+
127
+ type DSNBoolType struct {
128
+ Key string
129
+ Value bool
130
+ }
131
+
132
+ func (b DSNBoolType ) DSNString () string {
133
+ return fmt .Sprintf ("&%s=%t" , b .Key , b .Value )
134
+ }
135
+
136
+ // OpenDB opens a mysql connection FD
137
+ func OpenDBWithDSN (cfg DBConfig , vars []DSNType ) (* sql.DB , error ) {
138
+ var dbDSN string
139
+ if len (cfg .Snapshot ) != 0 {
140
+ log .Info ("create connection with snapshot" , zap .String ("snapshot" , cfg .Snapshot ))
141
+ dbDSN = fmt .Sprintf ("%s:%s@tcp(%s:%d)/?charset=utf8mb4&tidb_snapshot=%s" , cfg .User , cfg .Password , cfg .Host , cfg .Port , cfg .Snapshot )
142
+ } else {
143
+ dbDSN = fmt .Sprintf ("%s:%s@tcp(%s:%d)/?charset=utf8mb4" , cfg .User , cfg .Password , cfg .Host , cfg .Port )
144
+ }
145
+
146
+ for _ , dsnType := range vars {
147
+ dbDSN += dsnType .DSNString ()
148
+ }
149
+
150
+ dbConn , err := sql .Open ("mysql" , dbDSN )
151
+ if err != nil {
152
+ return nil , errors .Trace (err )
153
+ }
154
+
155
+ err = dbConn .Ping ()
156
+ return dbConn , errors .Trace (err )
157
+ }
158
+
113
159
// OpenDB opens a mysql connection FD
114
160
func OpenDB (cfg DBConfig , vars map [string ]string ) (* sql.DB , error ) {
115
161
var dbDSN string
0 commit comments