-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdb.go
38 lines (33 loc) · 853 Bytes
/
db.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
package main
import (
"database/sql"
"net/url"
"strings"
_ "github.com/go-sql-driver/mysql"
_ "github.com/lib/pq"
_ "github.com/mattn/go-sqlite3"
)
func normalizeDbUrl(provider string, dbUrl string) string {
switch provider {
case "sqlite3", "mysql":
return strings.TrimPrefix(dbUrl, provider+"://")
default:
return dbUrl
}
return dbUrl
}
func dbDataFromUrl(dbConnectionString string) (string, string, error) {
dbUrl, err := url.Parse(dbConnectionString)
if err != nil {
return "", "", err
}
return dbUrl.Scheme, normalizeDbUrl(dbUrl.Scheme, dbUrl.String()), nil
}
func ConnectToDb(dbConnectionString string) (*sql.DB, string, error) {
driverName, dataSourceName, err := dbDataFromUrl(dbConnectionString)
if err != nil {
return nil, "", err
}
db, err := sql.Open(driverName, dataSourceName)
return db, driverName, err
}