This commit is contained in:
2020-09-20 15:42:39 -07:00
parent 37aa21b57e
commit 80465e3f1f
9 changed files with 897 additions and 0 deletions

88
database/manager.go Normal file
View File

@@ -0,0 +1,88 @@
package database
import (
"net/url"
"path/filepath"
"strings"
u "git.eeqj.de/sneak/goutil"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
_ "github.com/jinzhu/gorm/dialects/sqlite"
"github.com/rs/zerolog/log"
"github.com/spf13/viper"
)
type Manager struct {
db *gorm.DB
}
// New creates new Manager
func New() *Manager {
m := new(Manager)
m.init()
return m
}
func (m *Manager) init() {
m.open(viper.GetString("DBURL"))
// breaks stuff, do not use:
//m.db.SingularTable(true)
m.db.LogMode(false)
if viper.GetBool("Debug") {
m.db.LogMode(true)
}
}
func (m *Manager) open(dbURL string) {
log.Info().Msg("opening database")
dsn, err := url.Parse(dbURL)
if err != nil {
log.Panic().
Err(err).
Msg("error parsing dbURL")
}
log.Info().
Str("scheme", dsn.Scheme).
Str("user", dsn.User.Username()).
Str("host", dsn.Host).
Str("db", dsn.Path).
Str("args", dsn.RawQuery).
Msg("db connection values")
switch {
case strings.HasPrefix(dbURL, "postgres://"):
log.Info().Msg("using postgres db")
db, err := gorm.Open("postgres", dbURL)
if err != nil {
log.Panic().
Err(err).
Msg("failed to open database")
}
m.db = db
case strings.HasPrefix(dbURL, "sqlite://"):
log.Info().Msg("using sqlite db")
if !strings.HasSuffix(dbURL, ":memory:") {
dirname := filepath.Dir(strings.TrimPrefix(dbURL, "sqlite://"))
err := u.Mkdirp(dirname)
if err != nil {
log.Panic().
Err(err).
Msg("db path error")
}
}
db, err := gorm.Open("sqlite3", strings.TrimPrefix(dbURL, "sqlite://"))
if err != nil {
log.Panic().
Err(err).
Str("dbURL", dbURL).
Msg("failed to open database")
}
m.db = db
default:
log.Panic().
Str("driver", dsn.Scheme).
Msg("unsupported driver in database url, must be 'postgres' or 'sqlite'")
}
m.doMigrations()
}

31
database/model.go Normal file
View File

@@ -0,0 +1,31 @@
package database
import (
"time"
"github.com/google/uuid"
"github.com/jinzhu/gorm"
"github.com/rs/zerolog/log"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
type User struct {
gorm.Model
UUID uuid.UUID `gorm:"type:uuid;primary_key;"`
Username string `gorm:"unique_index"`
Created time.Time
}
type Post struct {
gorm.Model
UUID uuid.UUID `gorm:"type:uuid;primary_key;"`
Body string
}
// NB that when you add a model below you must add it to this list!
func (m *Manager) doMigrations() {
log.Info().Msg("doing database migrations if required")
m.db.AutoMigrate(&User{})
m.db.AutoMigrate(&Post{})
}