twitch-bot-streak/pkg/database/db.go
Knut Ahlers f1d35ce7c0
Switch to properly tested database interface
and with that support all databases the bot does support

Signed-off-by: Knut Ahlers <knut@ahlers.me>
2024-03-24 13:29:57 +01:00

70 lines
1.2 KiB
Go

package database
import (
"fmt"
"github.com/glebarez/sqlite"
"github.com/pkg/errors"
"gorm.io/driver/mysql"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
type (
DB struct {
db *gorm.DB
}
)
// New creates a new DB with the given driver and database
func New(driverName, connString string) (d *DB, err error) {
var innerDB gorm.Dialector
switch driverName {
case "mysql":
innerDB = mysql.Open(connString)
case "postgres":
innerDB = postgres.Open(connString)
case "sqlite":
innerDB = sqlite.Open(connString)
default:
return nil, errors.Errorf("unknown database driver %s", driverName)
}
db, err := gorm.Open(innerDB, &gorm.Config{
DisableForeignKeyConstraintWhenMigrating: true,
})
if err != nil {
return nil, errors.Wrap(err, "connecting database")
}
d = &DB{
db: db,
}
if err = db.AutoMigrate(
&StreakMeta{},
&StreakUser{},
); err != nil {
return nil, fmt.Errorf("applying schema: %w", err)
}
return d, nil
}
// Close closes the underlying database
func (d DB) Close() error {
sdb, err := d.db.DB()
if err != nil {
return fmt.Errorf("getting underlying database: %w", err)
}
if err = sdb.Close(); err != nil {
return fmt.Errorf("closing db: %w", err)
}
return nil
}