1
0
Fork 0

Database setup and basic models

This commit is contained in:
Gregory Eremin 2015-03-05 02:09:08 +07:00
parent 3216f261c3
commit cd6fb6923a
3 changed files with 85 additions and 0 deletions

34
db/common.go Normal file
View File

@ -0,0 +1,34 @@
package db
import (
"database/sql"
)
var (
conn *sql.DB
stmts map[string]*sql.Stmt
)
func Connect(uri string) (err error) {
conn, err = sql.Open("mysql", uri)
stmts = map[string]*sql.Stmt{}
return
}
func stmt(query string) *sql.Stmt {
if stmt, ok := stmts[query]; ok {
return stmt
} else {
stmt := prepareStatement(query)
stmts[query] = stmt
return stmt
}
}
func prepareStatement(query string) *sql.Stmt {
if stmt, err = conn.Prepare(query); err == nil {
return stmt
} else {
panic(err)
}
}

29
db/contrib.go Normal file
View File

@ -0,0 +1,29 @@
package db
import (
"github.com/fatih/structs"
)
type (
Contrib struct {
Week int64
Author string
Owner string
Repo string
Commits int
Additions int
Deletions int
}
)
const (
importContribQuery = "" +
"replace into contributions (week, author, owner, repo, commits, additions, deletions) " +
"values (?, ?, ?, ?, ?, ?, ?)"
)
func ImportContrib(c *Contrib) {
if _, err := stmt(importContribQuery).Exec(structs.Values(c)); err != nil {
panic(err)
}
}

22
db/repo.go Normal file
View File

@ -0,0 +1,22 @@
package db
import (
"github.com/fatih/structs"
)
type (
Repo struct {
Owner string
Name string
}
)
const (
repoImportQuery = "replace into repos (owner, name, updated_at) values (?, ?, now())"
)
func ImportRepo(r *Repo) {
if _, err := stmt(repoImportQuery).Exec(structs.Values(r)); err != nil {
panic(err)
}
}