visedriver/storage/parse.go

122 lines
1.8 KiB
Go
Raw Normal View History

2025-01-04 09:40:43 +01:00
package storage
2025-01-04 10:37:12 +01:00
import (
"fmt"
"net/url"
"path"
)
2025-01-04 09:40:43 +01:00
const (
2025-01-13 22:33:25 +01:00
DBTYPE_NONE = iota
DBTYPE_MEM
2025-01-14 19:57:04 +01:00
DBTYPE_FS
2025-01-04 09:40:43 +01:00
DBTYPE_GDBM
DBTYPE_POSTGRES
)
type ConnData struct {
2025-01-04 09:40:43 +01:00
typ int
str string
2025-01-09 08:42:09 +01:00
domain string
2025-01-04 09:40:43 +01:00
}
func (cd *ConnData) DbType() int {
2025-01-04 10:37:12 +01:00
return cd.typ
}
func (cd *ConnData) String() string {
2025-01-04 10:37:12 +01:00
return cd.str
}
2025-01-09 08:42:09 +01:00
func (cd *ConnData) Domain() string {
return cd.domain
}
func (cd *ConnData) Path() string {
v, _ := url.Parse(cd.str)
v.RawQuery = ""
return v.String()
}
func probePostgres(s string) (string, string, bool) {
domain := "public"
2025-01-04 10:37:12 +01:00
v, err := url.Parse(s)
if err != nil {
2025-01-09 08:42:09 +01:00
return "", "", false
2025-01-04 10:37:12 +01:00
}
if v.Scheme != "postgres" {
2025-01-09 08:42:09 +01:00
return "", "", false
}
vv := v.Query()
if vv.Has("search_path") {
domain = vv.Get("search_path")
2025-01-04 10:37:12 +01:00
}
2025-01-09 08:42:09 +01:00
return s, domain, true
2025-01-04 10:37:12 +01:00
}
2025-01-09 08:42:09 +01:00
func probeGdbm(s string) (string, string, bool) {
2025-01-14 19:57:04 +01:00
domain := "public"
v, err := url.Parse(s)
if err != nil {
return "", "", false
}
if v.Scheme != "gdbm" {
return "", "", false
}
2025-01-15 01:32:56 +01:00
s = v.Path
2025-01-14 19:57:04 +01:00
return s, domain, true
}
func probeFs(s string) (string, string, bool) {
2025-01-04 10:37:12 +01:00
if !path.IsAbs(s) {
2025-01-09 08:42:09 +01:00
return "", "", false
2025-01-04 10:37:12 +01:00
}
s = path.Clean(s)
2025-01-09 08:42:09 +01:00
return s, "", true
2025-01-04 10:37:12 +01:00
}
2025-01-14 19:57:04 +01:00
func probeMem(s string) (string, string, bool) {
if s != "" {
return "", "", false
}
return "", "", true
}
func ToConnData(connStr string) (ConnData, error) {
var o ConnData
2025-01-04 09:40:43 +01:00
2025-01-04 10:37:12 +01:00
if connStr == "" {
return o, nil
2025-01-04 09:40:43 +01:00
}
2025-01-04 10:37:12 +01:00
2025-01-09 08:42:09 +01:00
v, domain, ok := probePostgres(connStr)
2025-01-04 10:37:12 +01:00
if ok {
o.typ = DBTYPE_POSTGRES
o.str = v
2025-01-09 08:42:09 +01:00
o.domain = domain
2025-01-04 10:37:12 +01:00
return o, nil
}
2025-01-09 08:42:09 +01:00
v, _, ok = probeGdbm(connStr)
2025-01-04 10:37:12 +01:00
if ok {
o.typ = DBTYPE_GDBM
o.str = v
return o, nil
}
2025-01-14 19:57:04 +01:00
v, _, ok = probeFs(connStr)
if ok {
o.typ = DBTYPE_FS
o.str = v
return o, nil
}
v, _, ok = probeMem(connStr)
if ok {
o.typ = DBTYPE_MEM
return o, nil
}
2025-01-04 10:37:12 +01:00
return o, fmt.Errorf("invalid connection string: %s", connStr)
2025-01-04 09:40:43 +01:00
}