From 255b6879c7957ce88c5dfcc6cd137ea27a26ad67 Mon Sep 17 00:00:00 2001 From: Gregory Eremin Date: Thu, 5 Mar 2015 23:06:45 +0700 Subject: [PATCH] Use sqlx --- db/common.go | 22 +++++++++++++--------- db/org.go | 23 +++++++---------------- 2 files changed, 20 insertions(+), 25 deletions(-) diff --git a/db/common.go b/db/common.go index 92c1ec2..59387cd 100644 --- a/db/common.go +++ b/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) diff --git a/db/org.go b/db/org.go index 36508b8..8d3580b 100644 --- a/db/org.go +++ b/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