github.com/kunlun-qilian/sqlx/v3@v3.0.0/builder/stmt_insert.go (about) 1 package builder 2 3 import ( 4 "context" 5 ) 6 7 func Insert(modifiers ...string) *StmtInsert { 8 return &StmtInsert{ 9 modifiers: modifiers, 10 } 11 } 12 13 // https://dev.mysql.com/doc/refman/5.6/en/insert.html 14 type StmtInsert struct { 15 table *Table 16 modifiers []string 17 assignments []*Assignment 18 additions Additions 19 } 20 21 func (s StmtInsert) Into(table *Table, additions ...Addition) *StmtInsert { 22 s.table = table 23 s.additions = additions 24 return &s 25 } 26 27 func (s StmtInsert) Values(cols *Columns, values ...interface{}) *StmtInsert { 28 s.assignments = Assignments{ColumnsAndValues(cols, values...)} 29 return &s 30 } 31 32 func (s *StmtInsert) IsNil() bool { 33 return s == nil || s.table == nil || len(s.assignments) == 0 34 } 35 36 func (s *StmtInsert) Ex(ctx context.Context) *Ex { 37 e := Expr("INSERT") 38 39 if len(s.modifiers) > 0 { 40 for i := range s.modifiers { 41 e.WriteQueryByte(' ') 42 e.WriteQuery(s.modifiers[i]) 43 } 44 } 45 46 e.WriteQuery(" INTO ") 47 e.WriteExpr(s.table) 48 e.WriteQueryByte(' ') 49 50 e.WriteExpr(ExprBy(func(ctx context.Context) *Ex { 51 e := Expr("") 52 e.Grow(len(s.assignments)) 53 54 ctx = ContextWithToggles(ctx, Toggles{ 55 ToggleUseValues: true, 56 }) 57 58 WriteAssignments(e, s.assignments...) 59 60 return e.Ex(ctx) 61 })) 62 63 WriteAdditions(e, s.additions...) 64 65 return e.Ex(ctx) 66 } 67 68 func OnDuplicateKeyUpdate(assignments ...*Assignment) *OtherAddition { 69 assigns := assignments 70 if len(assignments) == 0 { 71 return nil 72 } 73 74 e := Expr("ON DUPLICATE KEY UPDATE ") 75 76 for i := range assigns { 77 if i > 0 { 78 e.WriteQuery(", ") 79 } 80 e.WriteExpr(assigns[i]) 81 } 82 83 return AsAddition(e) 84 } 85 86 func Returning(expr SqlExpr) *OtherAddition { 87 e := Expr("RETURNING ") 88 if expr == nil || expr.IsNil() { 89 e.WriteQueryByte('*') 90 } else { 91 e.WriteExpr(expr) 92 } 93 return AsAddition(e) 94 }