dao

package
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 17, 2021 License: MIT Imports: 4 Imported by: 0

README

dao

DAO,是数据访问层,负责访问 DB、MC、外部 HTTP 等接口,对上层屏蔽数据访问细节。
后续更换、升级ORM引擎,不影响业务逻辑。能提高测试效率,单元测试时,用Mock对象代替实际的数据库存取,可以成倍地提高测试用例运行速度。
应用 Repository 模式所带来的好处,远高于实现这个模式所增加的代码。只要项目分层,都应当使用这个模式。 Repository是DDD中的概念,强调 Repository 是受Domain(本项目主要是Service)驱动的。 对 Model 层只能单表操作,每一个方法都有一个参数 db *grom.DB 实例,方便事务操作。

具体职责有:

  • SQL 拼接和 DB 访问逻辑
  • DB 的拆库分表逻辑
  • DB 的缓存读写逻辑
  • HTTP 接口调用逻辑

Tips: 如果是返回的列表,尽量返回map,方便service使用。

建议:

  • 推荐使用编写原生SQL
  • 禁止使用连表查询,好处是易扩展,比如分库分表
  • 逻辑部分在程序中进行处理

一个业务一个目录,每一个dao go文件对应一个表操作,比如用户是在user目录下,涉及用户相关的都可以放到这里,
根据不同的模块分离到不同的文件,同时又避免了单个文件func太多的问题。比如:

  • 用户基础服务- user_base_dao.go
  • 用户关注- user_follow_dao.go
  • 用户喜欢- user_like_dao.go
  • 用户评论- user_comment_dao.go

单元测试

关于数据库的单元测试可以用到的几个库:

Reference

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotFound = gorm.ErrRecordNotFound
)

Functions

This section is empty.

Types

type BasePmapLog

type BasePmapLog struct {
	ID             uint      `gorm:"primary_key" json:"id"`
	Model          string    `json:"model"`
	FileName       string    `json:"fileName"`
	EndTime        time.Time `json:"endTime"`
	EndTimeStamp   int64     `json:"endTimeStamp"`
	StartTime      time.Time `json:"startTime"`
	StartTimeStamp int64     `json:"startTimeStamp"`
	Size           float32   `json:"size"`
	SN             string    `json:"sn"`
	// contains filtered or unexported fields
}

func (*BasePmapLog) TableName

func (p *BasePmapLog) TableName() string

TableName 表名

type Dao

type Dao struct {
	// contains filtered or unexported fields
}

Dao mysql struct

func New

func New(db *gorm.DB) *Dao

New new a Dao and return

func (*Dao) Close

func (d *Dao) Close()

Close release mysql connection

func (*Dao) Ping

func (d *Dao) Ping(c context.Context) error

Ping ping mysql

type UserBaseModel

type UserBaseModel struct {
	ID        uint64    `gorm:"primary_key;AUTO_INCREMENT;column:id" json:"id"`
	Username  string    `json:"username" gorm:"column:username;not null" binding:"required" validate:"min=1,max=32"`
	Password  string    `json:"password" gorm:"column:password;not null" binding:"required" validate:"min=5,max=128"`
	Phone     int64     `gorm:"column:phone" json:"phone"`
	Email     string    `gorm:"column:email" json:"email"`
	Avatar    string    `gorm:"column:avatar" json:"avatar"`
	Sex       int       `gorm:"column:sex" json:"sex"`
	CreatedAt time.Time `gorm:"column:created_at" json:"-"`
	UpdatedAt time.Time `gorm:"column:updated_at" json:"-"`
}

UserBaseModel User represents a registered user.

func (*UserBaseModel) Validate

func (u *UserBaseModel) Validate() error

Validate the fields.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL