feat: migrations
This commit is contained in:
@ -2,30 +2,15 @@ package database
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"net/url"
|
||||
"regexp"
|
||||
|
||||
"github.com/stephenafamo/bob"
|
||||
_ "modernc.org/sqlite" // Sqlite
|
||||
)
|
||||
|
||||
func NewSQLiteConnection(name string) (*bob.DB, error) {
|
||||
// Find config diretory
|
||||
configDir, err := os.UserConfigDir()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Create database directory if not exists
|
||||
settingsPath := filepath.Join(configDir, "trevstack")
|
||||
err = os.MkdirAll(settingsPath, 0766)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Open database
|
||||
dbPath := filepath.Join(settingsPath, name)
|
||||
db, err := sql.Open("sqlite", dbPath)
|
||||
func NewSQLiteConnection(url *url.URL) (*bob.DB, error) {
|
||||
db, err := sql.Open("sqlite", sqliteConnectionString(url))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -35,3 +20,47 @@ func NewSQLiteConnection(name string) (*bob.DB, error) {
|
||||
|
||||
return &bobdb, nil
|
||||
}
|
||||
|
||||
// ConnectionString converts a URL into a valid connection string
|
||||
func sqliteConnectionString(u *url.URL) string {
|
||||
// duplicate URL and remove scheme
|
||||
newURL := *u
|
||||
newURL.Scheme = ""
|
||||
|
||||
if newURL.Opaque == "" && newURL.Path != "" {
|
||||
// When the DSN is in the form "scheme:/absolute/path" or
|
||||
// "scheme://absolute/path" or "scheme:///absolute/path", url.Parse
|
||||
// will consider the file path as :
|
||||
// - "absolute" as the hostname
|
||||
// - "path" (and the rest until "?") as the URL path.
|
||||
// Instead, when the DSN is in the form "scheme:", the (relative) file
|
||||
// path is stored in the "Opaque" field.
|
||||
// See: https://pkg.go.dev/net/url#URL
|
||||
//
|
||||
// While Opaque is not escaped, the URL Path is. So, if .Path contains
|
||||
// the file path, we need to un-escape it, and rebuild the full path.
|
||||
|
||||
newURL.Opaque = "//" + newURL.Host + mustUnescapePath(newURL.Path)
|
||||
newURL.Path = ""
|
||||
}
|
||||
|
||||
// trim duplicate leading slashes
|
||||
str := regexp.MustCompile("^//+").ReplaceAllString(newURL.String(), "/")
|
||||
|
||||
return str
|
||||
}
|
||||
|
||||
// MustUnescapePath unescapes a URL path, and panics if it fails.
|
||||
// It is used during in cases where we are parsing a generated path.
|
||||
func mustUnescapePath(s string) string {
|
||||
if s == "" {
|
||||
panic("missing path")
|
||||
}
|
||||
|
||||
path, err := url.PathUnescape(s)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return path
|
||||
}
|
||||
|
Reference in New Issue
Block a user