github.com/octohelm/storage@v0.0.0-20240516030302-1ac2cc1ea347/pkg/sqlbuilder/stmt_update.go (about) 1 package sqlbuilder 2 3 import ( 4 "context" 5 6 "github.com/pkg/errors" 7 ) 8 9 var ( 10 UpdateNeedLimitByWhere = errors.New("no where limit for update") 11 ) 12 13 func Update(table Table, modifiers ...string) *StmtUpdate { 14 return &StmtUpdate{ 15 table: table, 16 modifiers: modifiers, 17 } 18 } 19 20 type StmtUpdate struct { 21 table Table 22 modifiers []string 23 assignments []Assignment 24 additions []Addition 25 } 26 27 func (s *StmtUpdate) IsNil() bool { 28 return s == nil || IsNilExpr(s.table) || len(s.assignments) == 0 29 } 30 31 func (s StmtUpdate) Set(assignments ...Assignment) *StmtUpdate { 32 s.assignments = assignments 33 return &s 34 } 35 36 func (s StmtUpdate) Where(c SqlExpr, additions ...Addition) *StmtUpdate { 37 s.additions = []Addition{Where(c)} 38 if len(additions) > 0 { 39 s.additions = append(s.additions, additions...) 40 } 41 return &s 42 } 43 44 func (s *StmtUpdate) Ex(ctx context.Context) *Ex { 45 e := Expr("UPDATE") 46 47 if len(s.modifiers) > 0 { 48 for i := range s.modifiers { 49 e.WriteQueryByte(' ') 50 e.WriteQuery(s.modifiers[i]) 51 } 52 } 53 54 e.WriteQueryByte(' ') 55 e.WriteExpr(s.table) 56 e.WriteQuery(" SET ") 57 58 WriteAssignments(e, s.assignments...) 59 WriteAdditions(e, s.additions...) 60 61 return e.Ex(ctx) 62 }