Use sqlx
This commit is contained in:
parent
1bcebaed59
commit
255b6879c7
22
db/common.go
22
db/common.go
|
@ -1,24 +1,28 @@
|
|||
package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
"github.com/jmoiron/sqlx"
|
||||
"github.com/jmoiron/sqlx/reflectx"
|
||||
)
|
||||
|
||||
var (
|
||||
conn *sql.DB
|
||||
stmts map[string]*sql.Stmt
|
||||
conn *sqlx.DB
|
||||
stmts map[string]*sqlx.Stmt
|
||||
)
|
||||
|
||||
func Connect(uri string) (err error) {
|
||||
conn, err = sql.Open("mysql", uri)
|
||||
stmts = map[string]*sql.Stmt{}
|
||||
func Connect(params string) (err error) {
|
||||
conn, err = sqlx.Connect("mysql", params)
|
||||
|
||||
conn.Mapper = reflectx.NewMapperFunc("json", strings.ToLower)
|
||||
stmts = map[string]*sqlx.Stmt{}
|
||||
return
|
||||
}
|
||||
|
||||
func stmt(query string) *sql.Stmt {
|
||||
func stmt(query string) *sqlx.Stmt {
|
||||
if stmt, ok := stmts[query]; ok {
|
||||
return stmt
|
||||
} else {
|
||||
|
@ -28,8 +32,8 @@ func stmt(query string) *sql.Stmt {
|
|||
}
|
||||
}
|
||||
|
||||
func prepareStatement(query string) *sql.Stmt {
|
||||
if stmt, err := conn.Prepare(query); err == nil {
|
||||
func prepareStatement(query string) *sqlx.Stmt {
|
||||
if stmt, err := conn.Preparex(query); err == nil {
|
||||
return stmt
|
||||
} else {
|
||||
fmt.Println(query)
|
||||
|
|
23
db/org.go
23
db/org.go
|
@ -2,28 +2,19 @@ package db
|
|||
|
||||
type (
|
||||
Org struct {
|
||||
Login string
|
||||
Descr string
|
||||
ID int64
|
||||
AvatarURL string
|
||||
Login string `json:"login"`
|
||||
Descr string `json:"descr"`
|
||||
ID int64 `json:"id"`
|
||||
AvatarURL string `json:"avatar_url"`
|
||||
}
|
||||
)
|
||||
|
||||
const (
|
||||
userOrgsQuery = "select org from members where user = ?"
|
||||
userOrgsQuery = "select o.* from members m join orgs o on o.login = m.org where user = ?"
|
||||
)
|
||||
|
||||
func UserOrgs(login string) (orgs []string) {
|
||||
if res, err := stmt(userOrgsQuery).Query(login); err == nil {
|
||||
defer res.Close()
|
||||
for res.Next() {
|
||||
var org string
|
||||
if err := res.Scan(&org); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
orgs = append(orgs, org)
|
||||
}
|
||||
} else {
|
||||
func UserOrgs(login string) (orgs []*Org) {
|
||||
if err := stmt(userOrgsQuery).Select(&orgs, login); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return
|
||||
|
|
Loading…
Reference in New Issue