Пример #1
0
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
}
Пример #2
0
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
}
Пример #3
0
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
}
Пример #4
0
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")
	}
}
Пример #5
0
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")
	}
}
Пример #6
0
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
}
Пример #7
0
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

}
Пример #8
0
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")
		}
	}
}
Пример #9
0
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{})
}
Пример #10
0
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")
	}
}
Пример #11
0
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)
}
Пример #12
0
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
}
Пример #13
0
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")
	}
}
Пример #14
0
func increaseCount(record *Record) {
	try(db.Model(record).Update("OpenCount", gorm.Expr("open_count + 1")).Error)
}
Пример #15
0
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
}
Пример #16
0
func (store *DataStore) addArticle(response http.ResponseWriter, section string, id int) {
	fmt.Println("add")
	tx := db.Begin()
	var current Article
	if tx.Where("id = ?", id).Find(&current).RecordNotFound() {
		tx.Create(&Article{Section: section})
	} else {
		tx.Table("articles").Where("sort_order > ?", current.SortOrder).Update("sort_order", gorm.Expr("sort_order + 1"))
		tx.Create(&Article{Section: section, SortOrder: current.SortOrder + 1})
	}
	tx.Commit()
	writeResponse(response)
}