| 1 | // Package sqliteuri builds SQLite file URIs for local disk databases. |
| 2 | package sqliteuri |
| 3 | |
| 4 | import ( |
| 5 | "errors" |
| 6 | "net/url" |
| 7 | "path/filepath" |
| 8 | "runtime" |
| 9 | "strings" |
| 10 | ) |
| 11 | |
| 12 | // Disk converts a local disk path into an absolute SQLite file URI. Query |
| 13 | // parameters are encoded separately from the path so path punctuation cannot |
| 14 | // be interpreted as SQLite options. |
| 15 | func Disk(path string, query url.Values) (string, error) { |
| 16 | if strings.TrimSpace(path) == "" { |
| 17 | return "", errors.New("sqlite disk path is empty") |
| 18 | } |
| 19 | abs, err := filepath.Abs(path) |
| 20 | if err != nil { |
| 21 | return "", err |
| 22 | } |
| 23 | return disk(abs, query, runtime.GOOS), nil |
| 24 | } |
| 25 | |
| 26 | func disk(absPath string, query url.Values, goos string) string { |
| 27 | slash := filepath.ToSlash(absPath) |
| 28 | if goos == "windows" { |
| 29 | slash = strings.ReplaceAll(slash, `\`, "/") |
| 30 | if len(slash) >= 2 && slash[1] == ':' { |
| 31 | slash = "/" + slash |
| 32 | } |
| 33 | } |
| 34 | u := &url.URL{Scheme: "file", Path: slash} |
| 35 | u.RawQuery = query.Encode() |
| 36 | return u.String() |
| 37 | } |
| 38 |