2015-03-04 19:09:08 +00:00
|
|
|
package db
|
|
|
|
|
|
|
|
import (
|
2015-03-06 13:35:13 +00:00
|
|
|
"log"
|
|
|
|
"time"
|
|
|
|
|
2015-03-04 19:14:11 +00:00
|
|
|
_ "github.com/go-sql-driver/mysql"
|
2015-03-05 16:06:45 +00:00
|
|
|
"github.com/jmoiron/sqlx"
|
|
|
|
"github.com/jmoiron/sqlx/reflectx"
|
2015-03-04 19:09:08 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2015-03-21 14:10:50 +00:00
|
|
|
db *sqlx.DB
|
|
|
|
queryQueue = make(chan func(), 1000)
|
2015-03-04 19:09:08 +00:00
|
|
|
)
|
|
|
|
|
2015-03-05 16:06:45 +00:00
|
|
|
func Connect(params string) (err error) {
|
2015-03-06 12:36:35 +00:00
|
|
|
db, err = sqlx.Connect("mysql", params)
|
2015-03-06 13:23:01 +00:00
|
|
|
db.Mapper = reflectx.NewMapper("json")
|
2015-03-21 14:10:50 +00:00
|
|
|
go processQueue()
|
2015-03-04 19:09:08 +00:00
|
|
|
return
|
|
|
|
}
|
2015-03-06 11:29:52 +00:00
|
|
|
|
|
|
|
func mustExecN(query string, arg interface{}) {
|
2015-03-06 12:36:35 +00:00
|
|
|
if _, err := db.NamedExec(query, arg); err != nil {
|
2015-03-06 11:29:52 +00:00
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func mustSelect(dest interface{}, query string, args ...interface{}) {
|
2015-03-06 12:36:35 +00:00
|
|
|
if err := db.Select(dest, query, args...); err != nil {
|
2015-03-06 11:29:52 +00:00
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
}
|
2015-03-06 13:35:13 +00:00
|
|
|
|
2015-03-08 11:17:56 +00:00
|
|
|
func mustSelectN(dest interface{}, query string, params interface{}) {
|
|
|
|
var stmt *sqlx.NamedStmt
|
|
|
|
var err error
|
|
|
|
if stmt, err = db.PrepareNamed(query); err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
if err = stmt.Select(dest, params); err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-03-21 14:10:50 +00:00
|
|
|
func Queue(fun func()) {
|
|
|
|
queryQueue <- fun
|
|
|
|
}
|
|
|
|
|
|
|
|
func processQueue() {
|
|
|
|
for {
|
|
|
|
fun := <-queryQueue
|
|
|
|
fun()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-03-06 13:35:13 +00:00
|
|
|
func measure(op string, start time.Time) {
|
|
|
|
duration := time.Since(start).Nanoseconds()
|
|
|
|
outcome := "succeeded"
|
2015-03-06 16:29:26 +00:00
|
|
|
err := recover()
|
|
|
|
if err != nil {
|
2015-03-06 13:35:13 +00:00
|
|
|
outcome = "failed"
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Printf("Operation %s %s; time: %d (%dms)\n", op, outcome, duration, duration/1000000)
|
2015-03-06 16:29:26 +00:00
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
2015-03-06 13:35:13 +00:00
|
|
|
}
|