github.com/yongjacky/phoenix-go-orm-builder@v0.3.5/builder_update.go (about) 1 // Copyright 2016 The Xorm Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package builder 6 7 import ( 8 "fmt" 9 ) 10 11 // UpdateCond defines an interface that cond could be used with update 12 type UpdateCond interface { 13 IsValid() bool 14 OpWriteTo(op string, w Writer) error 15 } 16 17 // Update creates an update Builder 18 func Update(updates ...Cond) *Builder { 19 builder := &Builder{cond: NewCond()} 20 return builder.Update(updates...) 21 } 22 23 func (b *Builder) updateWriteTo(w Writer) error { 24 if len(b.from) <= 0 { 25 return ErrNoTableName 26 } 27 if len(b.updates) <= 0 { 28 return ErrNoColumnToUpdate 29 } 30 31 if _, err := fmt.Fprintf(w, "UPDATE %s SET ", b.from); err != nil { 32 return err 33 } 34 35 for i, s := range b.updates { 36 37 if err := s.OpWriteTo(",", w); err != nil { 38 return err 39 } 40 41 if i != len(b.updates)-1 { 42 if _, err := fmt.Fprint(w, ","); err != nil { 43 return err 44 } 45 } 46 } 47 48 if !b.cond.IsValid() { 49 return nil 50 } 51 52 if _, err := fmt.Fprint(w, " WHERE "); err != nil { 53 return err 54 } 55 56 return b.cond.WriteTo(w) 57 }