1
0
Fork 0

MySQL storage accepts a config struct

This commit is contained in:
Gregory Eremin 2015-01-11 21:22:34 +07:00
parent 5e5ca78cad
commit a4da88659d
2 changed files with 85 additions and 79 deletions

View File

@ -1,79 +0,0 @@
package mysql
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
"github.com/localhots/steward/steward"
)
type (
MysqlStorage struct {
db *sql.DB
importStmt *sql.Stmt
}
)
const (
importQuery = "" +
"replace into contributions (author, repo, week, commits, additions, deletions) " +
"values (?, ?, ?, ?, ?, ?)"
)
func New(host, user, pass, db string) *MysqlStorage {
var (
s = &MysqlStorage{}
err error
databaseURI = makeDatabaseURI(host, user, pass, db)
)
if s.db, err = sql.Open("mysql", databaseURI); err != nil {
panic(err)
}
if s.importStmt, err = s.db.Prepare(importQuery); err != nil {
panic(err)
}
return s
}
func (ms *MysqlStorage) ImportContributions(contrib []*steward.Contribution) {
for _, c := range contrib {
if _, err := ms.importStmt.Exec(
c.Author,
c.Repo,
c.Week,
c.Commits,
c.Additions,
c.Deletions,
); err != nil {
panic(err)
}
}
}
func makeDatabaseURI(host, user, pass, db string) string {
var (
databaseURI string
)
if user == "" && pass != "" {
panic("Password is set but no is user specified")
}
if user != "" {
databaseURI += user
}
if pass != "" {
databaseURI += ":" + pass
}
if user != "" {
databaseURI += "@"
}
if host != "" {
databaseURI += host
}
databaseURI += "/" + db + "?parseTime=true"
return databaseURI
}

View File

@ -0,0 +1,85 @@
package mysql
import (
"database/sql"
"strconv"
_ "github.com/go-sql-driver/mysql"
"github.com/localhots/steward/steward"
)
type (
Config struct {
Hostname string
Port int
Username string
Password string
Database string
}
Storage struct {
db *sql.DB
importStmt *sql.Stmt
}
)
const (
importQuery = "" +
"replace into contributions (author, repo, week, commits, additions, deletions) " +
"values (?, ?, ?, ?, ?, ?)"
)
func New(c *Config) *Storage {
var (
s = &Storage{}
err error
)
if s.db, err = sql.Open("mysql", c.URI()); err != nil {
panic(err)
}
if s.importStmt, err = s.db.Prepare(importQuery); err != nil {
panic(err)
}
return s
}
func (s *Storage) ImportContributions(contrib []*steward.Contribution) {
for _, c := range contrib {
if _, err := s.importStmt.Exec(
c.Author,
c.Repo,
c.Week,
c.Commits,
c.Additions,
c.Deletions,
); err != nil {
panic(err)
}
}
}
func (c *Config) URI() (uri string) {
if c.Username == "" && c.Password != "" {
panic("Password is set but no username specified")
}
if c.Username != "" {
uri += c.Username
}
if c.Password != "" {
uri += ":" + c.Password
}
if c.Username != "" {
uri += "@"
}
if c.Hostname != "" {
uri += c.Hostname
}
if c.Port != 0 {
uri += ":" + strconv.Itoa(c.Port)
}
uri += "/" + c.Database + "?parseTime=true"
return
}