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


Golang gorm.Expr函数代码示例

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


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

示例1: move

func move(db *gorm.DB, value sortingInterface, pos int) error {
	clone := db
	for _, field := range db.NewScope(value).PrimaryFields() {
		if field.DBName != "id" {
			clone = clone.Where(fmt.Sprintf("%s = ?", field.DBName), field.Field.Interface())
		}
	}

	currentPos := value.GetPosition()

	if pos > 0 {
		if results := clone.Model(newModel(value)).
			Where("position > ? AND position <= ?", currentPos, currentPos+pos).
			UpdateColumn("position", gorm.Expr("position - ?", 1)); results.Error == nil {
			value.SetPosition(currentPos + int(results.RowsAffected))
			return clone.Model(value).UpdateColumn("position", gorm.Expr("position + ?", results.RowsAffected)).Error
		}
	} else if pos < 0 {
		if results := clone.Model(newModel(value)).
			Where("position < ? AND position >= ?", currentPos, currentPos+pos).
			UpdateColumn("position", gorm.Expr("position + ?", 1)); results.Error == nil {
			value.SetPosition(currentPos - int(results.RowsAffected))
			return clone.Model(value).UpdateColumn("position", gorm.Expr("position - ?", results.RowsAffected)).Error
		}
	}
	return nil
}
开发者ID:kennylixi,项目名称:qor,代码行数:27,代码来源:sorting.go

示例2: moveDeviceByID

func moveDeviceByID(fromReportItemID uint, toHolderId uint, toHolderType string, quantity int) (err error) {
	var d Device
	var cdIn ClientDeviceIn
	var from, to DeviceHolder
	from, to, d, cdIn, _, _ = fromToDevice(fromReportItemID, toHolderId, toHolderType)

	var fromRi, toRi *ReportItem

	var fcount = 0
	if from != nil {
		fromRi, err = getOrCreateReportItem(from, &d, &cdIn, 0)
		if err != nil {
			log.Println(err)
			return
		}
		fcount = fromRi.Count - quantity
	}

	tcount := 0
	if to != nil {
		toRi, err = getOrCreateReportItem(to, &d, &cdIn, 0)
		if err != nil {
			log.Println(err)
			return
		}
		tcount = toRi.Count + quantity
	}

	if fcount < 0 || tcount < 0 {
		err = errors.New(fmt.Sprintf("数量输入有误"))
		return
	}

	if from != nil {
		err = DB.Model(&fromRi).Where("id = ?", fromRi.ID).UpdateColumn("count", gorm.Expr("count - ?", quantity)).Error
		if err != nil {
			log.Println(err)
			return
		}
	}

	if to != nil {
		err = DB.Model(&toRi).Where("id = ?", toRi.ID).UpdateColumn("count", gorm.Expr("count + ?", quantity)).Error
		if err != nil {
			log.Println(err)
			return
		}
	}

	return
}
开发者ID:theplant,项目名称:device_management,代码行数:51,代码来源:logic.go

示例3: move

func move(db *gorm.DB, value sortingInterface, pos int) (err error) {
	var startedTransaction bool
	var tx = db.Set("publish:publish_event", true)
	if t := tx.Begin(); t.Error == nil {
		startedTransaction = true
		tx = t
	}

	scope := db.NewScope(value)
	for _, field := range scope.PrimaryFields() {
		if field.DBName != "id" {
			tx = tx.Where(fmt.Sprintf("%s = ?", field.DBName), field.Field.Interface())
		}
	}

	currentPos := value.GetPosition()

	var results *gorm.DB
	if pos > 0 {
		results = tx.Model(newModel(value)).
			Where("position > ? AND position <= ?", currentPos, currentPos+pos).
			UpdateColumn("position", gorm.Expr("position - ?", 1))
	} else {
		results = tx.Model(newModel(value)).
			Where("position < ? AND position >= ?", currentPos, currentPos+pos).
			UpdateColumn("position", gorm.Expr("position + ?", 1))
	}

	if err = results.Error; err == nil {
		var rowsAffected = int(results.RowsAffected)
		if pos < 0 {
			rowsAffected = -rowsAffected
		}
		value.SetPosition(currentPos + rowsAffected)
		err = tx.Model(value).UpdateColumn("position", gorm.Expr("position + ?", rowsAffected)).Error
	}

	// Create Publish Event
	createPublishEvent(tx, value)

	if startedTransaction {
		if err == nil {
			tx.Commit()
		} else {
			tx.Rollback()
		}
	}
	return err
}
开发者ID:NZAOM,项目名称:qor,代码行数:49,代码来源:sorting.go

示例4: TestUpdateColumn

func TestUpdateColumn(t *testing.T) {
	product1 := Product{Code: "product1code", Price: 10}
	product2 := Product{Code: "product2code", Price: 20}
	DB.Save(&product1).Save(&product2).UpdateColumn(map[string]interface{}{"code": "product2newcode", "price": 100})
	if product2.Code != "product2newcode" || product2.Price != 100 {
		t.Errorf("product 2 should be updated with update column")
	}

	var product3 Product
	DB.First(&product3, product1.Id)
	if product3.Code != "product1code" || product3.Price != 10 {
		t.Errorf("product 1 should not be updated")
	}

	DB.First(&product2, product2.Id)
	updatedAt2 := product2.UpdatedAt
	DB.Model(product2).UpdateColumn("code", "update_column_new")
	var product4 Product
	DB.First(&product4, product2.Id)
	if updatedAt2.Format(time.RFC3339Nano) != product4.UpdatedAt.Format(time.RFC3339Nano) {
		t.Errorf("updatedAt should not be updated with update column")
	}

	DB.Model(&product4).UpdateColumn("price", gorm.Expr("price + 100 - 50"))
	var product5 Product
	DB.First(&product5, product4.Id)
	if product5.Price != product4.Price+100-50 {
		t.Errorf("UpdateColumn with expression")
	}
	if product5.UpdatedAt.Format(time.RFC3339Nano) != product4.UpdatedAt.Format(time.RFC3339Nano) {
		t.Errorf("UpdateColumn with expression should not update UpdatedAt")
	}
}
开发者ID:cdevienne,项目名称:gorm,代码行数:33,代码来源:update_test.go

示例5: TestUpdates

func TestUpdates(t *testing.T) {
	product1 := Product{Code: "product1code", Price: 10}
	product2 := Product{Code: "product2code", Price: 10}
	DB.Save(&product1).Save(&product2)
	DB.Model(&product1).Updates(map[string]interface{}{"code": "product1newcode", "price": 100})
	if product1.Code != "product1newcode" || product1.Price != 100 {
		t.Errorf("Record should be updated also with map")
	}

	DB.First(&product1, product1.Id)
	DB.First(&product2, product2.Id)
	updatedAt1 := product1.UpdatedAt
	updatedAt2 := product2.UpdatedAt

	var product3 Product
	DB.First(&product3, product1.Id).Updates(Product{Code: "product1newcode", Price: 100})
	if product3.Code != "product1newcode" || product3.Price != 100 {
		t.Errorf("Record should be updated with struct")
	}

	if updatedAt1.Format(time.RFC3339Nano) != product3.UpdatedAt.Format(time.RFC3339Nano) {
		t.Errorf("updatedAt should not be updated if nothing changed")
	}

	if DB.First(&Product{}, "code = ? and price = ?", product2.Code, product2.Price).RecordNotFound() {
		t.Errorf("Product2 should not be updated")
	}

	if DB.First(&Product{}, "code = ?", "product1newcode").RecordNotFound() {
		t.Errorf("Product1 should be updated")
	}

	DB.Table("products").Where("code in (?)", []string{"product2code"}).Updates(Product{Code: "product2newcode"})
	if !DB.First(&Product{}, "code = 'product2code'").RecordNotFound() {
		t.Errorf("Product2's code should be updated")
	}

	var product4 Product
	DB.First(&product4, product2.Id)
	if updatedAt2.Format(time.RFC3339Nano) != product4.UpdatedAt.Format(time.RFC3339Nano) {
		t.Errorf("updatedAt should be updated if something changed")
	}

	if DB.First(&Product{}, "code = ?", "product2newcode").RecordNotFound() {
		t.Errorf("product2's code should be updated")
	}

	DB.Model(&product4).Updates(map[string]interface{}{"price": gorm.Expr("price + ?", 100)})
	var product5 Product
	DB.First(&product5, product4.Id)
	if product5.Price != product4.Price+100 {
		t.Errorf("Updates with expression")
	}
	if product5.UpdatedAt.Format(time.RFC3339Nano) == product4.UpdatedAt.Format(time.RFC3339Nano) {
		t.Errorf("Updates with expression should update UpdatedAt")
	}
}
开发者ID:galeone,项目名称:gorm,代码行数:57,代码来源:update_test.go

示例6: Add

func (*PersonAddress) Add(handler gorm.JoinTableHandlerInterface, db *gorm.DB, foreignValue interface{}, associationValue interface{}) error {
	return db.Where(map[string]interface{}{
		"person_id":  db.NewScope(foreignValue).PrimaryKeyValue(),
		"address_id": db.NewScope(associationValue).PrimaryKeyValue(),
	}).Assign(map[string]interface{}{
		"person_id":  foreignValue,
		"address_id": associationValue,
		"deleted_at": gorm.Expr("NULL"),
	}).FirstOrCreate(&PersonAddress{}).Error
}
开发者ID:roshats,项目名称:gorm,代码行数:10,代码来源:join_table_test.go

示例7: getSequence

func getSequence(db gorm.DB) (uint64, error) {
	tx := db.Begin()

	if err := tx.Model(&Seq{}).Update("id", gorm.Expr("LAST_INSERT_ID(id + 1)")).Error; err != nil {
		return 0, err
	}
	var id uint64
	r := tx.Raw("SELECT LAST_INSERT_ID()").Row()
	r.Scan(&id)
	return id, nil

}
开发者ID:hachi-eiji,项目名称:go-practice,代码行数:12,代码来源:client.go

示例8: TestSelectWithVariables

func TestSelectWithVariables(t *testing.T) {
	DB.Save(&User{Name: "jinzhu"})

	rows, _ := DB.Table("users").Select("? as fake", gorm.Expr("name")).Rows()

	if !rows.Next() {
		t.Errorf("Should have returned at least one row")
	} else {
		columns, _ := rows.Columns()
		if !reflect.DeepEqual(columns, []string{"fake"}) {
			t.Errorf("Should only contains one column")
		}
	}
}
开发者ID:lue828,项目名称:osinstall-server,代码行数:14,代码来源:query_test.go

示例9: TestOrderAndPluck

func TestOrderAndPluck(t *testing.T) {
	user1 := User{Name: "OrderPluckUser1", Age: 1}
	user2 := User{Name: "OrderPluckUser2", Age: 10}
	user3 := User{Name: "OrderPluckUser3", Age: 20}
	DB.Save(&user1).Save(&user2).Save(&user3)
	scopedb := DB.Model(&User{}).Where("name like ?", "%OrderPluckUser%")

	var user User
	scopedb.Order(gorm.Expr("name = ? DESC", "OrderPluckUser2")).First(&user)
	if user.Name != "OrderPluckUser2" {
		t.Errorf("Order with sql expression")
	}

	var ages []int64
	scopedb.Order("age desc").Pluck("age", &ages)
	if ages[0] != 20 {
		t.Errorf("The first age should be 20 when order with age desc")
	}

	var ages1, ages2 []int64
	scopedb.Order("age desc").Pluck("age", &ages1).Pluck("age", &ages2)
	if !reflect.DeepEqual(ages1, ages2) {
		t.Errorf("The first order is the primary order")
	}

	var ages3, ages4 []int64
	scopedb.Model(&User{}).Order("age desc").Pluck("age", &ages3).Order("age", true).Pluck("age", &ages4)
	if reflect.DeepEqual(ages3, ages4) {
		t.Errorf("Reorder should work")
	}

	var names []string
	var ages5 []int64
	scopedb.Model(User{}).Order("name").Order("age desc").Pluck("age", &ages5).Pluck("name", &names)
	if names != nil && ages5 != nil {
		if !(names[0] == user1.Name && names[1] == user2.Name && names[2] == user3.Name && ages5[2] == 20) {
			t.Errorf("Order with multiple orders")
		}
	} else {
		t.Errorf("Order with multiple orders")
	}

	DB.Model(User{}).Select("name, age").Find(&[]User{})
}
开发者ID:jinzhu,项目名称:gorm,代码行数:44,代码来源:query_test.go

示例10: TestUpdate

func TestUpdate(t *testing.T) {
	product1 := Product{Code: "product1code"}
	product2 := Product{Code: "product2code"}

	DB.Save(&product1).Save(&product2).Update("code", "product2newcode")

	if product2.Code != "product2newcode" {
		t.Errorf("Record should be updated")
	}

	DB.First(&product1, product1.Id)
	DB.First(&product2, product2.Id)
	updatedAt1 := product1.UpdatedAt

	if DB.First(&Product{}, "code = ?", product1.Code).RecordNotFound() {
		t.Errorf("Product1 should not be updated")
	}

	if !DB.First(&Product{}, "code = ?", "product2code").RecordNotFound() {
		t.Errorf("Product2's code should be updated")
	}

	if DB.First(&Product{}, "code = ?", "product2newcode").RecordNotFound() {
		t.Errorf("Product2's code should be updated")
	}

	DB.Table("products").Where("code in (?)", []string{"product1code"}).Update("code", "product1newcode")

	var product4 Product
	DB.First(&product4, product1.Id)
	if updatedAt1.Format(time.RFC3339Nano) != product4.UpdatedAt.Format(time.RFC3339Nano) {
		t.Errorf("updatedAt should be updated if something changed")
	}

	if !DB.First(&Product{}, "code = 'product1code'").RecordNotFound() {
		t.Errorf("Product1's code should be updated")
	}

	if DB.First(&Product{}, "code = 'product1newcode'").RecordNotFound() {
		t.Errorf("Product should not be changed to 789")
	}

	if DB.Model(product2).Update("CreatedAt", time.Now().Add(time.Hour)).Error != nil {
		t.Error("No error should raise when update with CamelCase")
	}

	if DB.Model(&product2).UpdateColumn("CreatedAt", time.Now().Add(time.Hour)).Error != nil {
		t.Error("No error should raise when update_column with CamelCase")
	}

	var products []Product
	DB.Find(&products)
	if count := DB.Model(Product{}).Update("CreatedAt", time.Now().Add(2*time.Hour)).RowsAffected; count != int64(len(products)) {
		t.Error("RowsAffected should be correct when do batch update")
	}

	DB.First(&product4, product4.Id)
	updatedAt4 := product4.UpdatedAt
	DB.Model(&product4).Update("price", gorm.Expr("price + ? - ?", 100, 50))
	var product5 Product
	DB.First(&product5, product4.Id)
	if product5.Price != product4.Price+100-50 {
		t.Errorf("Update with expression")
	}
	if product4.UpdatedAt.Format(time.RFC3339Nano) == updatedAt4.Format(time.RFC3339Nano) {
		t.Errorf("Update with expression should update UpdatedAt")
	}
}
开发者ID:cdevienne,项目名称:gorm,代码行数:68,代码来源:update_test.go

示例11: articleHandler

func articleHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	sourceSlug := vars["source_slug"]
	articleSlug := vars["article_slug"]
	articleID := vars["article_id"]
	logger.Info("[article] Find for: source_slug=%s, article_slug:%s, article_id:%s", sourceSlug, articleSlug, articleID)

	var article SerializedArticle

	if db.Select("url").Where(map[string]interface{}{"id": articleID, "slug": articleSlug, "source_slug": sourceSlug}).Limit(1).Find(&article).RecordNotFound() {
		logger.Info("[article] Not found: source_slug=%s, article_slug:%s, article_id:%s", sourceSlug, articleSlug, articleID)
		unknownHandler(w, r)
		return
	}

	go db.Model(&article).Where(map[string]interface{}{"id": articleID, "slug": articleSlug, "source_slug": sourceSlug}).UpdateColumn("total_views", gorm.Expr("total_views + ?", 1))

	http.Redirect(w, r, article.Url, 301)
}
开发者ID:rastasheep,项目名称:utisak-worker,代码行数:19,代码来源:api.go

示例12: GiveOneVoteToAllAccounts

func (s *DatabaseStorage) GiveOneVoteToAllAccounts() error {
	log.Println("Giving vote to all accounts.")
	return s.dbGorm.Model(&account.Account{}).UpdateColumn("vote_bank", gorm.Expr("vote_bank + ?", 1)).Error
}
开发者ID:kiwih,项目名称:heyfyi,代码行数:4,代码来源:fyidb.go

示例13: TestUpdate

func TestUpdate(t *testing.T) {
	product := Product{Code: "Update", Name: "global"}
	checkHasErr(t, dbGlobal.Create(&product).Error)
	sharedDB := dbGlobal.Model(&Product{}).Where("id = ? AND code = ?", product.ID, "Update")

	product.Name = "中文名"
	checkHasErr(t, dbCN.Create(&product).Error)
	checkHasProductInLocale(sharedDB.Where("name = ?", "中文名"), "zh", t)

	product.Name = "English Name"
	checkHasErr(t, dbEN.Create(&product).Error)
	checkHasProductInLocale(sharedDB.Where("name = ?", "English Name"), "en", t)

	product.Name = "新的中文名"
	product.Code = "NewCode // should be ignored when update"
	dbCN.Save(&product)
	checkHasProductInLocale(sharedDB.Where("name = ?", "新的中文名"), "zh", t)

	product.Name = "New English Name"
	product.Code = "NewCode // should be ignored when update"
	dbEN.Save(&product)
	checkHasProductInLocale(sharedDB.Where("name = ?", "New English Name"), "en", t)

	// Check sync columns with UpdateColumn
	dbGlobal.Model(&Product{}).Where("id = ?", product.ID).UpdateColumns(map[string]interface{}{"quantity": gorm.Expr("quantity + ?", 2)})

	var newGlobalProduct Product
	var newENProduct Product
	dbGlobal.Find(&newGlobalProduct, product.ID)
	dbEN.Find(&newENProduct, product.ID)

	if newGlobalProduct.Quantity != product.Quantity+2 || newENProduct.Quantity != product.Quantity+2 {
		t.Errorf("should sync update columns results correctly")
	}

	// Check sync columns with Save
	newGlobalProduct.Quantity = 5
	dbGlobal.Save(&newGlobalProduct)

	var newGlobalProduct2 Product
	var newENProduct2 Product
	dbGlobal.Find(&newGlobalProduct2, product.ID)
	dbEN.Find(&newENProduct2, product.ID)
	if newGlobalProduct2.Quantity != 5 || newENProduct2.Quantity != 5 {
		t.Errorf("should sync update columns results correctly")
	}
}
开发者ID:strogo,项目名称:qor,代码行数:47,代码来源:curd_test.go

示例14: increaseCount

func increaseCount(record *Record) {
	try(db.Model(record).Update("OpenCount", gorm.Expr("open_count + 1")).Error)
}
开发者ID:brainopia,项目名称:shorty,代码行数:3,代码来源:db.go

示例15: UpdateTraffic

func (u *User) UpdateTraffic(storageSize int) error {
	return client.db.Model(u).Where("id = ?", u.id).UpdateColumn("d", gorm.Expr("d  + ?", storageSize)).UpdateColumn("t", time.Now().Unix()).Error
}
开发者ID:orvice,项目名称:shadowsocks-go,代码行数:3,代码来源:mysql.go


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