当前位置: 首页>>代码示例>>Golang>>正文


Golang DB.Save方法代码示例

本文整理汇总了Golang中github.com/jinzhu/gorm.DB.Save方法的典型用法代码示例。如果您正苦于以下问题:Golang DB.Save方法的具体用法?Golang DB.Save怎么用?Golang DB.Save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在github.com/jinzhu/gorm.DB的用法示例。


在下文中一共展示了DB.Save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: saveBinary

// SaveBinary will efficently save a binary and it's associated parts.
// Having to do this for efficency is probably a good sign that I should just
// use sqlx or something.
func saveBinary(tx *gorm.DB, b *types.Binary) error {
	var txerr error
	if tx.NewRecord(b) {
		parts := b.Parts
		b.Parts = []types.Part{}
		txerr = tx.Save(b).Error
		if txerr != nil {
			return txerr
		}
		pids := make([]int64, len(parts))
		for i, p := range parts {
			pids[i] = p.ID
		}
		txerr = tx.Model(types.Part{}).Where("id IN (?)", pids).Updates(map[string]interface{}{"binary_id": b.ID}).Error
		if txerr != nil {
			return txerr
		}
	} else {
		pids := make([]int64, len(b.Parts))
		for i, p := range b.Parts {
			pids[i] = p.ID
		}
		txerr = tx.Model(types.Part{}).Where("id IN (?)", pids).Updates(map[string]interface{}{"binary_id": b.ID}).Error
		if txerr != nil {
			return txerr
		}

	}
	return nil
}
开发者ID:hobeone,项目名称:gonab,代码行数:33,代码来源:binaries.go

示例2: ChangePassword

func ChangePassword(username string, newpassword string, db *gorm.DB) (int, error) {
	var user User
	var err error

	dbErr := db.Where(&User{UserName: username}).Find(&user).Error
	if dbErr != nil {
		if dbErr == gorm.RecordNotFound {
			WARNING.Println(UnregisteredUser.Error() + " ,username: " + username)
			return 401, UnregisteredUser
		} else {
			ERROR.Println(dbErr.Error())
			return 500, DatabaseError
		}
	}

	user.Password, err = EncryptPassword(newpassword)
	if err != nil {
		ERROR.Println(err.Error())
		return 500, EncryptionError
	}

	db.Save(&user)
	updatePasswordErr := UpdatePasswordRecordLoginCount(user.Id, false, db)

	if updatePasswordErr != nil {
		ERROR.Println("Password record not updated for userId: " + strconv.FormatInt(user.Id, 10) + ", Error details: " + updatePasswordErr.Error())
		return 500, DatabaseError
	}

	db.Save(&ActivityLog{UserId: user.Id, TokenId: -1, ActivityTime: time.Now().UTC(), Event: PASSWORD_CHANGE})
	TRACE.Println("Password changed for userId: " + strconv.FormatInt(user.Id, 10))

	return 200, nil
}
开发者ID:RodrigoDev,项目名称:gondalf,代码行数:34,代码来源:handlerUtils.go

示例3: CreateNewTokenDbEntry

//Create new token entry in the database
func CreateNewTokenDbEntry(login LoginCredential, db *gorm.DB) (string, error) {
	user := User{}
	db.Where(&User{UserName: login.Username}).Find(&user)

	token := Token{}
	token.UserId = user.Id
	token.Key = uuid.New()
	token.CreatedAt = time.Now().UTC()
	token.LastAccessedAt = time.Now().UTC()
	token.Token = generateSessionToken(login.Username+token.CreatedAt.String(), token.Key)
	token.Active = true
	expiryTime, err := GetTimeOutValue(login.DeviceId)
	if err != nil {
		ERROR.Println(err.Error())
		return "", err
	}

	token.ExpiresAt = expiryTime

	var device DeviceType
	db.Where(&DeviceType{DeviceCode: login.DeviceId}).Find(&device)

	token.DeviceTypeId = device.Id

	db.Save(&token)

	db.Save(&ActivityLog{UserId: token.UserId, TokenId: token.Id, ActivityTime: time.Now().UTC(), Event: LOGIN})

	return token.Token, nil
}
开发者ID:RodrigoDev,项目名称:gondalf,代码行数:31,代码来源:handlerUtils.go

示例4: CreateNewUser

func CreateNewUser(request CreateUserRequest, db *gorm.DB) (int, error) {

	var err error

	if ValidateUniqueUsername(request.Username, db) {

		var user User

		user.UserName = request.Username
		user.LegalName = request.LegalName
		user.Password, err = EncryptPassword(request.Password)
		user.UpdatedAt = time.Now().UTC()
		user.Active = false

		if err != nil {
			ERROR.Println(err.Error())
			return 500, EncryptionError
		}

		db.Save(&user)
		TRACE.Println("New user created, userId: " + strconv.FormatInt(user.Id, 10))

		db.Save(&PasswordRecord{UserId: user.Id, LoginCount: 0})
		TRACE.Println("New password record created, userId: " + strconv.FormatInt(user.Id, 10))

		return 200, nil
	}

	ERROR.Println("Duplicate username " + request.Username + " server validation in create user")
	return 409, DuplicateUsernameError
}
开发者ID:RodrigoDev,项目名称:gondalf,代码行数:31,代码来源:handlerUtils.go

示例5: ValidateSessionToken

func ValidateSessionToken(sessionToken string, db *gorm.DB) (error, int64) {
	var token Token

	dbErr := db.Where(&Token{Token: sessionToken}).Find(&token).Error
	if dbErr != nil {
		if dbErr == gorm.RecordNotFound {
			WARNING.Println(InvalidSessionToken.Error() + ", sessionToken: " + sessionToken)
			return InvalidSessionToken, -1
		}
		ERROR.Println(dbErr.Error() + ", sessionToken: " + sessionToken)
		return dbErr, -1
	}

	if token.Active && token.ExpiresAt.After(time.Now().UTC()) {
		TRACE.Println("SessionToken validated: " + sessionToken)
		timeLeft := token.ExpiresAt.Sub(time.Now().UTC())
		if timeLeft.Minutes() < 5 {
			token.ExpiresAt = token.ExpiresAt.Add(time.Duration(GetTimeExtension()) * time.Minute)
		}
		token.LastAccessedAt = time.Now().UTC()
		db.Save(&token)
		return nil, token.UserId
	}

	return ExpiredSessionToken, -1
}
开发者ID:RodrigoDev,项目名称:gondalf,代码行数:26,代码来源:handlerUtils.go

示例6: Process

func Process(address *models.Address, db *gorm.DB, key string) error {
	query := fmt.Sprintf("%s, %s, %s, %s, BR, %s", address.Logradouro, address.Bairro, address.Localidade, address.Uf, address.Cep)

	address.Latitude, address.Longitude = getGeocode(query, key)

	return db.Save(address).Error
}
开发者ID:wagnergaldino,项目名称:training,代码行数:7,代码来源:geocode.go

示例7: updateTodoHandler

func updateTodoHandler(r *http.Request, params martini.Params, rendr render.Render, db *gorm.DB) {
	id, err := strconv.Atoi(params["id"])
	if err != nil {
		rendr.Text(http.StatusBadRequest, "Provide a `completed` paramter as a boolean")
		return
	}

	t, err := findTodo(db, &todo{ID: id})
	if err != nil {
		rendr.Text(http.StatusBadRequest, err.Error())
		return
	}

	text := r.FormValue("text")
	if text != "" {
		t.Text = text
	}

	completed := r.FormValue("completed")
	if completed != "" {
		completedBool, err := strconv.ParseBool(completed)
		if err != nil {
			rendr.Text(http.StatusBadRequest, err.Error())
			return
		}
		t.Completed = completedBool
	}

	db.Save(t)
	rendr.JSON(http.StatusOK, t)
}
开发者ID:danihodovic,项目名称:go-martini-gorm-angular-todo,代码行数:31,代码来源:server.go

示例8: AfterSave

// AfterSave invokes required actions after persisting.
func (u *Repo) AfterSave(db *gorm.DB) (err error) {
	tags := Tags{}

	err = db.Model(
		u,
	).Related(
		&tags,
	).Error

	if err != nil {
		return err
	}

	for _, tag := range tags {
		err = db.Save(
			tag,
		).Error

		if err != nil {
			return err
		}
	}

	return nil
}
开发者ID:umschlag,项目名称:umschlag-api,代码行数:26,代码来源:repo.go

示例9: PutContent

func PutContent(db gorm.DB, router *gin.Engine) {
	// PUT /content
	// Update content data by id
	router.PUT("/content/:id", func(c *gin.Context) {
		_id := c.Param("id")
		if id, err := strconv.ParseUint(_id, 10, 64); err == nil {
			var contentData model.ContentData
			if err := c.BindJSON(&contentData); err == nil {
				content := &model.Content{
					ContentData: contentData,
					ContentId:   model.ContentId{Id: id},
				}
				if err := checkDataContent(content.ContentData); err {
					checkContent := &model.Content{
						ContentData: contentData,
						ContentId:   model.ContentId{Id: id},
					}
					if err := db.First(checkContent).Error; err == nil {
						db.Save(&content)
						c.JSON(http.StatusOK, content)
					} else {
						c.AbortWithStatus(http.StatusNotFound)
					}
				} else {
					c.AbortWithStatus(http.StatusBadRequest)
				}
			}
		} else {
			log.Print(err)
			c.AbortWithError(http.StatusBadRequest, err)
		}
	})
}
开发者ID:ali-abdalla,项目名称:humhub-api,代码行数:33,代码来源:content.go

示例10: PutModuleEnabled

func PutModuleEnabled(db gorm.DB, router *gin.Engine) {
	// PUT /module_enabled
	// Update module_enabled data by id
	router.PUT("/module_enabled/:id", func(c *gin.Context) {
		_id := c.Param("id")
		if id, err := strconv.ParseUint(_id, 10, 64); err == nil {
			var module_enabledData model.ModuleEnabledData
			if err := c.BindJSON(&module_enabledData); err == nil {
				module_enabled := &model.ModuleEnabled{
					ModuleEnabledData: module_enabledData,
					ModuleEnabledId:   model.ModuleEnabledId{Id: id},
				}
				if err := checkDataModuleEnabled(module_enabled.ModuleEnabledData); err {
					checkModuleEnabled := &model.ModuleEnabled{
						ModuleEnabledData: module_enabledData,
						ModuleEnabledId:   model.ModuleEnabledId{Id: id},
					}
					if err := db.First(checkModuleEnabled).Error; err == nil {
						db.Save(&module_enabled)
						c.JSON(http.StatusOK, module_enabled)
					} else {
						c.AbortWithStatus(http.StatusNotFound)
					}
				} else {
					c.AbortWithStatus(http.StatusBadRequest)
				}
			}
		} else {
			log.Print(err)
			c.AbortWithError(http.StatusBadRequest, err)
		}
	})
}
开发者ID:ali-abdalla,项目名称:humhub-api,代码行数:33,代码来源:module_enabled.go

示例11: PutProfileFieldCategory

func PutProfileFieldCategory(db gorm.DB, router *gin.Engine) {
	// PUT /profile_field_category
	// Update profile_field_category data by id
	router.PUT("/profile_field_category/:id", func(c *gin.Context) {
		_id := c.Param("id")
		if id, err := strconv.ParseUint(_id, 10, 64); err == nil {
			var profile_field_categoryData model.ProfileFieldCategoryData
			if err := c.BindJSON(&profile_field_categoryData); err == nil {
				profile_field_category := &model.ProfileFieldCategory{
					ProfileFieldCategoryData: profile_field_categoryData,
					ProfileFieldCategoryId:   model.ProfileFieldCategoryId{Id: id},
				}
				if err := checkDataProfileFieldCategory(profile_field_category.ProfileFieldCategoryData); err {
					checkProfileFieldCategory := &model.ProfileFieldCategory{
						ProfileFieldCategoryData: profile_field_categoryData,
						ProfileFieldCategoryId:   model.ProfileFieldCategoryId{Id: id},
					}
					if err := db.First(checkProfileFieldCategory).Error; err == nil {
						db.Save(&profile_field_category)
						c.JSON(http.StatusOK, profile_field_category)
					} else {
						c.AbortWithStatus(http.StatusNotFound)
					}
				} else {
					c.AbortWithStatus(http.StatusBadRequest)
				}
			}
		} else {
			log.Print(err)
			c.AbortWithError(http.StatusBadRequest, err)
		}
	})
}
开发者ID:ali-abdalla,项目名称:humhub-api,代码行数:33,代码来源:profile_field_category.go

示例12: PutUrlOembed

func PutUrlOembed(db gorm.DB, router *gin.Engine) {
	// PUT /url_oembed
	// Update url_oembed data by id
	router.PUT("/url_oembed/:id", func(c *gin.Context) {
		_id := c.Param("id")
		if id, err := strconv.ParseUint(_id, 10, 64); err == nil {
			var url_oembedData model.UrlOembedData
			if err := c.BindJSON(&url_oembedData); err == nil {
				url_oembed := &model.UrlOembed{
					UrlOembedData: url_oembedData,
					UrlOembedId:   model.UrlOembedId{Id: id},
				}
				if err := checkDataUrlOembed(url_oembed.UrlOembedData); err {
					checkUrlOembed := &model.UrlOembed{
						UrlOembedData: url_oembedData,
						UrlOembedId:   model.UrlOembedId{Id: id},
					}
					if err := db.First(checkUrlOembed).Error; err == nil {
						db.Save(&url_oembed)
						c.JSON(http.StatusOK, url_oembed)
					} else {
						c.AbortWithStatus(http.StatusNotFound)
					}
				} else {
					c.AbortWithStatus(http.StatusBadRequest)
				}
			}
		} else {
			log.Print(err)
			c.AbortWithError(http.StatusBadRequest, err)
		}
	})
}
开发者ID:ali-abdalla,项目名称:humhub-api,代码行数:33,代码来源:url_oembed.go

示例13: PutSpaceSetting

func PutSpaceSetting(db gorm.DB, router *gin.Engine) {
	// PUT /space_setting
	// Update space_setting data by id
	router.PUT("/space_setting/:id", func(c *gin.Context) {
		_id := c.Param("id")
		if id, err := strconv.ParseUint(_id, 10, 64); err == nil {
			var space_settingData model.SpaceSettingData
			if err := c.BindJSON(&space_settingData); err == nil {
				space_setting := &model.SpaceSetting{
					SpaceSettingData: space_settingData,
					SpaceSettingId:   model.SpaceSettingId{Id: id},
				}
				if err := checkDataSpaceSetting(space_setting.SpaceSettingData); err {
					checkSpaceSetting := &model.SpaceSetting{
						SpaceSettingData: space_settingData,
						SpaceSettingId:   model.SpaceSettingId{Id: id},
					}
					if err := db.First(checkSpaceSetting).Error; err == nil {
						db.Save(&space_setting)
						c.JSON(http.StatusOK, space_setting)
					} else {
						c.AbortWithStatus(http.StatusNotFound)
					}
				} else {
					c.AbortWithStatus(http.StatusBadRequest)
				}
			}
		} else {
			log.Print(err)
			c.AbortWithError(http.StatusBadRequest, err)
		}
	})
}
开发者ID:ali-abdalla,项目名称:humhub-api,代码行数:33,代码来源:space_setting.go

示例14: AfterSave

// AfterSave invokes required actions after persisting.
func (u *Registry) AfterSave(db *gorm.DB) (err error) {
	orgs := Orgs{}

	err = db.Model(
		u,
	).Related(
		&orgs,
	).Error

	if err != nil {
		return err
	}

	for _, org := range orgs {
		err = db.Save(
			org,
		).Error

		if err != nil {
			return err
		}
	}

	return nil
}
开发者ID:umschlag,项目名称:umschlag-api,代码行数:26,代码来源:registry.go

示例15: PutUserHttpSession

func PutUserHttpSession(db gorm.DB, router *gin.Engine) {
	// PUT /user_http_session
	// Update user_http_session data by id
	router.PUT("/user_http_session/:id", func(c *gin.Context) {
		_id := c.Param("id")
		if id, err := strconv.ParseUint(_id, 10, 64); err == nil {
			var user_http_sessionData model.UserHttpSessionData
			if err := c.BindJSON(&user_http_sessionData); err == nil {
				user_http_session := &model.UserHttpSession{
					UserHttpSessionData: user_http_sessionData,
					UserHttpSessionId:   model.UserHttpSessionId{Id: id},
				}
				if err := checkDataUserHttpSession(user_http_session.UserHttpSessionData); err {
					checkUserHttpSession := &model.UserHttpSession{
						UserHttpSessionData: user_http_sessionData,
						UserHttpSessionId:   model.UserHttpSessionId{Id: id},
					}
					if err := db.First(checkUserHttpSession).Error; err == nil {
						db.Save(&user_http_session)
						c.JSON(http.StatusOK, user_http_session)
					} else {
						c.AbortWithStatus(http.StatusNotFound)
					}
				} else {
					c.AbortWithStatus(http.StatusBadRequest)
				}
			}
		} else {
			log.Print(err)
			c.AbortWithError(http.StatusBadRequest, err)
		}
	})
}
开发者ID:ali-abdalla,项目名称:humhub-api,代码行数:33,代码来源:user_http_session.go


注:本文中的github.com/jinzhu/gorm.DB.Save方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。