Skip to content

Commit

Permalink
add 2.0 feature
Browse files Browse the repository at this point in the history
  • Loading branch information
dreamans committed Jan 23, 2019
1 parent 366f656 commit d7791e8
Show file tree
Hide file tree
Showing 39 changed files with 2,440 additions and 79 deletions.
54 changes: 54 additions & 0 deletions config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// Copyright 2019 syncd Author. All Rights Reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package syncd

type (
Config struct {
Serve *ServeConfig
Db *DbConfig
Log *LogConfig
Syncd *SyncdConfig
Mail *MailConfig
}

SyncdConfig struct {
LocalSpace string
RemoteSpace string
Cipher string
}

LogConfig struct {
Path string
}

MailConfig struct {
Enable int
Smtp string
Port int
User string
Pass string
}

ServeConfig struct {
Addr string
ReadTimeout int
WriteTimeout int
IdleTimeout int
}

DbConfig struct {
Unix string
Host string
Port int
Charset string
User string
Pass string
DbName string
TablePrefix string
MaxIdleConns int
MaxOpenConns int
ConnMaxLifeTime int
}
)
56 changes: 56 additions & 0 deletions db.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// Copyright 2019 syncd Author. All Rights Reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package syncd

import (
"fmt"
"time"
"errors"

"github.com/jinzhu/gorm"
_ "github.com/go-sql-driver/mysql"
)

type DB struct {
DbHandler *gorm.DB
cfg *DbConfig
}

func NewDatabase(cfg *DbConfig) *DB {
return &DB{
cfg: cfg,
}
}

func (db *DB) Open() error {
c, err := gorm.Open("mysql", db.parseConnConfig())
if err != nil {
return errors.New(fmt.Sprintf("mysql connect failed, %s", err.Error()))
}

c.LogMode(true)
c.DB().SetMaxIdleConns(db.cfg.MaxIdleConns)
c.DB().SetMaxOpenConns(db.cfg.MaxOpenConns)
c.DB().SetConnMaxLifetime(time.Second * time.Duration(db.cfg.ConnMaxLifeTime))

db.DbHandler = c
return nil
}

func (db *DB) Close() {
db.DbHandler.Close()
}

func (db *DB) parseConnConfig() string {
var connHost string
if db.cfg.Unix != "" {
connHost = fmt.Sprintf("unix(%s)", db.cfg.Unix)
} else {
connHost = fmt.Sprintf("tcp(%s:%d)", db.cfg.Host, db.cfg.Port)
}
s := fmt.Sprintf("%s:%s@%s/%s?charset=%s&parseTime=True&loc=Local", db.cfg.User, db.cfg.Pass, connHost, db.cfg.DbName, db.cfg.Charset)
println(s)
return s
}
5 changes: 5 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
module github.com/dreamans/syncd

require (
github.com/Unknwon/goconfig v0.0.0-20181105214110-56bd8ab18619
github.com/gin-contrib/sse v0.0.0-20170109093832-22d885f9ecc7 // indirect
github.com/gin-gonic/gin v1.3.0
github.com/go-sql-driver/mysql v1.4.1
github.com/golang/protobuf v1.2.0 // indirect
github.com/jinzhu/gorm v1.9.2
github.com/jinzhu/inflection v0.0.0-20180308033659-04140366298a // indirect
github.com/mattn/go-isatty v0.0.4 // indirect
github.com/tinystack/goutil v0.0.0-20190106143837-b22470ba9279
github.com/ugorji/go/codec v0.0.0-20181209151446-772ced7fd4c2 // indirect
gopkg.in/go-playground/validator.v8 v8.18.2 // indirect
gopkg.in/yaml.v2 v2.2.2 // indirect
Expand Down
10 changes: 10 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,11 +1,21 @@
github.com/Unknwon/goconfig v0.0.0-20181105214110-56bd8ab18619 h1:6X8iB881g299aNEv6KXrcjL31iLOH7yA6NXoQX+MbDg=
github.com/Unknwon/goconfig v0.0.0-20181105214110-56bd8ab18619/go.mod h1:wngxua9XCNjvHjDiTiV26DaKDT+0c63QR6H5hjVUUxw=
github.com/gin-contrib/sse v0.0.0-20170109093832-22d885f9ecc7 h1:AzN37oI0cOS+cougNAV9szl6CVoj2RYwzS3DpUQNtlY=
github.com/gin-contrib/sse v0.0.0-20170109093832-22d885f9ecc7/go.mod h1:VJ0WA2NBN22VlZ2dKZQPAPnyWw5XTlK1KymzLKsr59s=
github.com/gin-gonic/gin v1.3.0 h1:kCmZyPklC0gVdL728E6Aj20uYBJV93nj/TkwBTKhFbs=
github.com/gin-gonic/gin v1.3.0/go.mod h1:7cKuhb5qV2ggCFctp2fJQ+ErvciLZrIeoOSOm6mUr7Y=
github.com/go-sql-driver/mysql v1.4.1 h1:g24URVg0OFbNUTx9qqY1IRZ9D9z3iPyi5zKhQZpNwpA=
github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/jinzhu/gorm v1.9.2 h1:lCvgEaqe/HVE+tjAR2mt4HbbHAZsQOv3XAZiEZV37iw=
github.com/jinzhu/gorm v1.9.2/go.mod h1:Vla75njaFJ8clLU1W44h34PjIkijhjHIYnZxMqCdxqo=
github.com/jinzhu/inflection v0.0.0-20180308033659-04140366298a h1:eeaG9XMUvRBYXJi4pg1ZKM7nxc5AfXfojeLLW7O5J3k=
github.com/jinzhu/inflection v0.0.0-20180308033659-04140366298a/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/mattn/go-isatty v0.0.4 h1:bnP0vzxcAdeI1zdubAl5PjU6zsERjGZb7raWodagDYs=
github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/tinystack/goutil v0.0.0-20190106143837-b22470ba9279 h1:rxIxbGfb/ibxaOFhYRozw4Yk7H6OsabMjZ1eo3S61jo=
github.com/tinystack/goutil v0.0.0-20190106143837-b22470ba9279/go.mod h1:EfhqgCLM9We6/X6PNGfv/7z8f0a9Uy8d07X3mW6UQ4Y=
github.com/ugorji/go/codec v0.0.0-20181209151446-772ced7fd4c2 h1:EICbibRW4JNKMcY+LsWmuwob+CRS1BmdRdjphAm9mH4=
github.com/ugorji/go/codec v0.0.0-20181209151446-772ced7fd4c2/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
Expand Down
152 changes: 152 additions & 0 deletions model/model.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
// Copyright 2019 syncd Author. All Rights Reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package model

import (
"fmt"
"strings"

"github.com/jinzhu/gorm"
"github.com/dreamans/syncd"
)

type WhereParam struct {
Field string
Tag string
Prepare interface{}
}

type QueryParam struct {
Fields string
Offset int
Limit int
Order string
Where []WhereParam
}

func Create(model interface{}) bool {
db := syncd.App.DB.DbHandler.Create(model)
if err := db.Error; err != nil {
syncd.App.Logger.Warning("mysql execute error: %s, sql [%v]", err.Error(), db.QueryExpr())
return false
}
return true
}

func GetMulti(model interface{}, query QueryParam) bool {
db := syncd.App.DB.DbHandler.Offset(query.Offset)
if query.Limit > 0 {
db = db.Limit(query.Limit)
}
if query.Fields != "" {
db = db.Select(query.Fields)
}
if query.Order != "" {
db = db.Order(query.Order)
}
db = parseWhereParam(db, query.Where)
db.Find(model)
if err := db.Error; err != nil {
syncd.App.Logger.Warning("mysql query error: %s, sql[%v]", err.Error(), db.QueryExpr())
return false
}
return true
}

func Count(model interface{}, count *int, query QueryParam) bool {
db := syncd.App.DB.DbHandler.Model(model)
db = parseWhereParam(db, query.Where)
db = db.Count(count)
if err := db.Error; err != nil {
syncd.App.Logger.Warning("mysql query error: %s, sql[%v]", err.Error(), db.QueryExpr())
return false
}
return true
}

func Delete(model interface{}, query QueryParam) bool {
if len(query.Where) == 0 {
syncd.App.Logger.Warning("mysql query error: delete failed, where conditions cannot be empty")
return false
}
db := syncd.App.DB.DbHandler.Model(model)
db = parseWhereParam(db, query.Where)
db = db.Delete(model)
if err := db.Error; err != nil {
syncd.App.Logger.Warning("mysql query error: %s, sql[%v]", err.Error(), db.QueryExpr())
return false
}
return true
}

func DeleteByPk(model interface{}) bool {
db := syncd.App.DB.DbHandler.Model(model)
db.Delete(model)
if err := db.Error; err != nil {
syncd.App.Logger.Warning("mysql query error: %s, sql[%v]", err.Error(), db.QueryExpr())
return false
}
return true
}

func GetOne(model interface{}, query QueryParam) bool {
db := syncd.App.DB.DbHandler.Model(model)
if query.Fields != "" {
db = db.Select(query.Fields)
}
db = parseWhereParam(db, query.Where)
db = db.First(model)
if err := db.Error; err != nil && !db.RecordNotFound() {
syncd.App.Logger.Warning("mysql query error: %s, sql[%v]", err.Error(), db.QueryExpr())
return false
}
return true
}

func GetByPk(model interface{}, id interface{}) bool {
db := syncd.App.DB.DbHandler.Model(model)
db.First(model, id)
if err := db.Error; err != nil && !db.RecordNotFound() {
syncd.App.Logger.Warning("mysql query error: %s sql[%v]", err.Error(), db.QueryExpr())
return false
}
return true
}

func UpdateByPk(model interface{}) bool {
db := syncd.App.DB.DbHandler.Model(model)
db = db.Updates(model)
if err := db.Error; err != nil {
syncd.App.Logger.Warning("mysql query error: %s, sql[%v]", err.Error(), db.QueryExpr())
return false
}
return true
}

func parseWhereParam(db *gorm.DB, where []WhereParam) *gorm.DB {
if len(where) == 0 {
return db
}
var (
plain []string
prepare []interface{}
)
for _, w := range where {
tag := w.Tag
if tag == "" {
tag = "="
}
var plainFmt string
switch tag {
case "IN":
plainFmt = fmt.Sprintf("%s IN (?)", w.Field)
default:
plainFmt = fmt.Sprintf("%s %s ?", w.Field, tag)
}
plain = append(plain, plainFmt)
prepare = append(prepare, w.Prepare)
}
return db.Where(strings.Join(plain, " AND "), prepare...)
}
47 changes: 47 additions & 0 deletions model/server.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// Copyright 2019 syncd Author. All Rights Reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package model

import(
"time"
)

type Server struct {
ID int `gorm:"primary_key"`
GroupId int `gorm:"type:int(11);not null;default:0"`
Name string `gorm:"type:varchar(100);not null;default:''"`
Ip string `gorm:"type:varchar(100);not null;default:''"`
SSHPort int `gorm:"type:int(11);not null;default:0"`
Ctime int `gorm:"type:int(11);not null;default:0"`
}

func (m *Server) TableName() string {
return "syd_server"
}

func (m *Server) Create() bool {
m.Ctime = int(time.Now().Unix())
return Create(m)
}

func (m *Server) Update() bool {
return UpdateByPk(m)
}

func (m *Server) List(query QueryParam) ([]Server, bool) {
var data []Server
ok := GetMulti(&data, query)
return data, ok
}

func (m *Server) Count(query QueryParam) (int, bool) {
var count int
ok := Count(m, &count, query)
return count, ok
}

func (s *Server) Delete() bool {
return DeleteByPk(s)
}
48 changes: 48 additions & 0 deletions model/server_group.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// Copyright 2019 syncd Author. All Rights Reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package model

import (
"time"
)

type ServerGroup struct {
ID int `gorm:"primary_key"`
Name string `gorm:"type:varchar(100);not null;default:''"`
Ctime int `gorm:"type:int(11);not null;default:0"`
}

func (m *ServerGroup) TableName() string {
return "syd_server_group"
}

func (m *ServerGroup) Create() bool {
m.Ctime = int(time.Now().Unix())
return Create(m)
}

func (m *ServerGroup) Update() bool {
return UpdateByPk(m)
}

func (m *ServerGroup) List(query QueryParam) ([]ServerGroup, bool) {
var data []ServerGroup
ok := GetMulti(&data, query)
return data, ok
}

func (m *ServerGroup) Count(query QueryParam) (int, bool) {
var count int
ok := Count(m, &count, query)
return count, ok
}

func (m *ServerGroup) Delete() bool {
return DeleteByPk(m)
}

func (m *ServerGroup) Get(id int) bool {
return GetByPk(m, id)
}
Loading

0 comments on commit d7791e8

Please sign in to comment.