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 15:19:32 +00:00
|
|
|
db *sqlx.DB
|
|
|
|
priorityQueue = make(chan func())
|
|
|
|
delayedQueue = 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 15:19:32 +00:00
|
|
|
func Now(fun func()) {
|
|
|
|
priorityQueue <- fun
|
|
|
|
}
|
|
|
|
|
|
|
|
func Later(fun func()) {
|
|
|
|
delayedQueue <- fun
|
2015-03-21 14:10:50 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func processQueue() {
|
|
|
|
for {
|
2015-03-21 15:19:32 +00:00
|
|
|
var fun func()
|
|
|
|
select {
|
|
|
|
case fun = <-priorityQueue:
|
|
|
|
case fun = <-delayedQueue:
|
|
|
|
}
|
|
|
|
fun()
|
2015-03-21 14:10:50 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-03-21 14:58:40 +00:00
|
|
|
func measure(start time.Time, op string) {
|
2015-03-06 13:35:13 +00:00
|
|
|
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"
|
2015-03-21 14:58:40 +00:00
|
|
|
defer panic(err)
|
2015-03-06 13:35:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
log.Printf("Operation %s %s; time: %d (%dms)\n", op, outcome, duration, duration/1000000)
|
|
|
|
}
|