github.com/eden-framework/sqlx@v0.0.2/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.WriteByte(' ') 42 e.WriteString(s.modifiers[i]) 43 } 44 } 45 46 e.WriteString(" INTO ") 47 e.WriteExpr(s.table) 48 e.WriteByte(' ') 49 50 e.WriteExpr(ExprBy(func(ctx context.Context) *Ex { 51 e := Expr("") 52 53 ctx = ContextWithToggles(ctx, Toggles{ 54 ToggleUseValues: true, 55 }) 56 57 WriteAssignments(e, s.assignments...) 58 59 return e.Ex(ctx) 60 })) 61 62 WriteAdditions(e, s.additions...) 63 64 return e.Ex(ctx) 65 } 66 67 func OnDuplicateKeyUpdate(assignments ...*Assignment) *OtherAddition { 68 assigns := assignments 69 if len(assignments) == 0 { 70 return nil 71 } 72 73 e := Expr("ON DUPLICATE KEY UPDATE ") 74 75 for i := range assigns { 76 if i > 0 { 77 e.WriteString(", ") 78 } 79 e.WriteExpr(assigns[i]) 80 } 81 82 return AsAddition(e) 83 } 84 85 func Returning(expr SqlExpr) *OtherAddition { 86 e := Expr("RETURNING ") 87 if expr == nil || expr.IsNil() { 88 e.WriteByte('*') 89 } else { 90 e.WriteExpr(expr) 91 } 92 return AsAddition(e) 93 }