Skip to content

Commit

Permalink
feat(database): add mysql support (#39)
Browse files Browse the repository at this point in the history
  • Loading branch information
TardC authored Dec 22, 2021
1 parent 8e96962 commit 9d7a5b4
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
3 changes: 3 additions & 0 deletions internal/database/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,15 @@ var (
type DriverType = string

const Sqlite = "sqlite"
const Mysql = "mysql"

func InitDB(driver DriverType, dsn string) (err error) {
Driver = driver
switch driver {
case Sqlite:
DB, err = NewSqlite3(dsn)
case Mysql:
DB, err = NewMysql(dsn)
}
return err
}
14 changes: 14 additions & 0 deletions internal/database/mysql.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package database

import (
"gorm.io/driver/mysql"
"gorm.io/gorm"
)

func NewMysql(dsn string) (*gorm.DB, error) {
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
return nil, err
}
return db, nil
}
11 changes: 10 additions & 1 deletion pkg/server/server.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package server

import (
"github.com/pkg/errors"
"strings"
"sync"

"github.com/gin-gonic/gin"
Expand Down Expand Up @@ -60,7 +62,14 @@ func initDatabase(dsn string) {
Level: log.LevelInfo,
})

err := database.InitDB(database.Sqlite, dsn)
var err error
if strings.Contains(dsn, "@tcp") {
err = database.InitDB(database.Mysql, dsn)
} else if strings.Contains(dsn, ".db") {
err = database.InitDB(database.Sqlite, dsn)
} else {
err = errors.New("unsupported database")
}
if err != nil {
log.Fatal(err.Error())
}
Expand Down

0 comments on commit 9d7a5b4

Please sign in to comment.