github.com/artisanhe/tools@v1.0.1-0.20210607022958-19a8fef2eb04/sqlx/builder/stmt_update.go (about)

     1  package builder
     2  
     3  import (
     4  	"fmt"
     5  )
     6  
     7  var (
     8  	UpdateNeedLimitByWhere = fmt.Errorf("no where limit for update")
     9  )
    10  
    11  func Update(table *Table) *StmtUpdate {
    12  	return &StmtUpdate{
    13  		table: table,
    14  	}
    15  }
    16  
    17  type StmtUpdate struct {
    18  	table     *Table
    19  	modifiers []string
    20  	Assignments
    21  	*where
    22  	*orderBy
    23  	*limit
    24  	comment string
    25  }
    26  
    27  func (s StmtUpdate) Comment(comment string) *StmtUpdate {
    28  	s.comment = comment
    29  	return &s
    30  }
    31  
    32  func (s *StmtUpdate) Type() StmtType {
    33  	return STMT_UPDATE
    34  }
    35  
    36  func (s StmtUpdate) Modifier(modifiers ...string) *StmtUpdate {
    37  	s.modifiers = append(s.modifiers, modifiers...)
    38  	return &s
    39  }
    40  
    41  func (s StmtUpdate) Set(assignments ...*Assignment) *StmtUpdate {
    42  	if s.Assignments == nil {
    43  		s.Assignments = []*Assignment{}
    44  	}
    45  	s.Assignments = append(s.Assignments, assignments...)
    46  	return &s
    47  }
    48  
    49  func (s StmtUpdate) Where(cond *Condition) *StmtUpdate {
    50  	s.where = (*where)(cond)
    51  	return &s
    52  }
    53  
    54  func (s StmtUpdate) OrderBy(col *Column, orderType OrderType) *StmtUpdate {
    55  	if s.orderBy == nil {
    56  		s.orderBy = &orderBy{}
    57  	}
    58  	s.orderBy = s.orderBy.setBy(col, orderType)
    59  	return &s
    60  }
    61  
    62  func (s StmtUpdate) OrderAscBy(col *Column) *StmtUpdate {
    63  	return s.OrderBy(col, ORDER_ASC)
    64  }
    65  
    66  func (s StmtUpdate) OrderDescBy(col *Column) *StmtUpdate {
    67  	return s.OrderBy(col, ORDER_DESC)
    68  }
    69  
    70  func (s StmtUpdate) Limit(size int32) *StmtUpdate {
    71  	if s.limit == nil {
    72  		s.limit = &limit{}
    73  	}
    74  	s.limit = s.limit.limit(size)
    75  	return &s
    76  }
    77  
    78  func (s *StmtUpdate) Expr() *Expression {
    79  	if s.where == nil {
    80  		return ExprErr(UpdateNeedLimitByWhere)
    81  	}
    82  
    83  	expr := Expr(fmt.Sprintf("%s %s SET", statement(s.comment, "UPDATE", s.modifiers...), s.table.FullName()))
    84  	expr = expr.ConcatBy(" ", s.Assignments)
    85  	expr = expr.ConcatBy(" ", s.where)
    86  	expr = expr.ConcatBy(" ", s.orderBy)
    87  	expr = expr.ConcatBy(" ", s.limit)
    88  
    89  	return expr
    90  }