ussd/internal/storage/parse.go

87 lines
1.3 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 (
DBTYPE_MEM = iota
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-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
}
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
}
return o, fmt.Errorf("invalid connection string: %s", connStr)
2025-01-04 09:40:43 +01:00
}