From cd6fb6923a4f587cdf48240a44af8922e6e3f95e Mon Sep 17 00:00:00 2001 From: Gregory Eremin Date: Thu, 5 Mar 2015 02:09:08 +0700 Subject: [PATCH] Database setup and basic models --- db/common.go | 34 ++++++++++++++++++++++++++++++++++ db/contrib.go | 29 +++++++++++++++++++++++++++++ db/repo.go | 22 ++++++++++++++++++++++ 3 files changed, 85 insertions(+) create mode 100644 db/common.go create mode 100644 db/contrib.go create mode 100644 db/repo.go diff --git a/db/common.go b/db/common.go new file mode 100644 index 0000000..742ee70 --- /dev/null +++ b/db/common.go @@ -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) + } +} diff --git a/db/contrib.go b/db/contrib.go new file mode 100644 index 0000000..70f6b1d --- /dev/null +++ b/db/contrib.go @@ -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) + } +} diff --git a/db/repo.go b/db/repo.go new file mode 100644 index 0000000..93fdb31 --- /dev/null +++ b/db/repo.go @@ -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) + } +}