/
dsn.go
56 lines (41 loc) · 838 Bytes
/
dsn.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
package database
import (
"fmt"
"net/url"
"os"
"path/filepath"
"strings"
)
func DSNFromURI(uri string) (string, error) {
u, err := url.Parse(uri)
if err != nil {
return "", fmt.Errorf("Failed to parse URI, %w", err)
}
host := u.Host
path := u.Path
q := u.RawQuery
var dsn string
switch host {
case "mem":
dsn = "file::memory:?mode=memory&cache=shared"
case "vfs":
// pass, TBD
default:
if host == "cwd" {
cwd, err := os.Getwd()
if err != nil {
return "", fmt.Errorf("Failed to derived current working directory, %w", err)
}
path = filepath.Join(cwd, path)
}
dsn = fmt.Sprintf("file:%s?cache=shared&mode=rwc", path)
}
if q != "" {
if strings.Contains(dsn, "?") {
dsn = fmt.Sprintf("%s&%s", dsn, q)
} else {
dsn = fmt.Sprintf("%s?%s", dsn, q)
}
}
return dsn, nil
}