Skip to content

Optimistic Lock in BeforeUpdate: PK Condition Placement Affecting DB Plan Efficiency #7427

Open
@ZhengweiHou

Description

@ZhengweiHou

Your Question

  1. optimistic lock hook
func (h *Hzw) BeforeUpdate(tx *gorm.DB) (err error) {
	cv := h.Version
	h.Version++

	nExprs := tx.Statement.BuildCondition("VERSION", cv)
	newwhere := clause.Where{Exprs: nExprs}
	tx.Statement.AddClause(newwhere) // TODO version条件放在第一个条件,索引性能存在问题

	return
}
  1. final sql
 UPDATE hzw SET NAME='111',AGE=56,VERSION=50 WHERE VERSION = 49 AND ID = 1

Implementing optimistic lock logic in BeforeUpdate, but the final generated update statement's primary key condition is at the end, which will affect the efficiency of the database execution plan.

The document you expected this should be explained

Perhaps we can adjust the logic of handling primary key conditions in callbacks.update.go ConvertToAssignments

Expected answer

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions