Skip to content

Commit

Permalink
add sql
Browse files Browse the repository at this point in the history
Rabbbit committed Jan 2, 2021
1 parent 2f6ccdd commit 402e67f
Showing 9 changed files with 140 additions and 19 deletions.
3 changes: 1 addition & 2 deletions context.go
Original file line number Diff line number Diff line change
@@ -150,9 +150,8 @@ func (c *contextImp) abort() {
}
func (c *contextImp) renderJSON(code int, obj interface{}) error {
defer c.abort()
c.resWriter.Header().Add("Content-Type", "application/json; charset=utf-8")
c.resWriter.WriteHeader(code)
header := c.resWriter.Header()
header["Content-Type"] = []string{"application/javascript; charset=utf-8"}
jsonBytes, err := json.Marshal(obj)
if err != nil {
return err
19 changes: 13 additions & 6 deletions core/db/db.go
Original file line number Diff line number Diff line change
@@ -8,28 +8,35 @@ import (
)

type MySQLDb interface {
Table(ctx rest.Context, name string) whereSQL
Table(ctx rest.Context, name string) interface {
whereSQL
insertSQL
}
}

var _ MySQLDb = &dbImp{}

type dbImp struct {
db *gorm.DB
*whereSQLImp
*insertSQLImp
}

func (d *dbImp) Table(ctx rest.Context, name string) whereSQL {
func (d *dbImp) Table(ctx rest.Context, name string) interface {
insertSQL
whereSQL
} {
d.db = d.db.WithContext(ctx).Session(&gorm.Session{NewDB: true}).Table(name)
w := &whereSQLImp{db:d.db}
d.whereSQLImp = w
return d.whereSQLImp
d.whereSQLImp = &whereSQLImp{db: d.db}
d.insertSQLImp = &insertSQLImp{db: d.db}
return d
}

func Open(dsn string) (MySQLDb, error) {
m := &dbImp{}
var err error
m.db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
Logger: logger.Default.LogMode(logger.Info),
Logger: logger.Default.LogMode(logger.Silent),
})
return m, err
}
12 changes: 11 additions & 1 deletion core/db/deleteSQL.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package db

import (
"github.com/gozelus/zelus_rest"
"gorm.io/gorm"
)

@@ -12,7 +13,16 @@ type deleteSQLImp struct {
}

func (d *deleteSQLImp) Delete(dest interface{}) error {
return d.db.Delete(dest).Error
// 新建一个 Session 用于构建 SQL
db := d.db.Session(&gorm.Session{DryRun: true})
stmt := db.Delete(dest).Statement
sql := db.Dialector.Explain(stmt.SQL.String(), stmt.Vars...)
ctx := d.db.Statement.Context.(rest.Context)

return exec(ctx, sql, func() (int64, error) {
result := d.db.Delete(dest)
return result.RowsAffected, result.Error
})
}

var _ deleteSQL = &deleteSQLImp{}
16 changes: 14 additions & 2 deletions core/db/findSQL.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package db

import "gorm.io/gorm"
import (
"github.com/gozelus/zelus_rest"
"gorm.io/gorm"
)

type findSQL interface {
Find(dest interface{}) error
@@ -13,5 +16,14 @@ type findSQLImp struct {
}

func (f *findSQLImp) Find(dest interface{}) error {
return f.db.Find(dest).Error
// 新建一个 Session 用于构建 SQL
db := f.db.Session(&gorm.Session{DryRun: true})
stmt := db.Find(dest).Statement
sql := db.Dialector.Explain(stmt.SQL.String(), stmt.Vars...)
ctx := f.db.Statement.Context.(rest.Context)

return exec(ctx, sql, func() (int64, error) {
result := f.db.Find(dest)
return result.RowsAffected, result.Error
})
}
16 changes: 14 additions & 2 deletions core/db/insertSQL.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package db

import "gorm.io/gorm"
import (
"github.com/gozelus/zelus_rest"
"gorm.io/gorm"
)

type insertSQL interface {
Insert(dest interface{}) error
@@ -13,5 +16,14 @@ type insertSQLImp struct {
}

func (i *insertSQLImp) Insert(dest interface{}) error {
return i.db.Create(dest).Error
// 新建一个 Session 用于构建 SQL
db := i.db.Session(&gorm.Session{DryRun: true})
stmt := db.Create(dest).Statement
sql := db.Dialector.Explain(stmt.SQL.String(), stmt.Vars...)
ctx := i.db.Statement.Context.(rest.Context)

return exec(ctx, sql, func() (int64, error) {
result := i.db.Create(dest)
return result.RowsAffected, result.Error
})
}
23 changes: 23 additions & 0 deletions core/db/log.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package db

import (
"github.com/gozelus/zelus_rest"
"github.com/gozelus/zelus_rest/logger"
"time"
)

func exec(ctx rest.Context, sql string, f func() (int64, error)) error {
now := time.Now()
rows, err := f()
consume := time.Now().Sub(now).Milliseconds()
if err != nil {
logger.ErrorfWithStackWithContext(ctx, "[%dms] [rows:%d] FAIL SQL : `%s` error for %s", consume, rows, sql, err)
return err
}
if consume <= 200 { // 200ms
logger.InfofWithContext(ctx, "[%dms] [rows:%d] SQL : `%s`", consume, rows, sql)
return nil
}
logger.WarnfWithStackWithContext(ctx, "[%dms] [rows:%d] SLOW SQL : `%s`", rows, consume, sql)
return nil
}
13 changes: 12 additions & 1 deletion core/db/updateSQL.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package db

import (
"github.com/gozelus/zelus_rest"
"gorm.io/gorm"
)

@@ -13,7 +14,17 @@ type updateSQLImp struct {
}

func (u *updateSQLImp) Updates(attrs map[string]interface{}) error {
return u.db.Updates(attrs).Error
// 新建一个 Session 用于构建 SQL
db := u.db.Session(&gorm.Session{DryRun: true})
stmt := db.Updates(attrs).Statement
sql := db.Dialector.Explain(stmt.SQL.String(), stmt.Vars...)
ctx := u.db.Statement.Context.(rest.Context)

return exec(ctx, sql, func() (int64, error) {
result := u.db.Updates(attrs)
return result.RowsAffected, result.Error
})

}

var _ updateSQL = &updateSQLImp{}
40 changes: 39 additions & 1 deletion example/cmd/helloworld.go
Original file line number Diff line number Diff line change
@@ -2,18 +2,56 @@ package main

import (
"github.com/gozelus/zelus_rest"
"github.com/gozelus/zelus_rest/core/db"
"github.com/gozelus/zelus_rest/logger"
_ "gorm.io/driver/mysql"
"log"
"net/http"
)

type User struct {
ID int64 `gorm:"id"`
Nickname string `json:"nickname" gorm:"nickname"`
}

func (u *User) Data() interface{} {
return u
}

func (u *User) ErrorCode() int {
return 200
}

func (User) ErrorMessage() string {
return "ok"
}

func main() {
s := rest.NewServer("localhost", 8080)
if err := s.AddRoute(rest.Route{
Path: "/user/create",
Method: http.MethodPost,
Handler: func(context rest.Context) {
d, _ := db.Open("zhengli:Zhengli_0220@tcp(rm-2ze0o33s1so634285bo.mysql.rds.aliyuncs.com:3306)/podcast?charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai")
u := User{}
var _ rest.Rsp = &User{}
if err := context.JSONBodyBind(&u); err != nil {
logger.Errorf("err : %s", err)
context.RenderJSON(nil)
}
d.Table(context, "users").Insert(&u)
context.RenderJSON(&u)
},
}, rest.Route{
Path: "/user/find",
Method: http.MethodGet,
Handler: func(context rest.Context) {

d, _ := db.Open("zhengli:Zhengli_0220@tcp(rm-2ze0o33s1so634285bo.mysql.rds.aliyuncs.com:3306)/podcast?charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai")
u := User{}
var _ rest.Rsp = &User{}
context.JSONQueryBind(&u)
d.Table(context, "users").Where("id = ?", u.ID).Find(&u)
context.RenderJSON(&u)
},
}); err != nil {
log.Fatal(err)
17 changes: 13 additions & 4 deletions example/db_test.go → example/internal/db_test.go
Original file line number Diff line number Diff line change
@@ -1,23 +1,32 @@
package example
package internal

import (
db2 "github.com/gozelus/zelus_rest/core/db"
"github.com/gozelus/zelus_rest/example/internal/data/db"
"sync"
"testing"
"time"
)

type UsersModel struct {
Id int64 `gorm:"id"` // 用户唯一id
CreateTime time.Time `gorm:"create_time"` // 创建时间
UpdateTime time.Time `gorm:"update_time"` // 更新时间
Nickname string `gorm:"nickname"` // 用户昵称
Avatar string `gorm:"avatar"` // 头像guid
Sign string `gorm:"sign"` // 用户签名
}

func TestGormStatement(t *testing.T) {
db, err := db2.Open("zhengli:Zhengli_0220@tcp(rm-2ze0o33s1so634285bo.mysql.rds.aliyuncs.com:3306)/podcast?charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai")
if err != nil {
t.Fatal(err)
}
var wg sync.WaitGroup
for i := 10 ; i < 20 ; i ++ {
for i := 10; i < 20; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
u := models.UsersModel{}
u := UsersModel{}
if err := db.Table(nil, "users").Where("id = ?", i).Find(&u); err != nil {
t.Fatal(err)
}

0 comments on commit 402e67f

Please sign in to comment.