go语言gorm实战——基础技术总结

前言:
一个go项目过后,有许多的精华部分、容易违犯go语言常规的部分,总结、记录,以供后续的学习、参考和大家探讨。

1 CRUD

1.1 单个查询、批量查询

// leimin
// 查询指定ID主键查询和版本的数据
func (this *Project) Find(db *gorm.DB) (b bool, err error) {

	db = db.First(this)
	if db.RecordNotFound() {
		return false, nil
	}
	return true, db.Error
}

// leimin
// 批量查询所有匹配数据
func (this *Project) FindAll(db *gorm.DB) (u []Project, err error) {

	db = db.Where("user_id = ?", this.UserID).Find(&u)
	return u, db.Error
}

1.2 模糊查询

func (this *Project) FindListByLikeName(db *gorm.DB) ([]Project, error) {
	var result []Project
	projects := db.Where("name like ?", "%"+this.Name+"%").Find(&result)
	if projects.RecordNotFound() {
		return nil, nil
	}
	return result, db.Error
}

1.3 多条件查询

//获取表单列表
//libing.niu
func (this *Form) FindList(db *gorm.DB) ([]Form, error) {

	var forms []Form
	db.Where("major=? AND app_id=?", this.Major, this.AppID).Find(&forms)
	return forms, db.Error

}

1.4 不等于查询

func (this *User) FuzzySearchByName(db *gorm.DB) (users []User, err error) {
	db.Where("name LIKE ? AND id <> ?", "%"+this.Name+"%", this.ID).Find(&users)
	return users, db.Error
}

1.5 倒叙,获取查询第一个元素

func (this *UserProject) FindByAppIdAndMajorAndUserId(db *gorm.DB) (bool, error) {

	db = db.Order("created_at desc").First(this, "app_id = ? and major = ? and user_id = ? ", this.AppID, this.Major, this.UserID)
	if db.RecordNotFound() {
		return false, nil
	}
	return true, db.Error
}

1.6 单个新增,批量新增

// leimin
// 新增数据
func (this *Project) Create(db *gorm.DB) (err error) {

	return db.Create(this).Error
}

// 批量新增

1.7 单个删除、批量删除

// leimin
//通过结构体删除
func (this *UserProject) Delete(db *gorm.DB) (err error) {
	db = db.Delete(this)
	return db.Error
}
// 批量删除
//leimin
func (this *UserProject) DeleteAll(db *gorm.DB) (err error) {

	return db.Where("app_id = ? AND major = ?", this.AppID, this.Major).
		Delete(UserProject{}).Error
}

1.8 单个修改、批量修改

// leimin
// 修改数据属性
func (this *Project) Update(db *gorm.DB) (err error) {

	return db.Save(this).Error
}

//批量修改
//author: weihong.zhu
func (this *Project) UpdateMinor(db *gorm.DB) error {
	return db.Model(this).Where("major = ?", this.Major).Update("minor", this.Minor).Error
}

2 异常处理

2.1 model层异常

db.Error

2.2 service 层异常

	db, err := orm.CreateDB()
	if err != nil {
		logrus.Errorf("UpdateProject service, orm.CreateDB error :%v\n", err.Error())
		return nil, errors.New("数据库连接异常")
	}
	// 修改完成后,再到数据库获取最新数据,用于封装返回参数
	found, err := project.Find(db)
	if err != nil {
		logrus.Errorf("UpdateProject service, project.Find error :%v\n", err.Error())
		return nil, errors.New("数据库查询异常")
	}
	if !found {
		return nil, errors.New("无数据")
	}

2.3 controller 层异常

// author:leimin
// title:创建应用
// detail:从project表新增一条数据
// return:新增后的数据
func ProjectCreate(c *gin.Context) {

	userId := c.GetHeader(USER_ID)
	name := c.PostForm(NAME)
	appType := c.PostForm(TYPE)

	if userId == "" || name == "" || appType == "" {
		c.JSON(http.StatusOK, response.NewBaseResponseWithMessage(response.ResponseCodeBadRequest, "请求参数异常"))
		return
	}
	//todo 保证返回的值都有值
	pic, suffix, err := getIcon(c)
	if err != nil {
		c.JSON(http.StatusOK, response.NewBaseResponseWithMessage(response.ResponseCodeBadRequest, err.Error()))
		return
	}
	res, err := service.AddProject(name, pic, appType, userId, suffix)
	if err != nil {
		logrus.Error(err)
		c.JSON(http.StatusOK, response.NewBaseResponseWithMessage(response.ResponseCodeInternalServerError, err.Error()))
		return
	}

	//返回id,name,version,type,creator
	c.JSON(http.StatusOK, response.NewBaseResponseOkWithData(*res))
}

3 非空校验

字符串、指针、数组、数字

	ups, err := userProject.FindByUserId(db)
	if err != nil {
		logrus.Errorf("projectList service, userProject.FindByUserId error on row 24:%v\n", err.Error())
		return nil, errors.New("数据库查询异常")
	}
	if len(ups) == 0 {
		return nil, nil
	}
	if str == "" { // 字符串如此判断
		return nil, nil
	}

4 返回参数

// leimin
// 返回参数、其类型提前定义,方法中直接使用
func UpdateProject(appId string, majorCode int, name string, icon []byte, userId string, appType string, fileType string) (re *view.Project, err error) {...}
// 同类型合并
// 基础参数放前边
func UpdateProject(icon []byte, majorCode int, appId ,  name , userId , appType , fileType string) (re *view.Project, err error) {...}


5 去重

// 对象切片去重
func deduplication(list []model.UserProject) (mp map[string]model.UserProject) {

	var dedupMap = make(map[string]model.UserProject)
	for _, v := range list {
		if _, ok := dedupMap[v.AppID+strconv.Itoa(v.Major)]; !ok {
			dedupMap[v.AppID+strconv.Itoa(v.Major)] = v
		}
	}

	return dedupMap
}

6 获取db、获取事务、回滚、提交


// leimin
func AddProject(icon []byte, name , appType , userId , fileType string) (re *view.Project, err error) {

	vp := view.Project{}

	db, err := orm.CreateTx()
	if err != nil {
		logrus.Errorf("projectCreate service, orm.CreateTx error:%v\n", err.Error())
		return nil, errors.New("数据库连接异常")
	}

	project := model.Project{
		Model: model.Model{
			ID: utils.UUID(),
		},
		Major:    1,
		Minor:    1,
		Name:     name,
		Icon:     icon,
		IconType: fileType,
		Type:     appType,
		UserID:   userId,
	}

	err = project.Create(db)
	if err != nil {
		db.Rollback()
		logrus.Errorf("projectCreate service, project.Create error:%v\n", err.Error())
		return nil, errors.New("数据库操作异常")
	}

	userProject := model.UserProject{
		Model: model.Model{
			ID: utils.UUID(),
		},
		AppID:  project.ID,
		Major:  project.Major,
		UserID: project.UserID,
		Type:   "creator",
	}

	err = userProject.Create(db)
	if err != nil {
		db.Rollback()
		logrus.Errorf("projectCreate service, userProject.Create error:%v\n", err.Error())
		return nil, errors.New("数据库操作异常")
	}
	db.Commit()

	vp.ID = project.ID
	vp.Name = project.Name
	vp.Type = project.Type
	vp.Created = true
	vp.Version = strconv.Itoa(project.Major) + "." + strconv.Itoa(project.Minor)
	return &vp, err
}

你可能感兴趣的:(go技术,GoLand,编码)