switch db tool to self create

This commit is contained in:
Jay 2018-04-20 14:33:52 +08:00
parent 3df7291d56
commit a3dae8424b
4 changed files with 42 additions and 25 deletions

View File

@ -17,7 +17,8 @@ func main() {
log.Fatal(err)
}
server = routes.NewServ()
_, err = models.NewDB()
x, err := models.NewDB()
defer x.Close()
if err != nil {
log.Fatal(err)
}

View File

@ -1,7 +1,10 @@
package models
import (
"errors"
"time"
"git.trj.tw/golang/utils/dbtool"
)
// Account - Account table struct
@ -18,18 +21,24 @@ type Account struct {
// GetAllAccount - all account
func GetAllAccount() ([]Account, error) {
var accs []Account
err := x.Table("account").Find(&accs)
return accs, err
rows, err := x.Query(`select "id", "account", "password", "nick", "email", "ctime", "mtime" from "public"."account" where 1`)
if err != nil {
return nil, err
}
err = dbtool.ScanToStructAll(rows, &accs)
return accs, nil
}
// GetAccount -
func GetAccount(account string) (acc *Account, err error) {
acc = &Account{
Account: account,
acc = &Account{}
rows, err := x.Query(`select "id", "account", "password", "nick", "email", "ctime", "mtime" from "public"."account" where "account" = $1`, account)
if err != nil {
return nil, err
}
ok, err := acc.Get()
ok, err := dbtool.ScanToStruct(rows, acc)
if err != nil || !ok {
return nil, err
}
@ -39,7 +48,12 @@ func GetAccount(account string) (acc *Account, err error) {
// Get -
func (a *Account) Get() (bool, error) {
ok, err := x.Table("account").Get(a)
rows, err := x.Query(`select "id", "account", "password", "nick", "email", "ctime", "mtime" from "public"."account" where "account" = $1`, a.Account)
if err != nil {
return false, err
}
ok, err := dbtool.ScanToStruct(rows, a)
if err != nil {
return false, err
}
@ -49,6 +63,19 @@ func (a *Account) Get() (bool, error) {
// Create -
func (a *Account) Create() error {
_, err := x.Table("account").Insert(a)
return err
row, err := x.Query(`insert into "public"."account"
("account", "password", "nick", "email") values ($1, $2, $3, $4) returning *`, a.Account, a.Password, a.Nick, a.Email)
if err != nil {
return err
}
ok, err := dbtool.ScanToStruct(row, a)
if err != nil {
return err
}
if !ok {
return errors.New("data returning fail")
}
return nil
}

View File

@ -1,18 +1,16 @@
package models
import (
"fmt"
"database/sql"
"github.com/go-xorm/xorm"
_ "github.com/lib/pq"
)
var x *xorm.Engine
var x *sql.DB
// NewDB - db object
func NewDB() (*xorm.Engine, error) {
func NewDB() (*sql.DB, error) {
var err error
x, err = xorm.NewEngine("postgres", fmt.Sprintf("postgres://%s@%s/%s?sslmode=disable", "postgres", "localhost", "gallery"))
x.ShowSQL(true)
x, err = sql.Open("postgres", "user=postgres host=localhost sslmode=disable dbname=gallery")
return x, err
}

View File

@ -166,14 +166,5 @@ func UserSignup(c *context.Context) {
return
}
ok, err := acc.Get()
if !ok {
c.ServerError(nil)
return
}
log.Println(acc.ID)
c.Success(nil)
}